-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathgamestatemachine.cpp
More file actions
84 lines (71 loc) · 2.28 KB
/
gamestatemachine.cpp
File metadata and controls
84 lines (71 loc) · 2.28 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
#include <fea/structure/gamestatemachine.hpp>
#include <fea/assert.hpp>
#include <sstream>
namespace fea
{
GameStateMachine::GameStateMachine() : mCurrentStateName("NONE"), mCurrentState(nullptr)
{
}
void GameStateMachine::addGameState(const std::string& name, std::unique_ptr<GameState> state)
{
FEA_ASSERT(gameStates.find(name) == gameStates.end(), "Trying to add state called " + name + " but such a state name already exists!");
state->setup();
gameStates.emplace(name, std::move(state));
}
void GameStateMachine::setCurrentState(const std::string& name)
{
FEA_ASSERT(gameStates.find(name) != gameStates.end(), "Trying to set to state called " + name + " but such a state does not exist!");
if(mCurrentState == nullptr)
{
mCurrentState = gameStates.at(name).get();
mCurrentState->activate("");
mCurrentStateName = name;
}
else
{
switchState(name);
}
}
GameState* GameStateMachine::getCurrentState()
{
return mCurrentState;
}
bool GameStateMachine::isFinished() const
{
return mCurrentState == nullptr;
}
void GameStateMachine::switchState(const std::string& nextStateName)
{
if(nextStateName == mCurrentStateName)
{
return;
}
mCurrentState->deactivate(nextStateName);
GameState* previousState = mCurrentState;
std::string previousStateName = mCurrentStateName;
mCurrentState = gameStates.at(nextStateName).get();
mCurrentStateName = nextStateName;
mCurrentState->handOver(*previousState, previousStateName);
mCurrentState->activate(previousStateName);
}
void GameStateMachine::run()
{
if(mCurrentStateName != "NONE")
{
std::string returned = mCurrentState->run();
if(returned != "")
{
if(returned == "NONE")
{
mCurrentState->deactivate("NONE");
mCurrentState = nullptr;
mCurrentStateName = "NONE";
}
else
{
switchState(returned);
}
}
}
}
}