Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
SFML Game Development.pdf
Скачиваний:
194
Добавлен:
28.03.2016
Размер:
4.19 Mб
Скачать

Chapter 5

The state context

In general, every screen will need to display some text or sprites, draw to the screen, among other common things. Due to this fact, and to avoid unnecessary memory wasting by loading the same texture or font to memory in multiple places, we introduced the State::Context structure. It works as a holder of shared objects between all states of our game.

Essentially, every state will now have access to the getContext() method, which itself contains the pointer to the window used to draw its objects and resource holders such as font and texture managers. Here's the declaration of the structure:

struct Context

{

 

Context(sf::RenderWindow& window,

 

TextureHolder& textures,

 

FontHolder& fonts,

 

Player& player);

sf::RenderWindow*

window;

TextureHolder*

textures;

FontHolder*

fonts;

Player*

player;

};

 

The usefulness of the state context is undeniable. It will save system memory by reusing the same fonts and textures for every state. It will also provide access to the window's view at all times, which is a necessity when positioning and resizing our objects relatively to the view's dimensions.

Integrating the stack in the Application class

Since we have now more states than the game itself, we create a new class Application that controls input, logic updates, and rendering. Having a ready StateStack implementation waiting to be used, it is time to promote it into the Application class. We will plug our new state architecture into our Application class and then start using it!

[ 121 ]

www.it-ebooks.info

Diverting the Game Flow – State Stack

First, we add the mStateStack member variable to Application. We register all the states in an own method:

void Application::registerStates()

{

mStateStack.registerState<TitleState>(States::Title);

mStateStack.registerState<MenuState>(States::Menu);

mStateStack.registerState<GameState>(States::Game);

mStateStack.registerState<PauseState>(States::Pause);

}

Now there are a few more things we must care about for a full integration of our state architecture:

Feeding it with events in the Application::processInput() function:

while (mWindow.pollEvent(event))

{

mStateStack.handleEvent(event);

}

Updating with the elapsed time:

void Application::update(sf::Time dt)

{

mStateStack.update(dt);

}

Rendering of the stack, in the middle of the frame draw:

mStateStack.draw();

Closing the game when no more states are left:

if (mStateStack.isEmpty()) mWindow.close();

And now that everything is plugged in and ready to go, in the end of our constructor we make the machine start with the title screen!

mStateStack.pushState(States::Title);

[ 122 ]

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]