Thursday, 9 September 2010

Angry Robot Rampage is OUT!

Angry Robot Rampage has been released on Xbox Live Marketplace!

The feeling is quite surreal that something I have made is now being played across the world (well I hope it is anyway)

If you have been so kind as to download and play my game, I am eternally grateful to you and would love nothing more than to give you an enormous hug and/or high five. I really hope you enjoy playing it and that it puts a smile on your face.

Here is a fan page if you are interested in spreading the love - http://www.facebook.com/pages/Angry-Robot-Rampage/112880442102923?v=page_getting_started

You are welcome to follow me on Twitter as well at http://twitter.com/pr0g89

Thank you so much for your time and interest, I appreciate it more than you'll ever know.

Monday, 6 September 2010

Angry Robot Rampage

It has again been a long while since I have written anything here and to those of you who care (if there are indeed any of you out there) I apologize. On a positive note however, I have actually been working on something that might be worth writing about.

Over the past two months I have been working on a game for Xbox Live Indie Games, and it is now on the verge of release - This is my story.

In the beginning, I knew whatever I was going to work on would need to be small - I had to be able to complete it over the summer. That meant no sweeping story-arcs, no endless levels escalating into ever higher and obscure difficulties, and no torrents of exposition about the characters motivation and inner most feelings (not that there's anything wrong with these things - but I knew I didn't stand a chance of pulling off such a game). I needed something with a small enough scope so that it could be reasonably polished, fun to play, and artistically appealing.

In mulling over ideas for the game, one idea kept coming back up, and that was SHOOTER. I had recently played a fantastic game for the iPhone called 'Zombieville: USA' (I highly recommend checking it out if you have an iPhone) You play an intrepid adventurer batting through hordes of zombies while slowly leveling up and gaining new weapons, it has some really nice design, and a wonderful art style. I wanted to create something like this then, but what, and how?

Work began very slowly. The first thing I knew I needed was a protagonist, but how to create such a chap? I began by creating a little man through the use of a sprite sheet (where I would draw each individual frame of him running) but this soon proved to be far more arduous and time consuming than I had first anticipated. (I can draw, but an artist I am not - My respect for animators and people who do this full time has increased exponentially - especially the artists who worked on the XBLA game 'Shank'). To remedy my inadequacies in the art department, I decided that the protagonist could be updated and animated (though somewhat crudely) through the wonders of computer code. The hero was born.

I had a man on screen, bobbing up and down in front of the CornFlowerBlue background that all XNA coders will be familiar with, but then I realized - 'What the 'heck' do I do next!?'

This stage of development is probably one of the worst (perhaps just behind bug fixing). You know what you want, but as with anything in programming, there are about five million different ways of going about it. To get me moving again, I went in search of inspiration. I am eternally grateful to the example code and tutorials at creators.xna.com. I dug through many of them, looking at techniques and examples to give me a better understanding of what I should be doing, and how I should be doing it. In particular I would like to make mention of the GameStateManagement and SafeAreaBounds examples. They helped me a lot in the beginning in getting my game structure working as well as the lovely scrolling background.

A few weeks later and things were slowly starting to take shape. I had a robot who would follow you round, a scrolling background, different states to handle my game, and.... well that was about it. At this stage I had what you call programmer art. (Please see below)


It was time to step up the time I was working on the game and start making stuff look cool! I contacted an old friend of mine named Richard Dorran, a fantastic artist and video game compatriot. I realized if the game was going to look any good at all I was going to need some lovely background art (largely to distract from the mediocre game play). Richard happily agreed, and it was then that the game went from 'lame prototype' to 'OMFG, this looks like a real game!'

Many discussions ensued ranging from the number of enemies to the color of my protagonist bandanna. Slowly things started to take shape, and within a few weeks, we had something that looked like this.


It was looking better, but the game play was pretty dreary (far more than it is now believe you me). It was over this part of development where programming is the most fun. You have the basic structure in place, and adding features doesn't seem as painful as before. You can experiment a lot, and see what works, and more importantly, what doesn't. It was in this phase that grenades were added, as were the red patches on the enemies back to cause them to blow up in one shot, and finally a flying enemy to make the enemies ever slightly more varied.

Before I knew it we were nearing completion. At this stage focus was moved to the sounds and menus and all other manner of things not related to the game itself (which all add up to be a lot more than you think). Another good friend of mine, one Ed Trethowan provided some lovely background music while SoundSnap.com provided the screams and dulcet tones of my hero that grace your ears. It was here too that I realized we needed a developer name, and ToRchEd was born (See if you can guess why that was the name)




The last and final hurdle was the addition of a high scores table. This was one the most painful programming problems I have ever experienced. The save and load operations required for a high scores table worked perfectly on the computer, but as soon as you tried to run it on the 360.... BOOOOOM - Error Code 4, thank you, try again. You of course cannot debug your code while it is running on the 360, so good luck finding out exactly what went wrong. I was stumped for a while on this but finally managed to crack it (I will upload how I did it soon if anyone is interested)

Now came the scariest part of all - submission. Up until this point it had only been me, my family and a few close friends who had laid eyes on the game, seeing it slowly take shape over the weeks and moths I had been working on it. Their comments were always positive and encouraging, but what happens when you throw it out to the internet.. What if they hate it? What if all of this has been for nothing!? Luckily things went smoother than I had thought, the community at creators.xna.com are very friendly, and they were constructive and helpful in their criticism. It is thanks to them that multiple weapons were added as well as a slightly higher jump, and a slew of other small fixes.

So here ladies and gentlemen, is the finished article.


As I sit here typing the game is in the process of peer review and should be out within a week or so. It has been a roller coaster ride, with ups and downs, and thrills and chills. It has been a fantastic experience, and I cannot wait for the rest of you adorable people out there to be able to play it!

I'll post here again when the game is available for public consumption.

(P.S. Here is a link to a video of the game! http://www.youtube.com/watch?v=ix31gnNFgJU Enjoy :))

Wednesday, 12 May 2010

Tower Defence is Finished!

Apologies it has been a while since I have written anything here, hopefully this will make up for it.


Well my Final Year Project is done, finished, finito! The hand in for not only the code but the 15,000 word dissertation was the 6th of May. In the week since I have been primarily breathing sigh after sigh of relief that it actually turned out okay. Below is a screen from the end result.






It wasn't perfect, there were bugs, there were things that I'd have done differently, things I wish I could change, but considering it was the first 'large' piece of software I have ever written, and definitely the one I have spent the most time on, it certainly could have been worse.


The experience was a roller coaster ride of emotions; Joy, despair, love, hate, pride and disappointment. There were times of pure ecstasy when features would come to life, and moments of sorrow and anger when things just didn't work. At times the code would seem majestic and beautiful, at others it would look like a hacky mess.

I have learnt so much from the experience. My knowledge of design, construction, debugging, and test has increased dramatically, but I feel the most important lesson I have learnt is the notion of compromise. Being realistic in your aims and what you hope to achieve is so very important to make sure you get something at the end. Now I'm not saying don't be ambitious, please set your sights high, but you have to realise you're not going to create a Call of Duty killer in the space of 6 months as an undergrad comp-sci student.

Now what I want more than anything is to take everything I've learnt and apply it to something new, something better, something even cooler!

Thursday, 4 March 2010

Height Maps

Greetings and salutations my friends, I hope you're well! I am in a specially good mood today as I have recently implemented a new feature in my game, and it actually looks cool!

Over the last few days I have been working on a cool way of creating a background for my tower defence game. When speaking with my project supervisor Simon, he mentioned it might be a good idea to create a height map which can be used to render a terrain.

First off, a height map is a way of procedurally generating a graphical scene. The height map itself is basically a grey-scale image (think of clouds) which acts as data that you want your program to get hold of. In order to get hold of the data, you go through the image, taking each pixel in turn, finding the intensity (level of white/black) in each one. The values of each pixel correspond to the heights of your vertices when you go to draw your scene. So white would be the highest point, and black would be the lowest, with all the greys somewhere in between. As you draw your vertices, you go through the list of pixel data and set the height to the corresponding value (you can of course scale this afterwards if you want).

This all sounds perfectly simple and straightforward, and I guess it is compared to some problems you'll face, but as I have come to learn, things are never as simple as they first seem. The first problem I had was getting hold of the actual pixel information itself. I am using SDL to load my images, and while the SDL_Surface object is great, it is not at first blindingly obvious how to get hold of each pixel. Realising I wasn't going to get that working first, I decided to get the drawing code working, and then work out what the height values would be after. Here is what I got first try...


Looks bad I know, instead of finding the height values from the height map image, I randomly set the values between 0 and 100 for each vertex; this was the result. Green probably wasn't the best choice either. At least I knew something was drawing which was a start. I then went about getting the pixel information to work, and I solved it with this little method:

get_pixel(SDL_Surface *surface, int x, int y)
{
Uint8* p = (Uint8*)surface->pixels + 3 * (y * surface->w + x);
return *( Uint16* )p;
}

Here you pass in your SDL_surface that corresponds to the image you have loaded, and the x and y values of the pixel you want to find (the coordinates of the pixel), you next store the pixel information in a pointer to an integer, (the pixel value is stored as an int) and then return it.

Once you have all those values (stored helpfully in a two dimensional array) you simply have to put them into the appropriate place in your drawing code, (which I had finally figured out after several hours of research and bouts of trial and error). I finally got something that looked like this, based on the height map below.


I was skipping and dancing around after I first got this to work. There was no lighting, I was just incrementally increasing the colour from dark to light in each triangle I drew. I then went about getting the lighting code to work, and finally ended up with this:


Success at last! I understand it does kind of obscure the playing area but you get the idea! I have to thank www.videotutorialsrock.com for a lot of information on height maps and techniques on how to create such an effect, I will hopefully be able to move it out of the way of the grid soon too!

Sunday, 28 February 2010

Tower Defence ideas and a bit of code

Recently in my tower defence game I decided it would be cool to allow opposing players to place bombs over one another's towers in order to destroy them for a certain amount of resources. My thinking was that this would introduce an extra element to the gameplay where by a player has to balance their resources to afford new towers to fend off the enemies, as well as also trying to destroy their friends towers to make life harder for them.

I wanted to implement the bombs so you could have as many as you wanted at a time, so as I have done with my enemies and my towers I created a good old c++ vector (a smart array, or simply a form of container for my data) that could then be iterated through to update them.

I ran into a bit of a problem when I wanted to remove a tower and a bomb after the bomb had blown up the tower. I needed to know if the bomb I was on as I cycled through the list matched the tower, and therefore knew which tower and bomb to remove.

Here is the code I am using, you probably won't understand it, and it probably isn't the most elegant way of doing it, but by joe it works!


void CGameController::Update_Bombs( CTimer* timer )
{
for( unsigned int i = 0; i < _bombs.size(); ++i )
{
_bombs.at(i)->Update( timer );

if(_bombs.at(i)->get_exploded())
{
         for( int j = 0; j < _towers.size(); ++j )
{
if( _bombs.at(i)->get_i() ==
                            _towers.at(j)->get_index_i() &&
    _bombs.at(i)->get_j() ==
                            _towers.at(j)->get_index_j() )
{
_grid->set_occupied( _towers.at(j)->get_index_i(),
                                 _towers.at(j)->get_index_j(), false);

         _towers.at(j) = _towers.back();
_towers.pop_back();

_bombs.at(i) = _bombs.back();
_bombs.pop_back();

break;

}
}
}
}
}

Basically what I am doing is iterating through all my bombs, I update each one in turn, and check if it has exploded. If it has indeed exploded, I then cycle through all my towers, and then do a comparison with the grid square of the tower and the bomb, to make sure they match, and then I remove both of them. It works perfectly, but only with the help of my friend 'break;'.

Without that helpful command, if the first bomb in the bomb list was matched with a tower halfway through the tower list, and the bomb was then removed, the tower list would keep iterating through, and would try and compare itself with a bomb that no longer existed! Not good! I got a horrible run time error, and panicked quite a lot, but then remembered I was missing a 'break;' and then suddenly all was lovely again.

If you can think or a far cleverer way of accomplishing what I am trying to do I would love to hear it, no doubt I am sure there is, but I am just glad it works, well mostly.

Saturday, 27 February 2010

Tower Defence Update

Firstly let me apologise for my lack of updates, I have been pretty swamped thinking about my project and working on my code lately. I kept coming to write an update but didn't feel like I had anything particularly great to talk about so I decided against it.

I thought now was as good a time as any as I feel as though I am finally making some head way on my project. I now have a game that two people can actually play in competition with one another. That might not sound like much, but now the game can actually be played I can start thinking about balancing all the variables I have carefully crafted into the game. Things such as wave speed and number, tower fire rate and damage, and resource costs can start being honed so as to create a well balanced and enjoyable experience. There is also the matter of polish with regard to the user interface and graphics that will go some way to increasing the visual appeal of the game itself.

I will try and post some screen shots of what I have soon so you can have a look at it, hopefully it will change more and more in the coming weeks and months.

Thursday, 18 February 2010

Problem Solving

Problem solving is something we humans do all the time. Each day we are confronted with problems ranging from getting your car to start in the morning, to making your way to two parties each taking place on the same night (good luck with that one).

Programming relies on ones ability to solve problems so heavily that the P in programming really should stand for problem, and perhaps the R for resolve (No S's in programming for solve, maybe 'programmers'... I'll keep thinking). If you look at literally any job listing for a programmer, one of the bullet points in which they list the skills required for the job, will most likely be 'Problem Solving'. I remember first seeing such a listing, and thinking what on earth they really meant. I knew I could solve problems (much like the ones listed before, well maybe not the two parties one) but what did it mean with regard to programming. Surely you could just write a program and it would work, you'd have a problem, which would be solved by creating the software itself; for example making a checking system for a hotel would solve their booking system problem. Actually making the program itself is the easy part, right?

Looking back I feel foolish for ever thinking such a thing. You see the problem with programming is that even if you have the perfect design, the greatest architecture in the world, and sharper programming skills than my comedic wit (ahaa...) you will always find yourself hitting road blocks and quandaries that cannot be solved by your initial design. Enter Problem Solving.

To be a good programmer you have to be able to think on your feet. If something suddenly doesn't work as you'd expect, or you realise the thing you are working on just won't work at all. Do not throw your hands up crying 'It's impossible, it can't be done, I am going to drink more coffee'. Instead what you must do is analyse the problem itself, and then think of every possible solution you can. The easy part of problem solving is thinking of great solutions, the hard part is then deciding which is the best or the most appropriate given the time and complexity involved, and then thinking how exactly you implement such a solution. As you program more you will begin to build a tool box of tricks to help you when you reach such problems (which will be often and always) but the most important skills I've found have won out, are patience, persistence, and a willingness to admit you may have been wrong.

The thing you realise the more you program is there is never one solution, you have to pick the best one you can, and when you realise it doesn't work, you have to make it work, by adapting or evolving the original solution. This ranges from lofty design ideas, to small implementation details; they both require the same set of skills to handle correctly.

I would like to tell you it gets easier, but that would probably be a lie. The more complex software you work on, the more intricate the problems, and the harder the solutions. Let me tell you though, when you solve the problem that has been taunting you for the last two hours/days/weeks, and you experience that moment when you hit run, and everything works.... my friend, nothing comes close to that in the world.

Monday, 15 February 2010

A Poem

On occasions/often (delete as appropriate) while you code you will come face to face with problems that seem insurmountable. There seems as though there is nothing you can do, everything is going wrong, and you can't face your monitor.

For when this happens, read this poem, and it might bring a smile to your face and give you the motivation to tackle the problem head on, and just maybe, prove yourself wrong, and do it.

Somebody said that it couldn’t be done,
    But, he with a chuckle replied
That "maybe it couldn’t," but he would be one
    Who wouldn’t say so till he’d tried.
So he buckled right in with the trace of a grin
    On his face. If he worried he hid it.
He started to sing as he tackled the thing
    That couldn’t be done, and he did it.

Somebody scoffed: "Oh, you’ll never do that;
    At least no one has done it";
But he took off his coat and he took off his hat,
    And the first thing we knew he’d begun it.
With a lift of his chin and a bit of a grin,
    Without any doubting or quiddit,
He started to sing as he tackled the thing
    That couldn’t be done, and he did it.

There are thousands to tell you it cannot be done,
    There are thousands to prophesy failure;
There are thousands to point out to you one by one,
    The dangers that wait to assail you.
But just buckle it in with a bit of a grin,
    Just take off your coat and go to it;
Just start to sing as you tackle the thing
    That "couldn’t be done," and you’ll do it.

                                                by Edgar Albert Guest

I am going to frame this and have it next to me for all those moments when it seems like it can't be done, when in fact it can.

Wednesday, 10 February 2010

Over-Engineering

Recently I have been thinking a lot about software design and software engineering. The importance of software design, as I have stressed before, is paramount in ensuring your code doesn't fall apart the moment you start trying to piece it together. The problem with programming however is there are nearly always 20 (or more) ways of solving a particular problem. Often some will be preferable to others, but nearly always you have to make some kind of compromise, and pick the lesser of two evils. There never really is a perfect solution, only the best one you can think of at the time, and there will no doubt be a helpful colleague to come and poke their nose in and tell you exactly how they would have done it instead.

Now when you come to design and implement a certain set of functionality, you are presented with a choice of possible ways with which to handle creating it. I have found there are two main approaches to this. The first is to think of a very rough idea of what you want, attempt to scribble some notes (doodles) in the form of some (very) basic design, and start coding. You are basically trying to achieve the functionality you want as quickly as possible, with little to no concern for who else will need to look at, or reuse your code. The other way, is to create an impeccable design, with a multitude of classes and interfaces that allow an array of functionality you might not even need yet, but you are planning for every eventuality, and for the system to be used over and over again.

Now I am pretty sure which one you think is better, and you'd probably be right. The latter sounds like what a proper software engineer would do, and this is probably true, but that approach might not always be the best or most appropriate solution. This approach is probably a good way to go if you are a professional, seasoned programmer, but for guys starting out, this approach can be completely overwhelming. There are so many levels of abstraction, and so many possible things to worry about, that it all ends up looking and sounding too much to take in and maintain.

What you want is the base functionality to work, and to be able to see it working. This is the best way to learn in my opinion and once you have these fundamentals in place you can start building a better design around them. There may be times when even professional developers take the quick fire approach, if it is a system that is small, and won't be used much, why make an over-engineered solution when you could code something up quickly, and then get on with more pressing tasks.

I am sure not everyone will agree with me, but it often feels like you need to walk before you can run, and there is no way you will create a flawless design without understanding the quick way of doing it first.

Monday, 8 February 2010

I love Visual Studio








I got this error today, I had never noticed it before but it made me smile. Studio can be so helpful at times... at others it can make you want to cave your own head in, this is one of the former.

Sunday, 7 February 2010

Simple DirectMedia Layer

I thought today I'd try and do a blog post with a little bit more codey stuff in it as opposed to the high brow design malarky I've been prattling on about for the last few weeks.

What I've decided to talk about is Simple DirectMedia Layer (SDL). It is a fantastic set of multimedia libraries primarily for C++ that allow you to access an array of subsystems on your computer such as graphics, sound, event handling, input, threads and timers (among other things). You can find the libraries here: SDL.

The whole object of the library is to be as 'simple' (clues in the name) to use as possible, and in my opinion they do just that. SDL supports an array of operating systems so your code will be portable. As well as that there are extension libraries such as sdl_net and sdl_mixer for networking and sound respectively, with even more following those.

These libraries serve as a great alternative to using Windows and DirectX interfaces when on a Windows PC. That isn't to say these aren't a good choice, but SDL does remove a large amount of the complexity of windows programming, and lets you set up a window and start getting stuff working very quickly. If Windows is your development platform all that code will still be there, it is just SDL kindly hides some of it away from you through interfaces which makes some of the boring tasks of window creation a lot easier to deal with, especially for the beginner.

Here is some example code for setting up a window (this won't compile but you get the idea)

// Your handle to the pixels on the screen
SDL_Surface* screen;

 //Initialise SDL

  if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
 {
     return false;
 }

// Set up the surface for drawing to
screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );

//Set the name displayed in the top of the window
 SDL_WM_SetCaption( "SDL Rocks!", NULL );

That pretty much gives you your window, that's all you need! Pretty neat right?

The event handling is also really useful, the calls look like this:

// Pointer to an event in SDL
SDL_Event* event

if( event->type == SDL_KEYDOWN)
{
         //Checks to see if the event was a being pressed;
         if( event->key.keysym.sym == SDLK_a );
}

This is only the briefest of brief introductions, I just really want to make you aware of SDL if you haven't already heard of it. There is a great book with lots of information on it called 'Focus on SDL' by Ernest Pazera which I strongly recommend if you are interested in learning more about SDL. There is also a wealth of information on the SDL website and on sites like GameProgrammingWiki which you can find links to on my blog.

I am using SDL as the base for my tower defence game and while I've had my ups and down with it I have found it to be a great set of libraries to work with.

Have fun and let me know what you think.

Friday, 5 February 2010

Take a break

There are times while you are coding that everything suddenly feels like it is going right, you are in the 'zone' for want of a better word. You are being productive, making progress, and generally feeling like a badass, ninja coder. However for every moment you spend in this zen like state, a hundred more will arise when you are stumped. You reach a point where you feel as though you have hit a brick wall. Suddenly your productivity takes a sharp turn for the worse as you encounter a problem that is simply outwitting you. Now the default reaction to this is to stare unerringly at your monitor for the next two hours making little to no progress as you rack your brain for a solution. My friend, I have an antidote that has helped me in these situations, time and time again; Take a break.

This might at first sound like a daft idea, 'How can you be solving the problem if you aren't looking at it?' Well my friend that is exactly the point, you want to separate yourself from the problem to give your brain time to properly digest all the information. I remember hearing this advice for the first time when I was younger from an excellent lecturer called Rob Miles, who among other things championed this method of working.

If you hit a problem that you really can't seem to solve, take a step back and give your brain a chance to breath. Go and make a cup of coffee, get some fresh air, or do something you find relaxing like playing some music or reading a book. Give yourself a rest in the range of 15 to 30 minutes and then return to your code. I guarantee you will see something you didn't see before, something will have clicked in the old grey matter that had just needed time to process. Sometimes the solution may jump off the page at you, other times you may being experimenting with things you hadn't thought of before, but you will return with fresh eyes, and a fresh perspective. It's like the old saying 'Can't see the forest for the trees'.

Trust me, it really works, and it can help no end when you feel stress building up around a particular problem. Another good idea when you are working on larger projects is to work on another part of the code for a while and come back to the part giving you difficulty, often something might have changed to give you a new idea of how to tackle the problem. If it's late too you're better off getting an early night and waking up early to tackle the problem, most bugs are introduced late at night when you aren't thinking perhaps as well as you would be at ten in the morning!

Now I am not advocating procrastination, these problem will require work and attention, but often these short breaks can prove invaluable in helping you while you code.

Time to go and put the kettle on I feel

Wednesday, 3 February 2010

An Analogy

Recently I have been thinking about software design in analogous terms to that of creating a statue (Don't ask me why, my mind goes to strange places okay). I have been thinking about how the architect of a piece of software may at some point decide to change the design, just as an artist may want to change the pose of a statue while he is creating it.

Now in a perfect world the software architect and the artist should both have an exact idea of the design they wish to achieve, and it is their goal to simply follow the design and implement it to the letter. This however, is often not the case. Each will reach scenarios where they suddenly think of a better design, and then want to change and evolve the original idea. This is as true in art as it is in software; imagine you have an idea for a fantastic pose for your statue, but as you begin moulding the piece you realise it doesn't look quite right and you think of another approach that is far more suitable

Jumping back a second I think to communicate my point more effectively I'll need to explain two terms you will come across in software engineering. The terms I am referring to are 'Coupling' and 'Cohesion'. Coupling describes a relationship between classes when they are heavily dependent on one another. They are literally 'coupled' together, changes made to one class may have repercussions in other classes, and this can then lead to disastrous consequences. In turn this then means making changes to your code can be extremely difficult.

Cohesion on the other hand refers to how well functions in a class are related to one another. So this means you have classes with specific behaviours and routines, not some class called 'GameClass' that has the AI, Rendering, Input, and Networking code all in it. You would want each of these to be in their own classes with their own specific interface. In your code you should always strive for strong cohesion, and low coupling, and you will make life much easier for yourself! (Trust me!)

So I hear you asking where the hell does my statue analogy fit in? Okay, imagine creating a statue out of clay (or Play-Doh, which ever you prefer) So long as you keep it wet, and fresh, you can pretty much bend and shape it in any way you like, you have complete freedom over how you want it to look. Think of this as a piece of software with high cohesion and low coupling. It is adaptable, and more suited to change. However while working on the statue, if you leave the clay to dry out, it becomes brittle and difficult to manipulate. Attempting to adjust the position of an arm may cause it, or other parts of the statue connected to it to break. You are forced to add more clay in an attempt to repair the damage already done, constantly applying these small 'fixes' leads to an excess of clay and a worse looking statue, just as if your software is highly coupled with low cohesion, you will try to fix problems that arise, but soon adding so much code will serve to make the program harder to maintain and understand, with the final result looking pretty shoddy.

So the morale of this story is always to strive for strong cohesion and low coupling (and don't let your Play-Doh dry out, your mum did always tell you to put the lid back on)

Tuesday, 2 February 2010

Re-factoring FTW!

Recently I decided to take a look over my project (call it a code review) and I came to the conclusion it was time to have a bit of a re-write. I wasn't going to change a large amount of the underlying code itself (I'll leave the joy of optimisation for later) but what I decided to do was to restructure the design of my code so everything would fit together a bit more nicely, and the relationships between classes would make more sense. Another thing I decided to do was to re-name a large amount of methods and classes to give them better more coherent names/descriptors (no more methods called DoCoolStuff() I promise).

I first looked at classes individually and decided exactly what behaviours I wanted them to do. I moved behaviours present in one class to another if they seemed more appropriate in that context, and in other cases split methods in a class into several smaller ones with much more specific names and functionality.

Doing this immediately makes classes easier to deal with; it gives you the ability to work with your classes by just looking at their interfaces and not having to worry about the implementation details of each class.

Once this was done I  decided to begin re-factoring the relationships between the classes themselves. Here is a brief example of how my design changed over time as a result of this.

When I started working on my tower defence game, the code for say, drawing a tower, was right there in the tower.cpp file. This was immediately a bad idea, what I needed was to abstract the drawing routine out into a renderer class, that the tower would then have access to. I went about giving each tower its own renderer, but then realised this was bad, because it meant I was creating lots of renderers when I only really needed one. So I then took the renderer out of the individual classes and created one instance of renderer in my PlayingState class, and it was then passed into a tower draw call when a tower wanted to be drawn. The design was almost there, but today I brought the renderer up one more level so it actually became part of my Engine. I now pass a pointer to my engine to the PlayingState and it then in turn contains the call to the renderer itself.

Now (almost) all of my drawing code is held in this renderer class, and in order to draw anything (or make any OpenGL calls) you must use this class. This gives me a level of abstraction that allows me (in theory I hasten to add) the ability to 'unplug' my current renderer and attach an entirely new one using another graphics API (DirectX says what's up).

What I find interesting is this design evolved with how I was writing my code. I knew in the beginning that the idea of having the renderer as part of the engine was a good idea, I had been told about it, and had read about similar techniques, but I didn't really understand how to implement it from the get go. If you'll forgive the analogy I think I needed to paddle in the shallows before before diving into deeper waters, but what was interesting was this pattern emerged naturally.

So what started out as some (procrastinating) re-factoring, ended up as a pretty big re-write (well for me anyway) and the lessons I have taken away from it are absolutely invaluable, more so I think for having done it wrong the first time.

Monday, 1 February 2010

Reading List

As a programmer, you will find that the need to further your knowledge and understanding will be an ever present factor in your life (I guess that's true if you're not a programmer, but I would say programmers are particularly good at this). As well as of course attending school, college and university (which I strongly recommend) the best way to achieve this is to read.

I love books, I love books almost as much as I love programming (and Keira Knightley for that matter, but I digress). I especially love books on programming itself, and the many areas they cover relating to the all the fields that programming can encompass.

I have a dazzling array of books on programming that range from books on artificial intelligence to xml. As I sit here typing this there are no fewer than 12 books sitting on my desk, all open at different pages, with book marks strewn throughout. They prove an invaluable aid not only in learning new things, and furthering your understanding, but as references while coding. You should approach books on programming differently depending on how they were intended to be read. Some are great to sit back with and read for a few hours without touching a keyboard, others are better used as refernece guides as you type, both are useful in their own way.

Now you might be sitting here nodding a way, all the while thinking 'That's all very well, but it sounds like you haven't heard of a little thing called 'The Internet' and 'Google''. I can assure you I am very aware of such things, and I agree they are extremely useful and convenient, but from my experience online articles often lack the detail and quality you will find in a published book. This could be just me, but I also prefer reading a book as opposed to reading large articles on my monitor (I am aware of the delicious irony that reading this would qualify as reading a large article on your monitor, but it's all I've got, so let's just move on) This is not to say online resources aren't worth using, not at all, but what I would advocate is a combination of books and online material. (Note: Check out GameDev.net, CProgramming.com, XNA.creators.com and NeHe.GameDev.net, some great sites for various areas of programming)

I thought it might be a good idea to list a few books that I have found extremely interesting and useful over the years. Here is a short list of the books I'd read if I was interested in programming:
(Note: Some of these do relate more to game development orientated programming, covering things like OpenGL etc, but they're still worth reading)

Big C++        //An awesome book on C++ covering almost everything you'll need to know about the               language, right from the beginning

OpenGL SuperBible  //An excellent reference for OpenGL covering a huge amount of information on graphics  

Effective C++     //A more advanced book on C++ for once you have a firm grasp of the language itself

Essential Mathematics for Games and Interactive Applications //Excellent reference book for an array of mathematical concepts and problems you will encounter with graphics and games programming

Code Complete     //The best book on software engineering

Learn Programming Now: XNA Game Studio  //Excellent introduction to XNA and programming concepts

Learning XNA 3.0 //Another great book on XNA

C# for Students      //Great introductory book for C#

Programming Game AI by Example //A great book on AI concepts

There are many more, but this should serve as a good start. As you can see some books focus on an implementation language while others refer to ideas and often use pseudo-code. There are definitely good and bad books, I have my share of both, but having a variety to refer to will help you no end while you work.

So there you go, why reading is awesome and a list of some books that you might find interesting

Right, I'm off to curl up with a good book and a warm cup of cocoa

Thursday, 28 January 2010

Do as I say, please

Recently I have been thinking about the old adage 'Do as I say not as I do'. This has been on my mind a lot since my recent entry on the usefulness of variables and their use in combating the problems caused by magic numbers

This is sound advice (trust me) but the thing is, I, as well as many other programmers, are guilty of breaking this rule, a lot (even though they'll tell you they don't). We will probably regret breaking it and curse ourselves for taking the short cut, but it does happen.

In an attempt to maintain the use of such a rule, one must try to apply it at all times, unless a set of requirements are met in which it is appropriate not to do so. So given a certain context, the rule can be broken, but one should ensure the reasons for breaking it are sound and justified. So an example of where using magic numbers may be acceptable is rapid prototyping or throw away prototyping where the object is to get something working as quickly as possible, and the code does not need to be maintained or reused. This would be a time where the rule does not need to be followed to the letter, but you can bet at most other times you should take heed of it.

Other examples of certain approaches which are regarded as dangerous or bad practice are things such as multiple inheritance or use of the goto statement. You are told to avoid such things (which I personally would!) but again you'll find times where it may be appropriate to apply them. Emphasis is placed on them to ensure that if you ever find your self having to implement such a design, you are acutely aware of the potential traps you can fall into, and why they are dangerous to use. (It's also worth adding a host of comments to explain your rationale to other friendly programmers!)

I guess, putting it as plainly as possible, you should take these things with a pinch of salt. These ideas are usually a good thing to follow, especially when you are starting out, but there will always be exceptions, the trick is knowing what they are and when to use them.

Monday, 25 January 2010

The Life Of A Programmer


Magic Numbers

int _health = 100;
_health -= 5;

What do you see?

Firstly, If you have no idea what the preceding lines mean, you're probably better off not reading the rest of this post as it won't mean a whole lot to you. I'd go and check facebook if I were you, I am sure something more interesting is going on over there anyway, however if you change your mind you are welcome to stay.

If you do understand what on earth I am going on about (Greeting fellow nerd), and you see a perfectly acceptable line of code, please get out of my sight and write a console application that prints the line 'I am sorry for my hacking' 100 times. I'm kidding, please don't do that, but please do read on to see why you are quite mistaken.

What you should in fact see is a terrifying example of hacky code. The above line, while maybe, (and I mean maaaaybe) acceptable in a program a few hundred lines long, it is in fact the bane of a programmer's existence when the program begins increasing in size and complexity.

What the '5' represents in that line of code is a magic number, an arbitrary value that can easily and accidentally be changed (often with disastrous consequences), or prove extremely difficult to change if there are lots of them (I'll come to that later). In your programs you should never have values like this appearing in your code. When ever you see a value like this it should scream at you with the sound of an opera singer's wail after a grand piano has just been dropped on their toe.

Whenever you see a value like this, you should immediately think exactly what it is meant to be representing, and then replace it with a variable!

Variables are fantastic things and should be used as much as possible. What they allow you to do is represent a type, be that an integer, a floating point value, or one of your own classes, with a piece of text, that you the programmer can easily process and understand. As the name is associated with a type you know exactly what kind of information it represents too. So for example, an improvement on our previous example is:

int _health = 100;
int _damage = 5;
_health -= _damage;

Immediately it is clearer what is happening, but that really isn't the best part. Imagine if damage appears in multiple places all over your program, suppose you then decide that you want the damage to be '10', not '5' any more (I told you I'd come to it later). If you were not using variables you would have to search all over the program to find every context where '5' was being used to change the health, and updates it's value to '10'. This can easily lead to bugs, and take an inordinate amount of time finding every '5'. If instead you had used _damage, you need only change that value once where it is declared, and all the other values will be updated accordingly.

We can also declare variables with the const keyword if you do not want the value to change. const tells the compiler that the value cannot change after the variable has been defined. This stops you the programmer from accidentally changing the value later in the program, possibly introducing more bugs into your code.

There are many more reasons for why variables are useful, and a myriad of examples, but I won't go into them just now. I hope you found my rant vaguely informative, if not mildly entertaining. I am now going to double check my code and I fear I'll eat my words when I see all the magic numbers staring back at me.

Sunday, 24 January 2010

Drawing pictures

While working on code, you often find yourself confronted with problems that are quite tricky to get your head around. Such problems might range from things like relationships between classes, to detailed path finding algorithms. In my (short) experience I have found a sure fire way to help in defining such problems, and it's simple; draw a picture.

'Wait!' I hear you cry, 'I'm a programmer not an artist, why the hell do I need to draw anything!?'

Now don't get me wrong, I am not saying you should create a work of art, far from it, what you want is a crude abstraction of the problem facing you, and that is more often than not, best achieved with the aid or a picture or diagram.

By creating an abstraction of the problem, you immediately give your brain a chance to breathe, and absorb the information in a new way. It helps you visualise the problem, and allows you to hold it in your hands, add notes to it and see it in the real world. It takes a load off the old grey matter too so you don't have to be storing all the information you need in your head at once.

Universal Modelling Language (UML, of which I am sure I will talk later) is a fantastic tool for this when describing class relationships, program flow and so forth (it's also great because as it's a standard, if you implement it correctly, other people who know UML will understand exactly what you mean) But I'm not just talking about this, I am talking about any problem at all. It could be something mathematical,  some kind of behaviour, some process; if you attempt to draw a picture of what is happening, or create some pseudocode for the underlying process, it will help no end in your understanding.

The saying goes that a picture is worth a thousand words, in programming, I'd say a diagram is worth 10,000 lines of code.

Now get those pens out and start scribbling.

Saturday, 23 January 2010

C++ Errors

This isn't a proper blog entry but I felt I had to say something about this small (GINORMOUS) problem I encountered.

I'll set the scene for you, it was a quiet Saturday morning, I was leisurely sipping coffee as I went about re-factoring some of the code I had written the night before (which now looked terrible compared to what I remembered writing). I had made a few changes, checked over the file I was working on to ensure there weren't any glaring errors such as missing semicolons (Hey, we all do it okay). I hit build, and to my sheer horror, 161 errors leapt at me from the output window.

Now when this happens it is usually something easy to spot like a missing curly brace, and you can quickly fix the problem, but maybe because I had only drunk half my coffee, and it was now tepid and undrinkable, I could not for the life of me find the problem. I poured over the source code, looking in every file that was referenced by the one I had changed. Had I accidentally hit a key while I was changing pages? I couldn't find anything.

Thirty minutes later, with half the hair I had when I started now missing and tears welling in my eyes, I was ready to give up and become an art student (sorry art students). Then, just as all hope seemed lost, I caught something out of the corner of my eye, could it be? There staring me in the face was something that almost made me tear out any remaining hair I had. A class called Projectile was being declared, however it had somehow acquired an 's' on the end, so it was now 'Projectiles'. This typo had caused Visual Studio to throw up 161 errors!

I deleted the 's', hit compile, and Wooosh, everything was working again and the world was lovely...

That's life I guess, and another lesson learned that proof reading, perhaps more so in code than anything else, is intensely important. Now I am off to buy a hat to cover up the bald.

Friday, 22 January 2010

A moment for a joke

Here is an attempt to raise your spirits on a dreary Friday afternoon, a poor programming joke that came to me while writing some code:

How many programmers does it take to open a can of sardines?

10, 1 to open the can, and 9 to tell him how much more efficiently he could have done it.

Drum Roll, Symbol, Applause

( Edit: A better joke with thanks to James in the comments:

How many programmers does it take to open a can of sardines?

10, one to open it, and one to explain binary.

I doff my cap to you good sir )

Or the exact opposite..

With regard to my previous post about the use of comments and the importance of clear maintainable code, please see this http://freeworld.thc.org/root/phun/unmaintain.html

It is a brilliant article on the best ways to create completely unreadable and unmaintainable code to ensure you are the only person who can understand it, by the time you're done chances are you won't be able to understand it either.

Each to their own

(Thanks go to Paul Harsent for the link)

Thursday, 21 January 2010

Comments, Comments, Comments

From the title you may be guessing this is a crass attempt to get you, the poor bugger reading this, to post a comment at the bottom of this entry commending my awesomeness, but my friend it is not. Instead I thought I might briefly talk about the importance and usefulness of comments in code.

Often you hear from hardcore coders that commenting is for wimps, this sentiment comes from the same group of programmers who follow the mantra, 'If it was difficult to write, it should be difficult to read'. While these people may be justified in their beliefs, and lets face it, they do sound cool, in the long term it really isn't a good idea.

Now don't get me wrong, I am not condoning such enlightened commenting as:

                                         int val = 5; // val now equals five

This is clearly irrelevant, and only serves to de-emphasize comments that may actually be useful later on. I am talking about a brief description above a short piece of code or algorithm that briefly describes what it does. This could be as simple as //calculate shortest distance, or //rotate according to new position.

Now you could argue in these scenarios that the best idea is to create functions or methods with meaningful names such as CalculateBalance() or UpdatePosition(). This is a great idea, and often it is sufficient, but occasionally, especially while you are in the process of writing code, when you return to it, instead of having to skim through it and quickly figure out what it is doing, you can see the little comment descriptor and know exactly where you are. I have found this immensely useful when writing a method, and then when I know exactly what it is doing, I can give it a useful name so I can easily identify it.

Comments are also great for explaining your code to peers and other people who will be using your code. If you have used a certain hack or cool trick, be sure to point it out to the next guy so he doesn't have to rack his brain for why on earth you did it, remember the next guy can easily be you returning to your code a week later, finding a jumbled heap of squiggles staring back at you instead of the elegant code you thought you wrote.

Now this might be a point of contention, but I also love using comments to break up code, it makes it more readable (and more colourful if you are using lovely Visual Studio) and can make scanning through pages of code much easier.

//************************ I love comments *****************************//

void WriteComment( std::string comment );

//************************ I love comments ***************************//

You can't tell me that doesn't look lovely.

So there you go, why comments are awesome, now if only you could write a comment and have it magically turn into code, that would be sweet!

Wednesday, 20 January 2010

Tower Defence! and Design

Okay, I am going to attempt to make a start at this blog by talking about a project I am working on at the moment. Points go to those who guessed from the title that it is indeed a tower defence game.

One of the problems I encountered when starting the project was the sheer number of things you need to create a game, not just a cool tech demo, but a real game. I am going to assume that if you found your way here there is a good chance you have played a tower defence game, it might not seem like much, but when you start adding up all the features you realise there are enemies, towers, map, user interface, artificial intelligence, state management, input, sound, graphics (and networking in my case ) 'Audible Gulp'.

Now each of these in isolation is fine, but the trick with the game is there are relationships between these objects, and certain objects have to interact and update other objects accordingly, and in order for this to happen you need lovely code to properly initialize, update and finally clean up all of these things. The trouble is how you go about doing this.

Enter Software Engineeing! If you talk to anyone who has written a large piece of software they will tell you design is king. It is much better to spend longer on the design, and get it right, than start implementation, and have your shoddy plans fall apart. The only problem is, designing something, when you don't really know exactly what you want, or know the best way it should work, or how it should fit together, without a great deal of experience, is extremely difficult. What exactly do you do then...... Enter Tom!

Now I am in a small conundrum where I know design is important, and I do have a (flimsy) design, but there is also a desperate need (especially given the impetuousness of youth) to see results, and that can happen quickly if you throw design to the wind, and break open your tool bag of tricks to get stuff up on screen. This is intensely satisfying, but often you'll find that your hacking has created a hole (sometimes a black hole) that is now inescable and you find nothing else will work with your new change. The design falls apart and you are left with super glue and nails where girders and beams once stood.

This is the problem with writing code, when you are dealing with something that is intangible, you need a grasp of the structure and design of the software, not just small parts in isolation of one another. But to create that amazing design, you need to know what designs work, and when to use them, and to know this you probably have to fall, at least a few times.

I apologise for my mad ramble, but I find it is a difficult subject to talk about. I do think that it is a trap all too many programmers fall into, but it is one laid so expertly one can hardly blame them. In working on this project I hope to strike some kind of balance, I'll let you know how it pans out!

Tom's Tech Blog

Hello people of the internet!

I'm not quite sure how you found your way here but I'm glad you did. Please pull up a chair, I'll put the kettle on. Coffee or tea? Milk, sugar? Sorry I digress...

This blog is intended for those of you who share my interest in software engineering and programming. I hope in the coming months you'll find an array of interesting things here. I intend to post about what I'm working on, things I'm reading, and hopefully links to other cool stuff on the web.

I think this could be the beginning of a beautiful friendship.