Question

First of all I'm sorry for the title, couldnt come up with something short to describe my problem.

What I have is a "text-based adventure game". I have a main class that's called Game, where I have the game loop etc, I also have a class called Screen, and a childclass to Screen called Screen_One, and Screen_Two and so on, for as many different "Screens" I want in my game.

So what I have inside Screen, is an sf::Texture and sf::Sprite. Screen_One and Two both initialize those in their respective constructors with different values (in this case its just a background texture).

And here comes my problem, my Game class has an object of type Screen, which I want to change depending on where in the game I am, so basically I want to initialize Screen as a Screen_One object in the Game constructor, and when I progress in the game to Screen_Two I want to change that Screen object to a Screen_Two object and therefore get the right background for the screen I'm currently on.

What I have now (which doesn't work is something like this)

Screen_One's constructor

Screen_One::Screen_One(void)
{
    Texture.loadFromFile("filename.png"); // background for screen_one
    Sprite.setTexture(Texture);
}

inside the Game class:

Game::Game(void) : mWindow(sf::VideoMode(640, 480), "Game") // Game constructor
{
    sc = Screen_One(); // sc is a declared like "Screen sc" in Game.h
}

void Game::render() // this function runs inside the game loop
{
    //draw some stuff
    mWindow.draw(this->sc.Sprite);
}

this code runs, but it just gives me a white background (so basically it draws nothing). So this way of doing it obviously doesnt work but I hope you can understand what Im trying to do and maybe fix or give me another way of achieving the same thing.

EDIT: tl;dr can I have an object of type Screen, and then during runtime assign the Screen object to Screen_One or Screen_Two in order to for example change background.

Was it helpful?

Solution

In this code

sc = Screen_One();

what is happening is that the Screen part of Screen_One is being copied into sc, not the whole object, as sc doesn't have enough space for it. This is assuming you haven't overridden the = operator.

To fix your problem, sc should be a pointer to Screen. The declaration would be

Screen *sc;

Then in the Game constructor, initialize the pointer to a new object of type Screen_One:

sc = new Screen_One();

When you want to change screens, delete the old screen and make sc point to a new instance of Screen_Two:

delete sc;
sc = new Screen_Two();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top