/
Game.cpp
126 lines (101 loc) · 2.49 KB
/
Game.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/**
* Implementation of the Game class.
*
* @author Francis BISSON
*/
// INCLUDES ////////////////////////////////////////////////////////////////////
#include <cstdlib>
#include <ctime>
#include <SDL/SDL.h>
#include "Color.h"
#include "Debug.h"
#include "DisplayContext.h"
#include "Game.h"
#include "KeyboardDevice.h"
#include "Scene.h"
#include "SplashScene.h"
#include "Types.h"
// MACROS //////////////////////////////////////////////////////////////////////
#define USE_FRAMERATE_LIMITER
// IMPLEMENTATION //////////////////////////////////////////////////////////////
Game::Game()
:m_DisplayContext()
,m_KeyboardDevice()
,m_CurrentScene()
,m_Quit(false)
,m_Framerate(this, 60)
,m_DisplayArea(0, 0, 640, 480)
{
}
Game::~Game()
{
}
bool Game::Init()
{
// TODO Load game config
bool init = true;
init = init && m_DisplayContext.Init(m_DisplayArea.GetWidth(), m_DisplayArea.GetHeight());
init = init && m_KeyboardDevice.Init();
SDL_WM_SetCaption("Mugen Formation", NULL);
// Load initial scene
m_CurrentScene.reset( new SplashScene(this) );
init = init && m_CurrentScene->Init();
// Initialize random number generator
srand( time(NULL) );
return init;
}
void Game::Start()
{
DEBUG_ASSERT(m_CurrentScene.get() != NULL);
Uint32 lastTime = SDL_GetTicks();
m_Quit = false;
while(!m_Quit)
{
// CLEAR SCREEN
m_DisplayContext.SetColor(Color::Black);
m_DisplayContext.ClearScreen();
// MANAGE INPUT DEVICES
m_KeyboardDevice.Update();
// MANAGE EVENTS
ManageEvents();
Uint32 currentTime = SDL_GetTicks();
double deltaTime = (double)(currentTime - lastTime) / 1000.0;
lastTime = currentTime;
// MANAGE CURRENT SCENE
m_CurrentScene->Update(deltaTime);
m_Framerate.Update(deltaTime);
// RENDER GAME OBJECTS
m_CurrentScene->Render(&m_DisplayContext);
m_Framerate.Render(&m_DisplayContext);
// FLIP (SWAP) DISPLAY BUFFERS
m_DisplayContext.Flip();
#ifdef USE_FRAMERATE_LIMITER
m_Framerate.LimitFramerate();
#endif
}
}
void Game::ManageEvents()
{
SDL_Event event;
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
m_Quit = true;
break;
}
}
}
void Game::ChangeScene(ScenePtr scene)
{
if(m_CurrentScene)
{
/**
* TODO Implement scenes stack
* i.e. Game scene -> Pause Menu -> Options Menu -> Back to Pause Menu -> Back to Game
*/
m_CurrentScene = scene;
m_CurrentScene->Init();
}
}