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/app.cpp | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 src/app.cpp (limited to 'src/app.cpp') diff --git a/src/app.cpp b/src/app.cpp new file mode 100644 index 0000000..30bccdf --- /dev/null +++ b/src/app.cpp @@ -0,0 +1,71 @@ +#include "app.h" +#include "states/ids.h" +#include "states/titleState.h" + +const sf::Time App::TIME_PER_FRAME = sf::seconds(1.f/60.f); + + +App::App() + : textures_() + , window_(sf::VideoMode(640, 480), "Demo game" ) + , stateStack_( State::Context{&window_, &textures_} ) + //, player_() +{ + window_.setFramerateLimit(60); + + registerStates(); + stateStack_.push(States::Id::Title); +} + +void App::run(){ + // Make the app render the current state, so it needs a state stack too + sf::Clock clock; + sf::Time timeSinceLastUpdate = sf::Time::Zero; + + while(window_.isOpen()){ + + + // TODO Maybe move to a fixed time game loop (I prefer that) + sf::Time dt = clock.restart(); + timeSinceLastUpdate += dt; + + while (timeSinceLastUpdate > TIME_PER_FRAME) + { + timeSinceLastUpdate -= TIME_PER_FRAME; + + processInput(); + update(TIME_PER_FRAME); + + // Check inside this loop, because stack might be empty before update() call + if (stateStack_.isEmpty()) window_.close(); + } + + render(); + } +} + +void App::render(){ + window_.clear(); + stateStack_.render(); + window_.display(); +} + + +void App::update(sf::Time dt){ + stateStack_.update(dt); +} + +void App::processInput(){ + sf::Event event; + while (window_.pollEvent(event)) + { + stateStack_.handleEvent(event); + + if (event.type == sf::Event::Closed) + window_.close(); + } +} + +void App::registerStates(){ + stateStack_.registerState(States::Id::Title); +} -- cgit v1.2.3