-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMenuState.cpp
105 lines (84 loc) · 2.13 KB
/
MenuState.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
#include "MenuState.hpp"
MenuState::MenuState(StateStack &stack, Context context)
: State(stack, context)
, mOptions()
, mOptionIndex(0)
{
sf::Texture& texture = context.textures->get(Textures::TitleScreen);
sf::Font& font = context.fonts->get(Fonts::Main);
mBackgroundSprite.setTexture(texture);
// A simple menu demonstration
sf::Text playOption;
playOption.setFont(font);
playOption.setString("Play");
centerOrigin(playOption);
playOption.setPosition(context.window->getView().getSize() / 2.f);
mOptions.push_back(playOption);
sf::Text exitOption;
exitOption.setFont(font);
exitOption.setString("Exit");
centerOrigin(exitOption);
exitOption.setPosition(playOption.getPosition() + sf::Vector2f(0.f, 30.f));
mOptions.push_back(exitOption);
updateOptionText();
}
void MenuState::draw()
{
sf::RenderWindow &window = *getContext().window;
window.setView(window.getDefaultView());
window.draw(mBackgroundSprite);
for(const sf::Text &text : mOptions)
window.draw(text);
}
bool MenuState::update(sf::Time dt)
{
return true;
}
bool MenuState::handleEvent(const sf::Event &event)
{
// The demonstration menu logic
if (event.type != sf::Event::KeyPressed)
return false;
if (event.key.code == sf::Keyboard::Return)
{
if (mOptionIndex == Play)
{
requestStackPop();
requestStackPush(States::Loading);
}
else if (mOptionIndex == Exit)
{
// The exit option was chosen, by removing itself, the stack will be empty, and the game will know it is time to close.
requestStackPop();
}
}
else if (event.key.code == sf::Keyboard::Up)
{
// Decrement and wrap-around
if (mOptionIndex > 0)
mOptionIndex--;
else
mOptionIndex = mOptions.size() - 1;
updateOptionText();
}
else if (event.key.code == sf::Keyboard::Down)
{
// Increment and wrap-around
if (mOptionIndex < mOptions.size() - 1)
mOptionIndex++;
else
mOptionIndex = 0;
updateOptionText();
}
return true;
}
void MenuState::updateOptionText()
{
if (mOptions.empty())
return;
// White all texts
for(sf::Text& text : mOptions)
text.setColor(sf::Color::White);
// Red the selected text
mOptions[mOptionIndex].setColor(sf::Color::Red);
}