Tuesday, July 8, 2014

"saneblockerG" a pygame experiment

Making progress, one step at a time

After my last attempt at programming Python with a graphical library (see http://blog.peileppe.com/2014/05/squadron4-game-now-in-graphic-mode.html)– I had used pygcurse, because I was familiar with the 'curses' library, and that was the next logical step.
But obviously there were limitations, meaning that I would only be able to have more or less the same experience using a sort of a grid, and fonts characters to play with (no actual "sprites").

Pygcurse served its purpose well, I started to understand better how to implement graphical elements and make them interact – but my real interest, has always been to put little sprites everywhere. And since Pygcurse is just another layer between python and pygame – I made the next logical step by programming the new game in Pygame only.

Commenting the source

As usual the program starts with a few constants (to avoid using 'magic numbers' something I learned in the excellent book by Al Sweigart called "Making Games with Python & Pygame ") and then the load_image function (I borrowed from the oldalien.py source file that is provided with pygame) – then I create my 3 classes "Block", "Ball" and "Player" in the same way I did for the last source - see previous post).

Then in the main program I setup the environment, load the sprites – and go in a loop that will exit when the player press "ESC" or "Q" – I struggle a bit to find a good FPS (frame per second) timing for the game, and avoid the "avatar" to move an extra step (which happened quite a lot, I noticed in many pygame examples) by waiting for the event KEYDOWN to update the avatar position.

The funny thing about this game, is that it's actually based on a "odd" behavior of the ball class that would sometime get stuck and not being able to find a valid position to move into – I solve this by having a loop (using the variable "sane") to search for all possible positions and if it fails, the ball then is considered frozen.

That's where the saneblockerG name comes from.

Want more?


The game could be certainly improved – by for example stopping after the last ball is stuck.
Or by having more flexibility in the ball's trajectory (avoiding the repetitive diagonals)

But the purpose was just to have a first pygame playable game. And the program is there on google code if anybody wants to improve it, so … the plan now is to program another one, going further in the difficulty and having multiple sprites to simulate movements, or dialogs, … 

No comments: