-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.cc
72 lines (52 loc) · 1.88 KB
/
game.cc
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
#include "game.hh"
#include "util/exceptions.hh"
#include "geometry/dimensions.hh"
#include "gamestate.hh"
#include <iostream>
#include <chrono>
namespace jesh {
const double kMaxFrameDifference = 1.0 / 20;
// UGLY: game must have a pointer to state because it needs to bootstrap
// without one, because GameState needs a reference to Game.
// A potential fix to this would be to give GameState two methods, isCurrent()
// and getNextState(), which game would poll.
Game::Game(sf::RenderWindow &theWindow) :
window(theWindow),
state(nullptr) {
}
void Game::run() {
namespace chrono = std::chrono;
chrono::steady_clock::time_point lastUpdate = chrono::steady_clock::now();
// State is pseudo-optional because state needs a reference to the game to
// be created.
if (state == nullptr) {
throw_error("Attempt to run game without setting state.");
}
window.setVerticalSyncEnabled(true);
while (window.isOpen()) {
// Oh man, working with times sure is fun.
chrono::steady_clock::time_point now = chrono::steady_clock::now();
double frameDifference = chrono::duration_cast<chrono::duration<double>>(now - lastUpdate).count();
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
return;
} else if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
window.close();
return;
}
}
window.clear(sf::Color::Black);
while (frameDifference > 0) {
state->advance(std::min(frameDifference, kMaxFrameDifference));
window.display();
frameDifference -= kMaxFrameDifference;
}
lastUpdate = now;
}
}
void Game::setState(GameState *_state) {
this->state = _state;
}
}