Build a complete game with Python and PyGame
The drawGrid Function
The drawGrid
function walks through the self.grid
dictionary and draws the entire grid. Lines 57 and 58 start loops that match the dimensions of the grid. Line 59 draws a 1-pixel rectangle in blue to create the grid itself.
Lines 61, 63, 65, and 67 draw the appropriate color of filled rectangle based on what is occupying the square. That is determined by the chain of if
/elif
/else
statements on lines 60, 62, 64, and 66.
Note that the ( x , y )
tuple is the index into the dictionary. If the chain drops all the way through to the else
(line 66), then a black (empty) square is drawn. Finally, line 69 flips the display and draws changes to the real screen.
The checkWinLose Function
The checkWinLose
function is called after each turn to see whether the game is over. Line 72 initializes mycount
to 0
. Then, line 73 starts a loop that iterates over the robots
list. It is enumerated solely for debugging purposes.
On line 75, bot
will contain the coordinates of one of the robots. This is checked against the grid to see whether that square really is a robot. If so, then the counter is incremented (line 76).
After the loop has finished, line 79 starts looking at the results. If mycount
is zero, then no robots are left and the player has won. Line 81 checks whether the player occupies the same space as one of the robots. If so, then the player has lost; otherwise, the game condition is somewhere in the middle, so None
is returned. (See the "#DGB" box for more details.)
#DBG
You're probably already aware that # marks a comment in Python, so the rest of the line is ignored. It's a handy way to disable code for testing purposes. During the course of programming the robots game, I tried a couple different methods to check for robot collisions and other game activities.
This led to a lot of print statements to see what was happening internally in the game logic. Rather than remove them entirely, I left them in the code tagged with #DBG
. If you want to see what the program is "thinking" remove #DBG
to enable the print statements.
« Previous 1 2 3 4 Next »
Buy this article as PDF
Pages: 8
(incl. VAT)