Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: How to realize a state machine based SFML?  (Read 1220 times)

0 Members and 1 Guest are viewing this topic.

Abc

  • Newbie
  • *
  • Posts: 2
    • View Profile
How to realize a state machine based SFML?
« on: April 20, 2024, 01:38:41 pm »
Hello everyone.
I am trying to realize a simple game engine based on SFML. It has a state machine, that represents the LIFO queue. My base state class looks something like this:

class AbstractScene
{
    public:
    virtual handleEvents(const sf::Event& event) = 0;

    virtual updateLogic(const sf::Time& time) = 0;

    virtual draw() = 0;
};

Methods of the state machine are cached to be called simultaneously when the state machine has finished handle events, update logic and draw all states.

I pushed the Level state. I set pause and pushed Menu state by pressing a mouse button. It works, but I can get a few identical events (sf::Event::MouseButtonPressed) at the one frame loop and I have the three same states (but I should have the only one):

class Level : public AbstractScene
{
    public:
    void handleEvents(const sf::Event& event) override
    {
         if(event.type == sf::MouseButtonPressed)
         {
              // append new scene
              stateMachine.push(new Menu());
         }
       
         ...
    }
};

I can add a boolean flag that will collect the general value of this event and I will handle it at the "updateLogic" method. However, my state machine blocks this method when it paused.

So how and where should I change the states and how should I realize the game pause?

PS: sorry for my bad Engish. Thank you very much!

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11033
    • View Profile
    • development blog
    • Email
Re: How to realize a state machine based SFML?
« Reply #1 on: April 22, 2024, 08:25:07 am »
In my SmallGameEngine state machine example, I can create a new state anywhere in the code, it will be stored as m_next and only applied in the next state machine loop iteration.

This guarantees that the state doesn't just suddenly change and leaves the freedom to create a new state anywhere within the current state.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/