Build a complete game with Python and PyGame
The run Function
The run
function is the main PyGame event loop. On line 145, I initialize running
to True
. This is the loop control variable. When I want to exit, all I have to do is set running
to False
. You might think about just calling break
, but it won't work here because lines 146 and 147 are nested loops; break
would just exit one level, and the outer loop would restart the inner loop. Setting running
to False
makes the outer loop exit and the loop ends.
Line 147 gets all of the events from the PyGame event queue and iterates over them. Line 148 checks whether the event type is pygame.KEYDOWN
; that is, has the player pressed a key? If so, then the if
/elif
statements on lines 149, 153, 157, 161, 165, 170, 175, and 180 find the key, determine the direction, and update self.playerX
, self.playerY
, and self.grid
accordingly.
The elif event.key == ord ( "t" )
on line 185 handles the request for a teleport; self.grid
is cleared as in all the other moves, but instead of incrementing or decrementing self.playerX
and self.playerY
, new random values are generated.
Line 190 checks whether the player has pressed the p key, which is the "quit" key. If so, then running
is set to False
(line 191) so the main loop will exit. See the "Why p?" box for an explanation of why the number pad wasn't used.
Why p?
Usually, I would use q or x as the "exit" key, but they were both taken with the movement keys. It occurred to me after I finished the code that I could have used the number keypad for orthogonal and diagonal movement. However, I was originally coding on a laptop without a number pad, so the idea slipped my mind. Hence, this becomes a practical example of "remember the target platform and audience."
Line 192 calls self.moveBots
after the player's move has been processed, which makes all of the robots move toward the player. Line 193 uses the self.checkWinLose
function to see if the game is over. If so, lines 194 through 197 print the appropriate message and end the loop. Finally, line 203 calls self.drawGrid
to draw all of the changes to the screen.
Overall Program Setup
Up to this point, I've defined functions but, until the class itself and all of its requirements are set up, it won't do anything. So, other than placing the class and a couple of modules into memory, nothing happens until line 205. There, I initialize PyGame, and on line 206 create the screen
variable by setting the PyGame window size to 1024x768.
Line 208 is where the robotsGame
class gets initialized; the first argument is the PyGame screen
(so the class can draw things) and the number of robots to place on the grid. Line 209 calls the game's drawGrid
function, then line 210 starts the main event loop, game.run
, which will continue until the game is over.
Infos
- Python: http://www.python.org
- PyGame: http://www.pygame.org
« Previous 1 2 3 4 Next »
Buy this article as PDF
Pages: 8
(incl. VAT)