Search code examples
c++sfml

SFML Custom Class Not Closing


I have a custom class called "Game"

#include "Game.h"
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Graphics/Text.hpp>
using namespace sf;

Game::Game(float length, float height, std::string title) {
    this->length = length;
    this->height = height;
    this->window = new RenderWindow(VideoMode(this->length, this->height), title);
    this->isOpen = true;
    display();
}

bool Game::pollEvent() {
    return window->pollEvent(e);
}

void Game::close() {
    window->close();
}

void Game::display() {
    window->display();
}

void Game::clear() {
    window->clear(Color::White);
}

void Game::paint(Drawable component) {
    window->draw(component);
}

void Game::sleep(long millis) {
    sf::sleep(milliseconds(millis));
}


Game::~Game() {
}

And a main class that executes the program

#include <cstdlib>
#include "Game.h"

using namespace sf;

int main(int argc, char** argv) {
    Game game(1000, 1000, "My Class Works!");
    while (game.isOpen) {
        while (game.pollEvent()) {
            if (game.e.type == Event::Closed) {
                game.close();
            }
        }
        game.clear();
        game.sleep(1000/60);
        game.display();
    }
}

The window displays on the screen, however, when I try to close the window, it freezes and does not close. I am new to SFML so I would like to know if I am doing this the correct way, and my class is how it is supposed to be. Everything else seems to work apart from that. Why is it not closing? Thanks.


Solution

  • Your flag game.isOpen stays true, so the while loop continues to excute, but your RenderWindow is closed.

    Update the Game::close method like this :

    void Game::close() {
        window->close();
        isOpen = false;
    }