From bf34d835e4ea49bd4ef2e5de2b1fea2fd3c95adc Mon Sep 17 00:00:00 2001 From: Ekaitz Zarraga Date: Tue, 29 Nov 2022 18:19:25 +0100 Subject: Start to use a normal game structure: - App class that has a StateStack - StateStack - Some State definiton and a minimal TitleState to use as a template - Makefile updated accordingly - Delete old code that was there for testing --- src/states.cpp | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 src/states.cpp (limited to 'src/states.cpp') diff --git a/src/states.cpp b/src/states.cpp new file mode 100644 index 0000000..d7799b3 --- /dev/null +++ b/src/states.cpp @@ -0,0 +1,89 @@ +#include "states.h" + +// StateStack + +StateStack::StateStack(State::Context context) + : pendingOps_() + , context_(context) +{ +} + +void StateStack::update(sf::Time dt){ + for(State::Ptr &s: states_) { + s->update(dt); + } +} + +void StateStack::render(){ + for(State::Ptr &s: states_) { + s->render(); + } +} + +void StateStack::handleEvent(const sf::Event &event){ + for(State::Ptr &s: states_) { + s->handleEvent(event); + } +} + +void StateStack::requestOp(StateStack::Op op){ + pendingOps_.push_back(op); +} + +void StateStack::push(States::Id state){ + states_.push_back(std::move(createState(state))); +} + +void StateStack::pop(){ + states_.pop_back(); +} + +void StateStack::clear(){ + states_.clear(); +} + +void StateStack::applyPending(){ + for(StateStack::Op &op: pendingOps_) { + switch(op.id){ + case StateStack::OpId::Push: + push(op.state); + break; + case StateStack::OpId::Pop: + pop(); + break; + case StateStack::OpId::Clear: + clear(); + break; + } + } + pendingOps_.clear(); +} + +bool StateStack::isEmpty() const{ + return states_.empty(); +} + +State::Ptr StateStack::createState(States::Id id){ + return stateFactory_[id](); +} + + +// State + +State::State(StateStack &stack, State::Context context) + : context_(context) + , stack_(&stack) +{} + +void State::requestPush(States::Id state_id){ + StateStack::Op op {StateStack::OpId::Push, state_id}; + stack_->requestOp(op); +} +void State::requestPop(){ + StateStack::Op op {StateStack::OpId::Push}; + stack_->requestOp(op); +} +void State::requestClear(){ + StateStack::Op op {StateStack::OpId::Clear}; + stack_->requestOp(op); +} -- cgit v1.2.3