Game Development Reference
In-Depth Information
20 - Dodger
(WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
64. pygame.display.update()
65. waitForPlayerToPressKey()
On lines 62 and 63, we call our
drawText()
function and pass it five arguments: 1) the
string of the text we want to appear, 2) the font that we want the string to appear in, 3) the
Surface
object onto which to render the text, and 4) and 5) the X and Y coordinate on the
Surface
object to draw the text at.
This may seem like many arguments to pass for a function call, but keep in mind that this
function call replaces five lines of code each time we call it. This shortens our program and
makes it easier to find bugs since there is less code to check.
The
waitForPlayerToPressKey()
function will pause the game by entering into a
loop that checks for any
KEYDOWN
events. Once a
KEYDOWN
event is generated, the
execution breaks out of the loop and the program continues to run.
Start of the Main Game Code
68. topScore = 0
69. while True:
We have finished defining the helper functions and variables that we need for this game.
Line 68 is the start of the main game code. The value in the
topScore
variable starts at
0
only when the program first runs. Whenever the player loses and has a score larger than the
current top score, the top score is replaced with the player's score.
The infinite loop started on line 69 is technically not the "game loop". (The main game
loop handles events and drawing the window while the game is running.) Instead, this
while
loop will iterate each time the player starts a new game. We will set up the code so
that when the player loses and we need to reset the game, the program's execution will go
back to the start of this loop.
70. # set up the start of the game
71. baddies = []
72. score = 0
At the very beginning, we want to set the
baddies
list to an empty list. The
baddies
list is a list of dictionary objects with the following keys:
'rect'
- The
Rect
object that describes where and what size the baddie is.
'speed'
- How fast the baddie falls down the screen. This integer represents pixels
per iteration through the game loop.
'surface'
- The
Surface
object that has the scaled image of the baddie image