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