Nesesito know why my program exploits for no reason, and how could I solve it, I'm moving in the architecture of a game, very simple, for now I only have the class Stage
that serves as the main event which drew in the window everything that I add. I try to use as much as I can, the iterator design pattern.
This is Stage.h
:
#pragma once
#include <SFML\Graphics.hpp>
#include <vector>
class Stage {
private:
sf::RenderWindow *window;
std::vector <sf::Sprite> all_sprites;
public:
Stage ();
Stage (int width, int height, sf::String name);
void addObj (sf::Sprite newobject);
void removeObj (sf::Sprite ocurrence);
void renderize ();
void run ();
};
This is Stage.cpp
:
#include "Stage.h"
#include <SFML\Graphics.hpp>
#include <iostream>
#include <vector>
Stage::Stage() { window = nullptr; }
Stage::Stage(int width, int height, sf::String name) {
window = new sf::RenderWindow(sf::VideoMode(width, height), name);
}
void Stage::addObj(sf::Sprite obj) { all_sprites.push_back(obj); }
void Stage::removeObj(sf::Sprite obj) {
for (auto it = all_sprites.begin(); it != all_sprites.end(); it++) {
if ((*it).getPosition() == obj.getPosition()) {
all_sprites.erase(it);
}
}
}
void Stage::renderize() {
window->clear(sf::Color::Blue);
for (auto it = all_sprites.begin(); it != all_sprites.end(); it++) { window->draw(*it); }
window->display();
}
void Stage::run() {
while (window->isOpen()) {
sf::Event event;
while (window->pollEvent(event)) {
if (event.type == sf::Event::Closed) window->close();
if (event.key.code == sf::Keyboard::Escape) window->close();
if (event.type == sf::Event::MouseButtonPressed) {
if (event.mouseButton.button == sf::Mouse::Left) {
std::cout << "Left click detected!" << std::endl;
}
}
}
renderize();
}
}
finally this is my main.cpp
:
#include "Stage.h"
#include <SFML\Graphics.hpp>
int main() {
Stage app(640, 480, "Game #1");
sf::Texture text;
text.loadFromFile("pic/life.png");
sf::Sprite sprite(text);
app.addObj(sprite);
app.run();
return 0;
}
The program perfectly fulfills the syntax, the logic I see it all well and I do not even get any warning. But when I run it the program simply closes itself after about 2 seconds, I've also noticed that adding a click event increases this time by extending the life of the program, but in the end the same thing happens. I want it to run until I give it esc
or click on the close button, I do not know why my infinite while has an end.
What do you recommend I do to solve it?