Category Archives: Game Development

Getting started with Allegro 5.1 on Mac OS X 10.8 (Xcode 4.5, and homebrew)

In Dune 2 – The Maker, I have used Allegro quite a bit. Back then it was around version 4.2. Allegro is a library that allows you to make games. In essence it has functions for manipulating the screen (ie, drawing bitmaps, manipulating palettes, etc), use controls (mouse, joystick, keyboard, etc) and more. With plugins you could extend it further, to use fonts (TTF), networking, etc.

Currently, the most recent version is Allegro 5 which breaks with the Allegro 4 API and makes it impossible to convert from Allegro 4 to 5 (atleast for D2TM). From a nostalgic perspective I wanted to try Allegro 5 and on my new system which runs Mac OS X 10.8.

In this post I will describe how you can get Allegro 5 working on Mac OS X, under XCode 4.5. I had great help from the documentation provided, and hopefully this post is sufficient for you. If not, I would suggest to checkout this documentation, or this one.

Rough steps

To give you an idea what we’re going to do, here is the installation in very rough form:

  1. – Installing required software
  2. – Installing dependencies to make Allegro more useful and to get it compiling (cmake, etc)
  3. – Compiling Allegro for Xcode, installing it and making sure the Frameworks are installed in /Library/Frameworks
  4. – Setting up an Xcode project to test if Allegro works

Prerequisites (Installing required software)

Requirements for getting started, if you already have this installed you can skip the prerequisites

  • Mac OS X 10.8
  • Xcode 4.5 (with command line tools)
  • Git/SVN
  • Homebrew

Before we can start, we need to have installed some prerequisites. Which are Xcode (you can get this from the App store), git and svn. I have used homebrew to install dependencies, you can also use Macports but I do not have any experience with this. (as far as I can tell it should behave quite the same). My advice would be to install these in the following order:

  • – Xcode
  • – Install command line tools from Xcode
in Xcode, go to preferences, tab "Downloads" -> " Components" -> Command Line Tools
ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"
  • – The command line tools should have installed git and svn for you, try them out:
hit "svn --version", and "git --version" in your terminal.
If they are not installed, you could install them via homebrew (brew install git && brew install svn)

Installing required dependencies

As suggested by the Allegro 5 wiki we need to install dependencies. The wiki explains how to do it with Macports, but since I am using Homebrew, you need to do it like this:

brew install cmake

brew install zlib
brew install freetype
brew install jpeg
brew install libogg
brew install physfs
brew install libpng
brew install flac
brew install ffmpeg

The first one is cmake, which we will need to build Allegro. Cmake is required to create the OS specific build steps to compile Allegro, without it we cannot proceed. The other dependencies are used to make Allegro more useful. When we prepare to build Allegro in the next section, cmake will check what dependencies are installed. The more it finds, the more features it will provide in Allegro 5.

Note, you might get  a warning about zlib. If thats the case, you can ignore it.

Compiling Allegro for Xcode, and making sure the Frameworks are in /Library/Frameworks

Once we have everything set up, this step is relatively easy. Since we are going to compile it for Xcode, we basically are doing the same as the Allegro wiki is saying.

Open a terminal, and go (cd) to a directory where you want to get allegro’s sources. For example: ~/projects

cd ~/projects

We now need to fetch the sourcecode of Allegro, which we can do by using git clone. At this moment of writing, Allegro 5.1 is the current version. Our git clone command looks like this:

git clone git://git.code.sf.net/p/alleg/allegro

This takes a little while. Once git is done, you have Allegro’s sources in ~/projects/allegro.

Now: cd to allegro, and create a new directory called “build”, then go into that directory.

cd allegro
mkdir build
cd build

The first step is to let cmake (the first dependency we installed) prepare our build, then build it and then install it. This is done by the following:

cmake -G Xcode -DWANT_FRAMEWORKS=1 - ..
xcodebuild
sudo xcodebuild install

The last step requires you to enter your password.

I found that the last step did not work for me, in order to fix that I did:

cd lib/RelWithDebInfo

Within here all Frameworks are built. Now copy them over to your /Library/Frameworks directory with sudo. With this:

sudo cp -r *.* /Library/Frameworks/

If you don’t want to copy this over to your Library/Frameworks directory, then you need to remember the path to these frameworks as we are going to need them later.

Setting up an Xcode project and see it all working

This section is a copy & paste + improvement from this page.

  • Start XCode, create a new empty project (Other->Empty)
    Xcode new empty project
  • Add a Cocoa Application target to the project, let’s call it MyGame. (Click your project, then the + button at the bottom saying Add target, then Mac OSX->Application->Cocoa.)
    New cocoa application MyGame
  • Select the MyGame target, go to the Build Phases tab and add a new Copy Files Build Phase (+ button down right).
    • Select Frameworks from the dropdown
    • Leave Subpath blank
    • We leave this build phase empty for now, we will need it later.
      Add new build phase
  • Select the Build Settings tab then:
    • Note: You can change display from Basic to All at the top and use the search box to locate the following settings
    • Change Header Search Paths to (just copy & paste):
      /Library/Frameworks/Allegro-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroMain-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroAcodec-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroAudio-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroColor-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroDialog-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroFont-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroImage-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroPhysfs-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroMemfile-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroPrimitives-5.1.framework/Versions/Current/Headers /Library/Frameworks/AllegroTTF-5.1.framework/Versions/Current/Headers
      

      (yes, it is intended to be one line)
      add framework headers

    •  
    • In the targets Build Settings specify the Framework Search Paths as/Library/Frameworks.add framework search path
      • This is needed to have cross-platform code (#include <allegro5/allegro.h> working – otherwise paths like using #include <Allegro-5.0/allegro5/allegro> would work without changing the search path)
      • If you use another location, one way to save on typing is to double click the input field, then navigate to the Headers folder in each framework and drag it into the xcode input list
    • Delete Prefix Header (Edit->Delete)
      • You can of course use your own prefix headers – but the default Cocoa one will only work with objective C projects that’s why we remove it, assuming MyGame is a cross-platform C/C++ project
  • Add all the Allegro frameworks as follows (this can be done in many ways, a group just keeps things tidy):
    • Select the Summary tab
    • Click the + button under Linked Frameworks and Libraries and add all the Allegro frameworks
      • In case they are not listed use the Add Other button and navigate to /Library/Frameworks to find themadd frameworksselect frameworkslinked frameworks added
    • Go to the Build Phases tab, then in the list to the left select all the Allegro frameworks and drag them to the Copy Files entry which we added before
      drag frameworks to copy build phase
    • Select all the frameworks again and this time drag them to the Frameworks group to the left (just to have things more tidy)
  • Don’t forget to remove the created source files under MyGame and add your own source code instead (note the main.m in Supporting Files for example)
    • Create a new main.c
      create new main
    • Give it the following content:
#include <allegro5/allegro.h>

int main(int argc, char **argv) {
   al_init();
   al_create_display(640, 480);
   al_clear_to_color(al_map_rgb_f(1, 1, 0));
   al_flip_display();
   al_rest(5.0);
   return 0;
}

Caveats

  • Cannot find header files: Make sure you have set the header paths correctly. Try to copy the one line given above, into your header paths (remove old ones first). If that does not work. Try adding them one by one, to make it easier to copy/paste I have provided them for you separately as well:
    /Library/Frameworks/Allegro-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroMain-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroAcodec-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroAudio-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroColor-5.1.framework/Versions/Current/Header
    /Library/Frameworks/AllegroDialog-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroFont-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroImage-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroPhysfs-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroMemfile-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroPrimitives-5.1.framework/Versions/Current/Headers
    /Library/Frameworks/AllegroTTF-5.1.framework/Versions/Current/Headers
    
    
  • Compiling works fine, linking does not work: Make sure you have specified the Framework Search Paths as/Library/Frameworks.

D2TM Rewrite – Development Blog – Drawing stuff on the screen

In the previous post I have set up a raw architecture for the game. There is a Game class that has a function called execute, which allows basic stuff to happen:

– responding to events
– updating state
– and rendering state

In code it is:
[sourcecode language=”cpp”]
while (running) {
handleEvents();
update();
render();
}
[/sourcecode]

The end result of the first phase was, well, a black window. Nothing to be excited about just yet…

One of the very basic needs is drawing on the screen. One way to get something on the screen is by using something called blitting. Blitting is basically taking a picture in memory (called in SDL a surface, or in Allegro a BITMAP) and then copy it onto another surface which functions as the screen.

We already have this screen SDL Surface defined in our Game class. It is not the actual (hardware) screen buffer. But, by doing SDL_Flip we can make this screen visible.

In essense this means the render function will be like this:
[sourcecode language=”cpp”]
void Game::render() {
// draw some stuff on the screen
// flip screen at the end
SDL_Flip(screen);
}
[/sourcecode]

I want to be able to draw surfaces on the screen. SDL requires the usage of SDL_Rect‘s which allows you to draw pieces of surfaces. At this point I don’t want deal with these SDL_Rect’s directly. What i want is:

[sourcecode language=”text”]
draw (source surface, dest surface, int x, int y);
[/sourcecode]

This is where I introduce a new class (again Single Responsibility Principle) that allows drawing on the screen and providing easy methods to do so. I call this the surfaceDrawer. At this point in time, its class definition looks like this:

[sourcecode language=”cpp”]
#ifndef SURFACEDRAWER_H
#define SURFACEDRAWER_H

#include <SDL/SDL.h>

class SurfaceDrawer {

public:
void draw(SDL_Surface * from, SDL_Surface * dest, int x, int y);

};

#endif
[/sourcecode]

The implementation looks like this:

[sourcecode language=”cpp”]
#include "surfacedrawer.h"

void SurfaceDrawer::draw(SDL_Surface * from, SDL_Surface * dest, int x, int y) {
if(from == NULL || dest == NULL) {
return;
}

SDL_Rect rect;
rect.x = x;
rect.y = y;

SDL_BlitSurface(from, NULL, dest, &rect);
}
[/sourcecode]

This implementation is easy; the SDL_BlitSurface accepts:
– a from surface
– a from rectangle (ie, what to copy from the from surface?, NULL = everything)
– a destination surface
– a position given by a rect. (where to draw this? Starting with upperleft corner of from surface)

In this case, we provide NULL as 2nd argument, saying we want to copy the entire from surface. Then, the last parameter is the position where to draw it in the form of an SDL_Rect.

Next step is to actually use this function. One thing that we always need in an RTS is to draw the mouse. What we need is an SDL_Surface with a mouse bitmap loaded. I will be using:

Default mouse at 32x32 size, with purple background

Default mouse at 32x32 size, with purple background

Loading this image is done by using SDL_LoadBMP . We need to make sure that the surface we have loaded is in the same bit/color format as our screen. We can do that by using SDL_DisplayFormat. We don’t want to be bothered with this everytime, so we have to make some class responsible for loading resources into SDL_Surface’s which are suitable for drawing by the surfaceDrawer. For that I have introduced a surfaceDao class, which has the following class definition:

[sourcecode language=”cpp”]
#ifndef SURFACEREPO
#define SURFACEREPO

// Data Access Object for fetching SDL Surfaces
#include <SDL/SDL.h>

class SurfaceDao {

public:
SDL_Surface * load(char * file);

};

#endif
[/sourcecode]

SDL supports BMP formats out of the box. We need to use the SDL_Image library to get support for other formats. Using a DAO we can move all this format specific stuff out of our game into this single class later. For now I will be using BMP, as the main focus is drawing surfaces.

The implementation of the surfaceDao looks like this:

[sourcecode language=”cpp”]
#include "surfacedao.h"

#include <iostream>

using namespace std;

SDL_Surface * SurfaceDao::load(char * file) {
SDL_Surface * temp = NULL;
SDL_Surface * result = NULL;

if((temp = SDL_LoadBMP(file)) == NULL) {
cout << "Failed to load [" << file << "]." << endl;
return NULL;
}

result = SDL_DisplayFormat(temp);
SDL_FreeSurface(temp);

return result;
}
[/sourcecode]

We load the BMP, when that is succesful, we convert it to the current display format. We have to free the temp surface using SDL_FreeSurface, to prevent memory leaks.

Now, in the Game class, this all comes together, first the class definition is expanded and gets (at the private section) the following code:

[sourcecode language=”cpp”]
#ifndef GAME_H
#define GAME_H

#include <SDL/SDL.h>

#include "surfacedao.h"
#include "surfacedrawer.h"

class Game {

.. snip ..

private:
.. snip ..

SDL_Surface * mouse;

// Dependencies
SurfaceDao surfaceDao;
SurfaceDrawer surfaceDrawer;

};

#endif

[/sourcecode]

As you can see, I already have prepared the SDL_Surface for the mouse. Now in the Game implementation, loading the mouse is using the surfaceDao:

[sourcecode language=”cpp”]
int Game::init() {
… snip …

// load resources
mouse = surfaceDao.load("resources/images/MS_Normal.bmp");

return 0;
}
[/sourcecode]

In the render function I use the surfaceDrawer to draw the mouse at the current X and Y position of the mouse:

[sourcecode language=”cpp”]

void Game::render() {
int mouseX, mouseY;
SDL_GetMouseState(&mouseX, &mouseY);

surfaceDrawer.draw(mouse, screen, mouseX, mouseY);

// flip screen at the end
SDL_Flip(screen);
}
[/sourcecode]

This all finally results into:

Drawing the mouse! Isn't that cute.

Drawing the mouse! Isn't that cute.

Finally, we have something to draw! yay! But we need to make this a little bit better first:
– remove the system cursor (you don’t see this on the picture, but when running this your system cursor is on top)
– make sure we don’t have a trail of the mouse, ie, clean the screen before drawing
– we also see the purple background of the mouse, we don’t want to draw that…

Lets fix these things:

Hide system cursor
[sourcecode language=”cpp”]
int Game::init() {
… snip …
SDL_ShowCursor(0);

// load resources
… snip …
}
[/sourcecode]

Clean screen before drawing
Add function to the surfaceDrawer
[sourcecode language=”cpp”]
class SurfaceDrawer {

public:
… snip …
void clearToColor(SDL_Surface * target, Uint32 color);
[/sourcecode]

And implement this:
[sourcecode language=”cpp”]
void SurfaceDrawer::clearToColor(SDL_Surface * target, Uint32 color) {
if (target == NULL) return;
SDL_FillRect (target, NULL, color);
}
[/sourcecode]

Don’t draw the purple background
What we want is to skip a certain color when blitting a surface to another surface. We can do this by specifying a color key. This color will be skipped with drawing. The nice thing about the surfaceDrawer is that all have to do is add a function there to do this and change the call in Game to use the new function:

Add function to the surfaceDrawer
[sourcecode language=”cpp”]
class SurfaceDrawer {

public:
… snip …
void drawTransparant(SDL_Surface * from, SDL_Surface * to, int x, int y);
[/sourcecode]

One thing to note, in D2TM the assumption is that all colors with RGB: 255,0,255 (purple) will be skipped. That is the reason the surfaceDrawer does not have a color parameter. We could add this if it is needed later on.

Implementation:
[sourcecode language=”cpp”]

void SurfaceDrawer::drawTransparant(SDL_Surface * from, SDL_Surface * dest, int x, int y) {
Uint32 colorkey = SDL_MapRGB(from->format, 255, 0, 255);
SDL_SetColorKey(from, SDL_SRCCOLORKEY, colorkey);
draw(from, dest, x, y);
SDL_SetColorKey(from, 0, 0);
}
[/sourcecode]

The first line actually creates the purple color. The code is not that selfdescribing. Later on I will introduce a Colors class that basically says “give me purple”, and does the SDL_MapRGB in its implementation.

Of course, now in the Game we have to make a few adjustments.
[sourcecode language=”cpp”]
void Game::render() {
surfaceDrawer.clearToColor(screen, Colors::black(screen));

int mouseX, mouseY;
SDL_GetMouseState(&mouseX, &mouseY);

surfaceDrawer.drawTransparant(mouse, screen, mouseX, mouseY);

// flip screen at the end
SDL_Flip(screen);
}
[/sourcecode]
Two lines are added, first clear the screen to a specific color (black), and then for drawing the mouse we use the new drawTransparant function.

And after compiling, it looks like this:

Drawing a mouse, that leaves no 'trail', and skips the purple color

Drawing a mouse, that leaves no 'trail', and skips the purple color

Next blog post
Although we are able to draw stuff on the screen, it is far from efficient. If we want to draw a terrain we have up to 16 different surfaces for one terrain type (lets say, rocks). It is not doable to hold 16 different SDL_Surface’s and then draw the correct one. Besides, we also have spice, mountains, sand, hills, spicehills. So we need to do something clever. Thats where a tileset comes in. The next blog will be about that.

A side note about including SDL in every header file
One thing you’ll notice about my class definitions, is that I seem to include SDL all the time. Tutorials will say you’ll provide this at the top of your project in your main class (in this case it has to be main.cpp). Although I understand why (since the preprocessor will put the SDL code there, and will be accessible to all other files), it violates the SRP. In fact, you cannot compile a single CPP class anymore using SDL, since you do not refer to this.

As you can see in all my header files, there is a piece:

[sourcecode language=”cpp”]
#ifndef SOMETHING
#define SOMETTHING
// here is code
#endif
[/sourcecode]

This basically says “whenever I have not yet defined SOMETHING include the piece of code, and define SOMETHING”. This allows us to include the same files over and over again, but we are sure the preprocessor only includes it once. This is needed because else your program will not compile due multiple definitions of the same class.

So now:
– I can compile any CPP file seperately (and, the big plus: I can use that for testing later on! :))
– I know what all my dependencies are, they are not somewhere else hidden

End of side-note

D2TM Rewrite – Development Blog – SDL initialization & initial game setup

In my previous post I have described a way to compile your project with a Maven style like project structure. Using that as basis I am busy rewriting my project Dune II – The Maker. This time I am using SDL.

Because I have started over I thought of writing blog posts about my progress. Blog posts will be about progress made, decisions taken, etc. This is by no means a real tutorial sequence, but you could follow the blog posts probably and make something out of it. Do note: In reality I am much further in development then my blog posts. The blog posts are based upon older revisions than HEAD. If you are interested in the most recent version you can get the source yourself.

In this blog post I will describe how I have started to setup the project. I already have a directory structure as described in my previous blog post.

My goal is to have a primitive architecture set up, I have used the first SDL tutorial as starting point.

The reason I went with a tutorial is that I wanted to be inspired by a different approach than I have done myself in the past. In fact, I have always just tried to do what I thought what was best. In this case I took the tutorial and from there I will change it how I think it should be. Its never bad to take a fresh look at things 🙂

The very first start was to create a Game class, it has the following class declaration:

[sourcecode language=”cpp”]
#ifndef GAME_H
#define GAME_H

#include <SDL/SDL.h> /* All SDL App’s need this */

class Game {

public:
int execute();

private:
bool running;

int init();
void shutdown();

void handleEvents();
void update();
void render();

void onEvent(SDL_Event * event);

SDL_Surface * screen;

};

#endif
[/sourcecode]

The only function that needs to be exposed is the execute method. All other functions are used internally.
The SDL surface screen represents the main display (screen).

The Game class is implemented as follows:

[sourcecode language=”cpp”]
#include "gamerules.h"
#include "game.h"

#include <iostream>

using namespace std;

int Game::init() {
if((SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO)==-1)) {
printf("Could not initialize SDL: %s.n", SDL_GetError());
return -1;
}

screen = SDL_SetVideoMode(640, 480, 16, SDL_SWSURFACE);
if ( screen == NULL ) {
printf("Unable to set 640×480 video: %sn", SDL_GetError());
return -1;
}

return 0;
}

void Game::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
onEvent(&event);
}
}

void Game::onEvent(SDL_Event * event) {
if(event->type == SDL_QUIT) {
running = false;
}
}

void Game::update() {

}

void Game::render() {

}

void Game::shutdown() {
SDL_Quit();
}

int Game::execute() {
if (init() != 0) {
return -1;
}

while (running) {
handleEvents();
update();
render();
}

shutdown();

return 0;
}
[/sourcecode]

The execute function does basically everything. A game loop is in essence very simple. In fact the game is one big loop which does two things:
– update state
– show state

To update state, in this case we have separated two things:
– handle events (in SDL terminology, this means we handle input events. Which can have effect on the game state)
– update (here you actually update the game state)

That still remains updating game state, though a bit more split up. We could later split it into keyboard/mouse states. But, these things all are depended on the certain kind of game state you’re in. A main menu screen should react differently on mouse input than lets say the actual game playing. The current design has not given any direction yet what to do. We could have one big switch statement, but we could also do something better… I’ll come to that in a future blog post.

The init function basically sets up the application. I am not too happy about this in this stage, but for the initial setup it is good enough. I believe the factory pattern should be used for constructing a game object though, so I have already created a class for it. The reason is that i want to respect the Single Responsibility Principle. Constructing a Game object, which requires loading resources, setup SDL, etc, has nothing to do really with the basic Game object itself. In fact, as you will see in later blog posts, the Game object has the only responsibility and that’s calling all the right collaborator classes that make the game what it is.

Since I already know I will be using a factory class I already introduce one which for now does nothing spectacular:

Header:

[sourcecode language=”cpp”]
#ifndef GAMEFACTORY_H
#define GAMEFACTORY_H

#include "game.h"

class GameFactory {

public:
Game create();

};

#endif

[/sourcecode]

Implementation:

[sourcecode language=”cpp”]
#include "gamefactory.h"

Game GameFactory::create() {
Game game;

// TODO: load resources for game, do SDL initialization, etc.

return game;
}
[/sourcecode]

Finally the main.cpp which has the entry point of the application:

[sourcecode language=”cpp”]
#include "gamefactory.h"

int main(int argc, char **argv) {
GameFactory gameFactory;
Game game = gameFactory.create();
return game.execute();
}
[/sourcecode]

And thats it! The result is a game that is able to start, it has functions that declare several phases in the game and allows us to expand it further. Because of the factory we can also easily move initialization code out of the Game class.

If you would compile this, and run it, you would see:

A running application

As for developing applications, I believe a certain principle lies behind it. Most of it, you won’t really see. Often, with a few lines of code you can make a lot of stuff happen on the screen. But the actual work is ‘under water’:

Slick java library and 64 bit

Note: This post offers a Windows JAR/DLL package. I have delivered a newer version, also for Linux/Mac OS X. Get them from here

A long while ago I played around with Slick. A game library for Java. It offers easy 2d graphics drawing with the speed of OpenGL (by using LJWGL). It has much more features than that as well. 

When I tried it I was running Win XP 32 bit. However, recently I was trying my code again, this time on Windows 7 64 bit, and I encountered the following error:

lwjgl.dll: Can’t load IA 32-bit .dll on a AMD 64-bit platform

I could not find a decent solution easily, but I fixed it by doing this:
Get the latest source of Slick
Download the latest LJWGL version
– Use the latest LJWGL JAR and DLL files and put them into the latest source code of Slick
– Run “ant dist” of Slick

Use the newly generated JAR of Slick and the new DLL files of LJWGL together, and you’re all set for 32 AND 64 bit!

If you just want to download everything (DLL and JAR’s), I’ve made a little archive for Windows users. It is unofficial though, no support given!. Grab it from here.

An example of refactoring

As I have promised in my previous post, I would post an example of small refactorings in order to greatly improve the readability and understandability of code.

I own a little project called Dune II – The Maker, and I started writing it a little over 10 years ago. In those years I have learned a lot. I did not have much time in those days to apply my new knowledge to the project. You could say the software was rotting. In order to make it better I need to refactor a lot and I encounter the best examples to improve code without pointing fingers :). In any case I have experienced you have to make mistakes in order to get better. I hope you will learn from the mistakes I made.

So here is a little example I have just checked in the dune2themaker repository, I’ll give you the before (revision 411) and after (revision 412). Of course, I have taken smaller steps to get to the end result. First the original piece of code:

Revision 411 (before)
[sourcecode language=”cpp”]
void cGame::think_winlose() {
bool bSucces = false;
bool bFailed = true;

// determine if player is still alive
for (int i = 0; i < MAX_STRUCTURES; i++)
if (structure[i])
if (structure[i]->getOwner() == 0) {
bFailed = false; // no, we are not failing just yet
break;
}

// determine if any unit is found
if (bFailed) {
// check if any unit is ours, if not, we have a problem (airborn does not count)
for (int i = 0; i < MAX_UNITS; i++)
if (unit[i].isValid())
if (unit[i].iPlayer == 0) {
bFailed = false;
break;
}
}

// win by money quota
if (iWinQuota > 0) {
if (player[0].credits >= iWinQuota) {
// won!
bSucces = true;
}
} else {
// determine if any player (except sandworm) is dead
bool bAllDead = true;
for (int i = 0; i < MAX_STRUCTURES; i++)
if (structure[i])
if (structure[i]->getOwner() > 0 && structure[i]->getOwner()
!= AI_WORM) {
bAllDead = false;
break;
}

if (bAllDead) {
// check units now
for (int i = 0; i < MAX_UNITS; i++)
if (unit[i].isValid())
if (unit[i].iPlayer > 0 && unit[i].iPlayer != AI_WORM)
if (units[unit[i].iType].airborn == false) {
bAllDead = false;
break;
}

}

if (bAllDead)
bSucces = true;

}

// On succes…
if (bSucces) {
// <snip>

}

if (bFailed) {
// <snip>

}
}
[/sourcecode]

The intention of the think_winlose() function is to determine if the player has won or lost, and if so it transitions the game state. These transitions have been snipped.

So when does a player win or lose? It depends if there is a ‘win quota’, or not. The win quota is a number, whenever it is above zero it means the player has to collect at least that many of credits (spice) in order to win. If the win quota is not set, the default win rule : destroy everything of the enemy, will be used. (do you notice I need this much text for just a simple rule? Which I could have prevented If I had code that said this in the first place? At the bottom of this post you can see what I mean :))

Lets take a look at the code and point out what could be done better:

  • There are two booleans bSuccess and bFailed. Which is confusing and ambigious. What is succesfull? What did fail? Why aren’t they one boolean?
  • There are comments all over the place, meaning we could refactor these pieces to code so comments are not needed. (Comments are seen as clutter and should be removed)
  • The code formatting could be done better. If statements should start with { and end with }, even with one line.

And there are more things you will probably find yourself. What I’ll do is point out a few things that could be improved. If you just want to see the final result, just take a look below.

Lets start with the booleans bSuccess and bFailed. Why are there two booleans and whey are they called so vaguely? A little bit of searching in the code and we find out that bSuccess actually means “Mission is accomplished” (player has won), and bFailed means the player has no units and structures (which implicates the player has lost the game). They are not the same boolean, because a player could be alive and not have yet won the game of course. Now we know they are not actually the same boolean, but their naming was vague. A simple “rename variable” made things easier to understand!

[sourcecode language=”cpp”]
void cGame::think_winlose() {
bool bMissionAccomplished = false;
bool isPlayerAlive= true;
[/sourcecode]
(when posting this I realize the two booleans are named differently, consistency is also important to improve readability, so either both should start with “is” or both with a “b”, I prefer the first though)

Right after the booleans a few for loops are used just to find out if there is anything alive for the player. A little bit below we see such for loops again, but for the AI. This is duplicate code and should be removed. Extracting them into a method and make them return a boolean value is easy to do:

[sourcecode language=”cpp”]
bool cGame::playerHasAnyStructures(int iPlayerId) {
for (int i = 0; i < MAX_STRUCTURES; i++) {
if (structure[i]) {
if (structure[i]->getOwner() == iPlayerId) {
return true;
}
}
}
return false;
}
[/sourcecode]

(Again, while posting this I realize this could be even improved a bit more, the iPlayerId should be called ownerId (or the getOwner should be a getPlayerId), so it is obvious we match two of the same kind. Now it could confuse us: is an owner the same as the playerId? Since I know it is, why isn’t it called that way?… :))

Since we extract these for loops we can now set the isPlayerAlive boolean immidiately instead of setting a variable within the loop as it was done in the original example above. Reducing 24 lines into one!:

[sourcecode language=”cpp”]
bool isPlayerAlive = playerHasAnyStructures(HUMAN) || playerHasAnyGroundUnits(HUMAN);
[/sourcecode]

The final result of revision 412 is shown below. It will clearly show the major improvement regarding readability and understandability. Any other developer who comes to this code can see what it does and it is almost a no-brainer.

Result revision 412
[sourcecode language=”cpp”]
void cGame::think_winlose() {
bool bMissionAccomplished = false;
bool isPlayerAlive = playerHasAnyStructures(HUMAN) || playerHasAnyGroundUnits(HUMAN);

if (isWinQuotaSet()) {
bMissionAccomplished = playerHasMetQuota(HUMAN);
} else {
bool isAnyAIPlayerAlive = false;
for (int i = (HUMAN + 1); i < AI_WORM; i++ ) {
if (playerHasAnyStructures(i) || playerHasAnyGroundUnits(i)) {
isAnyAIPlayerAlive = true;
break;
}
}

bMissionAccomplished = !isAnyAIPlayerAlive;
}

if (bMissionAccomplished) {
// <snip>

} else if (!isPlayerAlive) {
// <snip>

}
}
[/sourcecode]

Using Slick to write 2D Java games

I have written a few games in the past. A recent example is Dune II – The Maker. I have written a platformer (in QuickBasic even..) and so forth. You may even consider RealBot a ‘game’ (although it is more a computer controlled opponent).

I haven’t really tried to write any games in Java. Although I do program in Java quite a lot these days. Especially for the web. But it seems there is (for some time now) a game library that I might try out.

The library is called Slick and when looking at its website, forum and documentation (API and get-started) it has some promise!

I have tried setting up a simple project with maven, including slick stuff, and wrote a little engine that only draws some blocks and bounces them at the borders of the screen. So far it works great.

Although writing games now is not my priority at all, I will get back to this once I have finished my thesis about Software Quality.

In the meantime, you might want to consider looking at Slick. Give it a chance!

Game Programming (Experience)

Recently I saw at Youtube someone telling about his view on game programming. His targetted audience was for those who want to create games, but have no clue how to start. He began with something along the line of “I’ve been programming games for 5 years, so I guess I could say I’m experienced“.

That got me thinking. How long have I been programming (for) games?

I’ve been working on Arrakis since I was around 14/15 years old. I’ve finished it when I was 18. Arrakis is written in Basic (using Quick Basic 4.5). I realized in order to get further I had to learn a new programming language. One that did not had the limitations as Basic. Thats when I had decided to learn C. My first attempt was writing a new Dune II clone, this time really using the Dune II graphics.

After a short period of learning C I began playing around with the Half-Life SDK; I’ve been toying around with a bot framework (Botman’s bot) and before I knew it, RealBot was born. RealBot has been developed for around 4 years.

And, to complete the circle; while RealBot was fading away I picked up again my Dune mania and recreated Dune II – The Maker from scratch. 

Today, I am 26 years old. I haven’t worked on Dune II – The Maker seriously since 2006. This would mean I would have rougly around 7 to 8 years “experience”.  So considering that, I might also say that I have experience in game programming.

When you look at my LinkedIn, you see none of those projects counted as experience. Sure, they are mentioned
under “websites”. But I would prefer to put them in a more suited spot. Perhaps somebody has a suggestion for that.

Although ~ 8 years might sound like a lot. I do think it has to taken with a grain of salt.

First, I did not work 8 hours a day, 5 days a week.
Secondly, I did not have any sparring partners,  so quality wise I did not write superb code.

However, there are concepts that I’ve learned; and you only learn those when you write games. Concepts like:

  • sprite/bitmap management
  • drawing maps / tile engine
  • A*
  • parsing files (from original game)
  • little AI, 
  • state machines, 
  • double buffering
  • blending techniques
  • team colouring (in RTS)
  • using colorkey’s
  • transparancy
  • palette manipulation

And probably a few other things I can’t recall at this moment.

So yeah, perhaps I could say I do have experience in Game programming…