目录
Class 1:游戏主循环——单例的构建
相关概念
单例模式,是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中应用该模式的类一个类只有一个实例。即一个类只有一个对象实例。
单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。在计算机系统中,线程池、缓存、日志对象、对话框、打印机、显卡的驱动程序对象常被设计成单例。这些应用都或多或少具有资源管理器的功能。每台计算机可以有若干个打印机,但只能有一个Printer Spooler,以避免两个打印作业同时输出到打印机中。每台计算机可以有若干通信端口,系统应当集中管理这些通信端口,以避免一个通信端口同时被两个请求同时调用。总之,选择单例模式就是为了避免不一致状态,避免政出多头。
程序构建
主程序——main.c
#include <stdio.h>
#include "GameFuntion.h"
int main(int argc,char *argv[])
{
float frameRate = 1000.0/60; //帧率
uint32_t startTime = 0;
uint32_t frameTime = 0;
GameFuntion* game = GameInstance(); //单例对象构建
game->init("SDL",640,480);
while(game->running())
{
startTime = SDL_GetTicks();
game->update();
game->render();
game->handleEvents();
frameTime = SDL_GetTicks() - startTime;
if(frameRate - frameTime > 0)
{
SDL_Delay(frameRate - frameTime);
}
}
game->clean();
return 0;
}
单例头文件——GameFunction.h
#ifndef GAMEFUNTION_H_
#define GAMEFUNTION_H_
#include <stdbool.h>
#include "SDL.h"
#pragma comment(lib,"SDL2.lib")
#pragma comment(lib,"SDLmain.lib")
typedef struct GameFuntion
{
SDL_Window* window;
SDL_Renderer* renderer;
SDL_Event events;
bool isRunning;
//声明函数指针
//返回值类型 (*指针变量名) (形参列表)
bool (*init)(const char* title,int w,int h);
void (*clean)();
void (*update)();
void (*render)();
void (*handleEvents)();
bool (*running)();
void (*quit)();
}GameFuntion;
GameFuntion* GameInstance();
#endif
单例源文件——GameFunction.c
#include "GameFuntion.h"
bool init(const char* title,int w,int h); //初始化
void clean(); //清理
void update(); //更新
void render(); //渲染
void handleEvents(); //事件处理
bool running(); //程序运行判定
void quit(); //退出
static GameFuntion* pthis = NULL;//此处定义一个pthis是为了写程序方便,如下面的init等函数可以直接使用pthis
GameFuntion* GameInstance()
{
static GameFuntion game;
if (!pthis)
{
pthis = &game;
pthis->init = init;
pthis->clean = clean;
pthis->update = update;
pthis->render = render;
pthis->handleEvents = handleEvents;
pthis->running = running;
pthis->quit = quit;
}
return pthis;
}
bool init(const char* title,int w,int h)
{
if(SDL_Init(SDL_INIT_EVERYTHING) == 0)
{
SDL_Log("SDL Init");
pthis->window = SDL_CreateWindow(title,SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,w,h,SDL_WINDOW_SHOWN);
if (pthis->window)
{
SDL_Log("Window Created");
}
else
{
printf("SDL_CreateWindow Error:%s \n",SDL_GetError());
return 1;
}
pthis->renderer = SDL_CreateRenderer(pthis->window,-1,0);
if(pthis->renderer)
{
SDL_Log("Renderer Created");
}
else
{
SDL_DestroyWindow(win_0);
printf("SDL_CreateRenderer Error:%s \n",SDL_GetError());
return 1;
}
pthis->isRunning = true;
}
else
{
pthis->isRunning = false;
}
return pthis->isRunning;
}
void clean()
{
SDL_DestroyRenderer(pthis->renderer);
SDL_DestroyWindow(pthis->window);
SDL_Quit();
SDL_Log("SDL Clean");
}
int cnt; //程序测试
void update()
{
cnt++; //程序测试
}
void render()
{
SDL_Log("cnt:%d",cnt) //程序测试
}
void handleEvents()
{
if(SDL_PollEvent(&pthis->events))
{
if(pthis->events.type == SDL_QUIT)
{
quit();
}
}
}
bool running(){return pthis->isRunning;}
void quit(){pthis->isRunning = false;}