Archive for December, 2012

Somehow I managed to miss the fact that Microsoft had actually implemented smart pointers in VS2012 and was working back with raw pointers everywhere in my code. This mean writing a lot of delete statements and ensuring that resources were being freed properly.

Not any more! Now I’ve finally tagged on to the blindingly obvious (why would Herb Sutter be talking about smart pointers and modern C++ so much if MSVC didn’t support it, how comes everyone at StackOverflow said use smart pointers when most newbies probably learn with MSVC, why were there so many docs mentioning it at MSDN etc etc) I felt the need to modernise my code. Now I’ve used smart pointers before, back on GCC 4.7 with Code::Blocks, but I was convinced I wasn’t using them correctly so I set off for some basics on best practices. After a few searches on Google and StackOverflow, I came across a link to the MSDN docs on smart pointers. This page contains explanations on each version, example code for how to implement them and then has links to more detailed explanations on unique_ptr, shared_ptr and weak_ptr all of which also contain exemplar code.

Taking this on board I set out to update my code. First up was finding where I could implement unique_ptr. These are members of a class that are not called or accessed from outside of the class, they are unique to the object that they belong to. Using my Flood Fill game as my test project, the first member I figured was best as a unique_ptr was the board contained in the Level class. This is not accessed by any other classes and is not passed to any other classes (as a whole, Squares contained within it are passed around however). The colorChooser vector of Squares is also never accessed from outside the class so can be a vector<unique_ptr<Square>>. The only other pointer that I was able to make into a unique_ptr was the StateMachine in Engine.

Shared_ptrs will therefore be prevalent in my code. All of my GameTextures are created as shared_ptr<GameTexture> and passed around by value, letting the reference counting do the job of managing their deletion (when the program ends and the MediaCache destroys their relevant xCache). In the Board class, the board itself is a vector<shared_ptr<Square>> because different classes try to access the individual squares (i.e. to change their colour in the floodfill algorithm). Within the StateMachine class, the currentState is a shared_ptr<State> because the Engine class accesses it to call the various functions to run the game.

Creation of unique_ptr is still handled through the use of new and the unique_ptr constructor, i.e.

board(std::unique_ptr<Board>(new Board(20, 20)))

I would love to move to Herb Sutter’s make_unique function, but at the moment it isn’t supported by VC110, so we have to make do with this.

Creation of shared_ptr is however handled through the use of make_shared<T>, i.e.

auto gt = std::make_shared<GameTexture>(tex);

Reasoning for this is given here on Herb Sutter’s blog – essentially it’s making the code more efficient by keeping the memory for the shared_ptr and the shared_ptrs reference counting in the same memory block and creating them in one go instead of two. With auto saving us the effort of writing std::shared_ptr<GameTexture> on the LHS of the assignment operator, this is one big, beautiful c++11 line taking in a variety of the new features.

The only items left that are raw pointers are SDL specific – SDL_Renderer, SDL_Window, TTF_Font* – for which it makes no sense to wrap them in smart pointers, because they have their own, SDL specific, destroy function that needs to be called at the end of their lifetime.

Read Full Post »

State Design Pattern

Ever since I started building games, back at the start of 2012, I’ve been using a fairly cumbersome Finite State Machine to switch states. This involved the use of a StateManager class to keep track of the current state I’m in, combined with a switch statement of varying size (depending on the number of states in the game) to switch between the different states. This was a fairly good design in my eyes, but I always knew there was a better way to do it through usage of the State Pattern. This would ideally mean that to change states all I’d need was to call a changeState function that took a pointer to the new state and deleted the old state.

After plenty of searching through Google, gamedev, stackoverflow, GameDevNet et al, I finally stumbled across a tutorial that explained the idea and provided enough concrete examples for me to build my own system off the back of it. Given the new found freedom of a programming a new engine in SDL 2.0, I took this idea and ran with it.

So now my State class now has these 5 pure virtual functions:

virtual void enter(Engine* engine) = 0;
 virtual void handleEvents(SDL_Event& e, Engine* engine) = 0;
 virtual void update(const double dTime, Engine* engine) = 0;
 virtual void render() = 0;
 virtual void exit(Engine* engine) = 0;

These obviously all have to be overridden in any derived classes, such as Title, Level and GameOver. The Engine*’s are used for calling the changeState function that is inside the Engine class (actually the StateMachine class, but it is called from the Engine class). Enter and exit are called at the start and end of the class’ lifetime to perform any special functions that are needed.

Keeping track of the currentState that the game is in is no longer controlled by the Engine class itself, but is now operated by a StateMachine class, which is much like the StateManager class I used to operate (in some ways). The StateMachine class is very simple:

void setCurrentState(State* s) ;

State* currentState() const;

void changeState(State* newState);

One to set the currentState, one to return it and one to change it. ChangeState isn’t even a difficult function:

if(typeid(*mCurrentState) == typeid(*newState))
delete newState;


delete mCurrentState;

mCurrentState = newState;


The first if statement stops us from changing from the state we’re in to the state we’re already in, using a wonderful feature I’d never encountered before in C++, RTTI (run time type information). This can work out what type a variable is whilst the program is running. For our pointers to State, we have to dereference them to find out what they’re actually pointing to. This little bit of code is put in because in the Engine class when we press the Esc key it changes state to the Title state, but if we’re already there there is no point in creating a new instance of it. We then exit the currentState, delete it, assign the newState to it and finally enter the state.

The Engine class then contains a StateMachine* within it, which is initialized in the body of the constructor (as we’re passing the “this” pointer into the constructor we can’t assign it in the initializer list) and the currentState is set. To change state from, say, the Title to the Level we can call one line of code, which is in the mouseClicked() function for Title:

engine->changeState(new Level(mediaCache));

No calls to any external classes are needed, there is no need for a big switch statement to take place, the Engine which seamlessly switch from the Title to the Level and all will be good with the world. Any other states that are introduced won’t mean having to rewrite the StateManage enum and extending the switch statement in the FSM, we can just create a different State* instead, i.e.

engine->changeState(new HighScore(mediaCache));

//or maybe...

engine->changeState(new GameOver(mediaCache));

Read Full Post »

Downloads update

There’s finally been an update over on the downloads page, one that’s been needed for a while. I removed all traces of my source code, so they’re not for download any more. The links won’t even work any more because they’re no longer in my dropbox account. I’ve instead just got release versions of the games zipped up with the dll’s and the fonts/images/levels etc required for each game.

There are also two new games and an updated version of another:

Flood Fill – You have to turn the entire board into the same colour, see how few moves you can complete it in!

Simon – Everyone’s favourite memory game. There are only 4 buttons, but for how long can you remember the correct sequence?

Bomber Run has been massively updated. The game now starts with 15 houses and increases to 25 through the first 5 levels, the plane lands and crashes with (some basic) animation, the sounds have been updated to play properly, there is a pause and mute option, the plane has been modified to resemble a Tiger Moth and the biggest change of all – animated clouds have been added!

Head to the downloads page where you can play the above as well as Pong, Brick Buster, Aliens and Blackjack.

Read Full Post »

In what I’ll now call GameEngine v1.0, I loaded all my images, text and fonts from one place. This worked well but something wasn’t quite right with calling imgCache.getFont(50) – why would I go to a cache of images to load a font? So given the freedom of SDL 2.0 and noting that “modern c++” (and programming in general) revolves around large classes being built from small, single purpose classes I broke ImageCache up into 3 smaller classes. ImageCache itself remains but it’s now only for loading images (duh!), FontCache is for loading fonts and TextCache is for loading text. To bring all of these 3 new classes together I created the MediaCache. (If I can build SDL_Mixer 2.0 at some point in the future, my AudioCache will sit inside the MediaCache as well). This means that the vast majority of MediaCache functions are just calling functions from one of the contained classes. i.e.

GameTexture* MediaCache::getImage(std::string file)
return imgCache.getImage(file);

The getImage() function in MediaCache calls the ImageCache function of the same name.

You’ll notice the function returns a GameTexture*. A GameTexture is a small wrapper around an SDL_Texture that also knows of it’s width and height, using SDL_QueryTexture in it’s constructor

GameTexture::GameTexture(SDL_Texture* texture) : tex(texture)


SDL_QueryTexture(tex, NULL, NULL, &mWidth, &mHeight);


The main reason for setting this up was so I could centre an SDL_Texture on the screen easily. It’s proved a bit of a boon as now when the object’s destructor is called, SDL_DestroyTexture() now deletes the texture from memory, making memory management a little easier.

Rendering is now all done through one function, renderTexture, which takes an x and y position and a GameTexture* and renders the GT at (x,y).

The rest of the MediaCache is as it was in the old ImageCache with functions to centre horizontally and vertically, clearScreen and updateScreen functions to take care of updating the screen, drawRectangle to render any SDL_Rects and scrWidth and scrHeight to access the private variables.

Read Full Post »

SDL 2.0

I’ve used SDL for a while now, coming up on a year, and almost every recent question that I read regarding 1.2 (the latest “stable” release of the library) on forums suggests that users move over to SDL 2.0. Seeing that there is only source code available for the library at the moment and not a pre built binary, I’ve held off from upgrading. But recently having come to a bit of an end with my development path, I took the jump to setup SDL 2.0.

The big news? It’s easy. Like really, ridiculously easy. Download and install mercurial (there’s a link at the top of the SDL HG page), then from the command line run “hg clone http://hg.libsdl.org/SDL&#8221;. This will download the various files used for the making of SDL into whichever folder you run the command from.  The best bit is that the code is in Visual Studio   solutions (going back a few versions and including 2012). This means that to build the library you just build the solution like you would any other. Once this is done, you can go and find the dll and lib files, get the src code from your folder and organise them on your hard drive to give your SDL 2.0. Easy.

Of course, SDL isn’t really finished until you have the various other libraries that come along with it (ttf, image, mixer, net) and these are easy to download as well: from the command line, run “hg clone http://hg.libsdl.org/SDL_ttf&#8221; or “hg clone http://hg.libsdl.org/SDL_image&#8221; etc, then build as before. In no time at all you can be on the flash new API.

So now you’re running SDL 2.0, unforunately your code won’t port straight across. Bit of a bummer, but not the end of the world. It’s not a whole lot of effort rewriting it and things will be easier on the new version (in my opinion). To this end I found a great tutorial over at Twinklebeardev which is up to date and explains things from the bottom up.

What are the advantages of SDL 2.0? Hardware accelerated textures (SDL_Texture), a window and rendering context which allow for multiple screens (SDL_Window, SDL_Renderer) and better OpenGL support (although I’m leaning towards GLFW for that at the moment). Have at it and see how you get on. I’ve enjoyed the new version and not found any bugs at all.

So to celebrate, I rewrote my game engine! I broke ImageCache up into 3 smaller classes, got rid of SDL_Surfaces and replaced them with SDL_Textures and introduced the state design pattern (finally!). All to come in a future post…

Read Full Post »