SDL Game Development-第3章-1.实现游戏对象管理器(1)Working with Game Objects


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;
}

运行测试:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值