-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGame.cpp
More file actions
103 lines (87 loc) · 2.18 KB
/
Game.cpp
File metadata and controls
103 lines (87 loc) · 2.18 KB
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
#include "Constants.h"
#include "Game.h"
#include "ResourceManager.h"
Game::Game() :
mWindow(sf::VideoMode({ SCREEN_WIDTH, SCREEN_HEIGHT }), GAME_NAME, sf::Style::Close),
mIcon(),
mGameStack()
{
// set window icon AND check assets directory
if (!mIcon.loadFromFile(ICON_IMAGE))
throw std::runtime_error("Failed to load png-file from data.");
mWindow.setIcon(mIcon);
// loading resources
ResourceManager::get().loadFont("main", TTF);
ResourceManager::get().loadTexture("ball", ICON_IMAGE);
ResourceManager::get().loadSound("ball", BALL_SOUND);
ResourceManager::get().loadSound("beat", BEAT_SOUND);
ResourceManager::get().loadSound("end", END_SOUND);
// turn off mouse
mWindow.setMouseCursorVisible(false);
// set TitleState
mGameStack.push_back(std::move(std::make_unique<PlayingState>(*this)));
mGameStack.push_back(std::move(std::make_unique<TitleState>(*this))); // overlay Title
}
void Game::run()
{
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
while (mWindow.isOpen())
{
sf::Time elapsedTime = clock.restart();
timeSinceLastUpdate += elapsedTime;
while (timeSinceLastUpdate > TIME_PER_FRAME)
{
timeSinceLastUpdate -= TIME_PER_FRAME;
processEvents();
update(TIME_PER_FRAME);
}
render();
}
}
void Game::processEvents()
{
while (const std::optional event = mWindow.pollEvent())
{
if (event->is<sf::Event::Closed>())
mWindow.close();
else if (const auto* keyPressed = event->getIf<sf::Event::KeyPressed>())
{
if (keyPressed->scancode == sf::Keyboard::Scancode::Escape)
mWindow.close();
}
if (mGameStack.empty()) continue;
mGameStack.back()->handleInput(*event);
}
}
void Game::update(sf::Time deltaTime)
{
if (!mGameStack.empty())
mGameStack.back()->update(deltaTime);
}
void Game::render()
{
mWindow.clear(BCG_COLOR);
if (!mGameStack.empty())
{
// drawing current state
//mGameStack.back()->render(mWindow);
// drawing all stack
for (const auto& state : mGameStack)
{
state->render(mWindow);
}
}
mWindow.display();
}
void Game::pushState(std::unique_ptr<State> newState)
{
mGameStack.push_back(std::move(newState));
}
void Game::popState()
{
if (!mGameStack.empty())
{
mGameStack.pop_back();
}
}