Hello everyone !
I'm currently learning SFML and C++.
I've created a little game, but the fact is I would like to delete the Player object and Obstacle object when the program is closed. I tried not to use pointers but the compiler says "obstacle.fall(10) : fall is not of type Obstacle()". And if I use pointers for dynamic allocation, it works great but when it comes to delete the objects, I have a memory error.
The delete instructions are written in
Game::endGame().
Source code (just the main.cpp and Game.cpp files in order to keep things simple and clear):
main.cpp
#include <iostream>
#include <SFML/Graphics.hpp>
#include "Game.hpp"
#include "Player.hpp"
#include "Obstacle.hpp"
int main()
{
sf::RenderWindow window(sf::VideoMode(800,600), "Test", sf::Style::Fullscreen);
window.setVerticalSyncEnabled(true);
Game *game = new Game();
if(game->displayMenu(&window) != 0)
{
std::cerr << "Exiting the game..." << std::endl;
}
return 0;
}
Game.cpp
#include <iostream>
#include <SFML/Graphics.hpp>
#include "Game.hpp"
#include "Player.hpp"
#include "Obstacle.hpp"
Game::Game()
{
}
int Game::startGame(sf::RenderWindow *window)
{
window->clear(sf::Color::Black);
Player *player = new Player(360,520,40);
Obstacle *obstacle = new Obstacle();
while(window->isOpen() == true)
{
sf::Event ev;
while(window->pollEvent(ev) == true)
{
if(ev.type == sf::Event::Closed)
{
window->close();
}
if(ev.type == sf::Event::KeyPressed)
{
switch(ev.key.code)
{
case(sf::Keyboard::Escape):
window->close();
break;
case(sf::Keyboard::Left):
player->move(-20);
break;
case(sf::Keyboard::Right):
player->move(20);
break;
default:
break;
}
}
}
obstacle->fall(10);
obstacle->isInWindow();
player->isInWindow();
if(isCollision(player,obstacle) == true)
{
if(lifes > 0)
{
lifes -= 1;
}
else
{
endGame(window, player, obstacle);
}
}
obstacle->reset();
window->clear(sf::Color::Black);
player->draw(window);
obstacle->draw(window);
window->display();
}
}
}
void Game::endGame(sf::RenderWindow *window, Player *player, Obstacle *obstacle)
{
window->clear(sf::Color::Black);
while(window->isOpen() == true)
{
sf::Event ev;
while(window->pollEvent(ev) == true)
{
if(ev.type == sf::Event::Closed)
{
window->close();
delete &player;
delete &obstacle;
}
if(ev.type == sf::Event::KeyPressed)
{
switch(ev.key.code)
{
case(sf::Keyboard::Escape):
window->close();
delete &player;
delete &obstacle;
break;
case(sf::Keyboard::Return):
startGame(window);
break;
default:
break;
}
}
}
}
window->close();
}
Regards