|
想要查看内容赶紧注册登陆吧!
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
1.使用继承
2.实现多态性
3.使用抽象基类
4.有效地继承关系设计
一、抽象基类GameObject实现//GameObject.h- #include "LoaderParams.h" //专门用于填充参数的简单类
- //注:没有了load函数,原因是不想为每个新项目创建一个新的load()
- //不同的游戏load的值不同
- //因此,专门定义一个填充参数的类LoaderParams
- //所有游戏中的对象将从这个基类派生
- class GameObject
- {
- public:
- virtual void draw() = 0; //三个纯虚函数,强制派生类必须声明并实现它们
- virtual void update() = 0;
- virtual void clean() = 0;
- protected:
- GameObject(const LoaderParams* pParams) {} //继承后成为私有
- virtual ~GameObject() {}
- };
复制代码
二、参数填充类的实现//LoaderParams.h
- //专门用于填充参数的简单类
- #include <string>
- class LoaderParams
- {
- public:
- LoaderParams(int x, int y,
- int width, int height,
- std::string textureID)
- : m_x(x), m_y(y),
- m_width(width), m_height(height),
- m_textureID(textureID)
- { }
- int getX() const { return m_x; }
- int getY() const { return m_y; }
- int getWidth() const { return m_width; }
- int getHeight() const { return m_height; }
- std::string getTextureID() const { return m_textureID; }
- private:
- int m_x;
- int m_y;
- int m_width;
- int m_height;
- std::string m_textureID;
- };
复制代码
三、将Game类实现为单例,方法同TextureManager类1.public中添加
- static Game* Instance()
- {
- if(s_pInstance == 0)
- {
- s_pInstance = new Game();
- return s_pInstance;
- }
- return s_pInstance;
- }
复制代码 2.将构造、析构放到private中,并添加静态实例指针,以及类体外,加上类型定义
- private:
- Game() {};
- ~Game() {};
- static Game* s_pInstance;
- ...
- };
- typedef Game TheGame;
复制代码 3.Game.cpp中初始化全局Game实例指针
- #include "Game.h"
- Game* Game::s_pInstance = 0;
复制代码 4.为Game.h定义一个返回渲染器指针的内联函数(公有)
- //由于渲染器指针会被外部使用,因此定义一个get方法
- SDL_Renderer* getRenderer() const { return m_pRenderer; }
复制代码 5.在main.cpp中修改如下:
- #include <iostream>
- #include "Game.h"
- //Game* g_game = 0; //全局实例
- //这里演示了基本框架结构
- int main(int argc, char* argv[])
- {
- std::cout << "game init attempt...\n";
- if(TheGame::Instance()->init("Charpter 3", 100, 100, 640, 480, false))
- {
- std::cout << "game init success!\n";
- while(TheGame::Instance()->running()) //开始主循环
- {
- TheGame::Instance()->handleEvents(); //处理输入
- TheGame::Instance()->update(); //计算时间和碰撞
- TheGame::Instance()->render(); //渲染到屏幕
- SDL_Delay(10); //SDL函数,延时10毫秒。有它,可以让cpu占用率低很多
- }
- }else
- {
- std::cout << "game init failure - " << SDL_GetError() << "\n";
- return -1;
- }
- std::cout << "game closing...\n";
- TheGame::Instance()->clean(); //清理资源,退出
- return 0;
- }
复制代码
运行测试:
|
|