Game Development Reference
In-Depth Information
20 - Dodger
game world on the screen. All of this happens several dozen times a second, which
makes it seem that the game is happening in real time to the player.
79. while True: # the game loop runs while the game part
is playing
80. score += 1 # increase score
Line 79 is the start of the main game loop. In the main game loop, we will increase the
player's score, handle any events that were generated, add any baddies to the top of the
screen if needed, move the baddies down a little, and then draw everything on the screen.
This code will be executed over and over again as the program execution iterates through
the game loop. The loop will only exit when the player either loses the game or quits the
program.
First, we will increment the player's score. The longer the player can go without losing,
the higher their score will be.
Event Handling
There are four different types of events we will handle in our game: QUIT , KEYDOWN ,
KEYUP , and MOUSEMOTION . The QUIT event is generated by Pygame if the player closes
the program's window or shuts down the computer. In that case, we want the program to
close itself. The KEYDOWN and KEYUP events are generated when the player pushes down
and releases the keyboard keys, respectively. These events will be how we can tell which
direction the player wants to move the character. The player could also have pressed the
Esc key to signal that they want to shut down the program. Each time the player moves the
mouse, Pygame will generate a MOUSEMOTION event which will tell us the X and Y
coordinates of the mouse cursor over the window.
82. for event in pygame.event.get():
83. if event.type == QUIT:
84. terminate()
Line 82 is the start of the event-handling code. First we call pygame.event.get() ,
which returns a list of Event objects. Each Event object represents an event that has
been created since the last call to pygame.event.get() . We will check the type
attribute of the event object to see what type of event it is, and handle the event
accordingly.
If the type attribute of the Event object is equal to QUIT , then this tells us that the
user has closed the program somehow. The QUIT constant variable was imported from the
pygame.locals module, but since we imported that module with the line from
pygame.locals import * instead of simply import pygame.locals , we only
need to type QUIT and not pygame.locals.QUIT .
Search WWH ::




Custom Search