2007-07-23

Canvas Pac Man

Another one of the games I’ve always wanted to have a go at writing was Pac Man, but I’ve never bothered writing it as the thought of having to write a complex pathfinder routine for the AI put me off. Having finally conquered Space Invaders I thought it was about time that I gave Pac Man a try.

After another few hours of fiddling, interrupted by a trip to the pub and half an hour spent researching ghost behaviour, here is Pac Man in a canvas element:

Canvas Pac Man

As it is another game written at speed, it doesn’t feature power pills, levels (the same level repeats over and over), scoring, power-ups or a life display. It does feature two of the AI routines from Pac Man - purple ghosts move about at random, whilst the red ghost takes the shortest path towards the player.

The AI turned out to be very simple - I was all set to either implement the A* pathfinder routine or bodge together one of my own, when I realised that all the red ghost needs to do is move towards the player at every junction - if the ghost can take more than one path, it needs to take the path that will take it nearer to the player if possible. It still has a few bugs in it, but it does the job. To watch it in action you’d never know that it wasn’t a full-blown pathfinder routine, which is ultimately how videogame AI is supposed to work - make the code simple, but make it look complicated in action.

The game is a little sluggish in Firefox, but it’s quick in Safari.