Created
March 4, 2022 06:59
-
-
Save yknishidate/dd626f43ea08ad88d0979739cc3cbc12 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
class Heroine; | |
enum class Input | |
{ | |
PressDown, | |
ReleaseDown | |
}; | |
class HeroineState | |
{ | |
public: | |
virtual ~HeroineState() {} | |
virtual void enter() {} | |
virtual HeroineState *handleInput(Heroine &heroine, Input input) = 0; | |
virtual void update(Heroine &heroine) {} | |
}; | |
class StandingState : public HeroineState | |
{ | |
public: | |
void enter() override | |
{ | |
std::cout << "now standing." << std::endl; | |
} | |
HeroineState *handleInput(Heroine &heroine, Input input) override; | |
}; | |
class DuckingState : public HeroineState | |
{ | |
public: | |
DuckingState() | |
: m_chargeTime(0) | |
{ | |
} | |
void enter() override | |
{ | |
std::cout << "now ducking." << std::endl; | |
} | |
HeroineState *handleInput(Heroine &heroine, Input input) override; | |
void update(Heroine &heroine) override | |
{ | |
m_chargeTime++; | |
} | |
private: | |
int m_chargeTime; | |
}; | |
class Heroine | |
{ | |
public: | |
Heroine() | |
{ | |
m_state = new StandingState(); | |
m_state->enter(); | |
} | |
virtual void handleInput(Input input) | |
{ | |
HeroineState *state = m_state->handleInput(*this, input); | |
if (state) | |
{ | |
delete m_state; | |
m_state = state; | |
m_state->enter(); | |
} | |
} | |
virtual void update() | |
{ | |
m_state->update(*this); | |
} | |
private: | |
HeroineState *m_state; | |
}; | |
HeroineState *StandingState::handleInput(Heroine &heroine, Input input) | |
{ | |
if (input == Input::PressDown) | |
{ | |
return new DuckingState(); | |
} | |
return nullptr; | |
} | |
HeroineState *DuckingState::handleInput(Heroine &heroine, Input input) | |
{ | |
if (input == Input::ReleaseDown) | |
{ | |
return new StandingState(); | |
} | |
return nullptr; | |
} | |
int main() | |
{ | |
Heroine heroine; // "now standing." | |
heroine.handleInput(Input::PressDown); // "now docking." | |
heroine.handleInput(Input::ReleaseDown); // "now standing." | |
heroine.handleInput(Input::ReleaseDown); // no output | |
heroine.handleInput(Input::PressDown); // "now docking." | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Game Programming Patterns, Chapter 7