Search code examples
c++signalssignals-slotssfml

How to manage SFML rendering, the "signals" way?


I'm developing a little snake game written in C++ and using SFML 2D library. The problem is: in order to render a window, and to print anything in it, you have to make it through a

while (App->IsOpened())
{
    //Do the stuff
    App->Clear();
    App->Display();
}

But, I'd like to build my program in a more generic ways, which would make me able to just Init the window, and then send signals to it, such as "RenderARect" in it, or "ClearTheWindow", from outside the while statement. It would let me use my rendering class instance as a dynamic library for exemple, making the game code, and the rendering code two different and independant things...

would you have you any advices on how to implement such a signal system to my SFML program?

PS: I've eared of the libsigc++, but have no idea on how to implement it...

Thank you!


Solution

  • There's no need to send such signals. Everything should be handled in that while loop (the main loop), and every frame should be cleared, and drawn individually and as a whole, not in regions, hence SFML uses OpenGL.

    The most obvious way to separate the game logic from the main loop is making the game OOP. Of course, it will separate it only to separate logic units, in separate files, but they will run "together", in the same loop. I think this is the desired (but at least acceptable) behaviour.

    So you'll have a Game class, which will have an Update() method. This is where the game logic happens, events are handled (preferably events are queryed before the call, and are passed as a parameter to Update()), and the state of everything which has to be displayed is updated. You should call this in every iteration of the main loop.

    And that class will also have a Render() method, which will draw everything as it is needed.

    So it would look like this:

    while (App->IsOpened())
    {
        Game->Update();
        App->Clear();
        Game->Render();
        App->Display();
    }

    P.S.: Sorry for my bad English, I hope you can understand it.