Friday, November 6, 2009

Perl/Tk Games: Snake

Hey, see what, my Snake in action!

Unbelievable - The script is developed using only 5 hours! This is really out of my expectation. I had previously used 6 hours to wrote just a simple Minesweeper - that game only use buttons with number/text . (e.g. '@' as boom, 'P' as flag and etc).

I got the idea to write a Snake while I am on my journey from Penang to my hometown - Ipoh in Saturday morning. Initially, I am still thinking whether I could get it done before Monday. But I never expect to it could be completed right before the dinner of the same day!

The reason behind is because of the implementation of Snake is much straight forward compared to Minesweeper. In Minesweeper, you need to make OOP design for those cells. When player click on an empty cell, you need to call a recursive "Open" on surrounding cells until all adjacent empty/numbered cells are opened. This requires very careful planning and also debugging effort - as you know debug a recursive subroutine is very painful process. In Snake, everything is straight forward, just need draw a circle in front of the existing head and remove the tail. No algorithm involved.
The script has 3 package: main, worm and segment.
  • segment is a single green circle. It needed to hold information of X-Y coordinate, head/tail, direction, pointer to related canvas item and etc.
  • worm consists of an array of segment together with other information. It holds data such latest button pressed (Up/Down/Left/Right), the array of segment instances and etc.
  • main: the GUI initialization, keyboard bindings and etc.
The script has 400 lines of with GNU-styled code. Tested in Win32 only.
Note to those who haven't read my previous posting: I am Perl hobbyist and write script for fun. :-)