Game Development Reference
In-Depth Information
80. if b['dir'] == DOWNRIGHT:
81. b['dir'] = DOWNLEFT
82. if b['dir'] == UPRIGHT:
83. b['dir'] = UPLEFT
This code is similar to the previous pieces of code, but it checks if the block has moved
past the rightmost edge of the window.
Drawing the Blocks on the Window in Their New Positions
85. # draw the block onto the surface
86. pygame.draw.rect(windowSurface, b['color'], b
['rect'])
Now that we have moved the block (and set a new direction if the block has bounced off
the window's edges), we want to draw it on the windowSurface surface. We can draw
this using the pygame.draw.rect() function. We pass windowSurface , because that
is the Surface object we want to draw on. We pass the b['color'] value, because this
is the color we want to use. Then we pass b['rect'] , because that Rect object has the
information about the position and size of the rectangle we want to draw.
This is the last line of the for loop. We want to run the moving, bouncing, and drawing
code on each of the blocks stored in the blocks list, which is why we loop through each of
them. Also, if we wanted to add new blocks or remove blocks from our program, we only
have to modify the blocks list and the rest of the code still works.
Drawing the Window on the Screen
88. # draw the window onto the screen
89. pygame.display.update()
90. time.sleep(0.02)
After we have run this code on each of the blocks in the blocks list, we want to finally
call pygame.display.update() so that the windowSurface surface is draw on the
screen. After this line, we loop back to the start of the game loop and begin the process all
over again. This way, the blocks are constantly moving a little, bouncing off the walls, and
being drawn on the screen in their new positions. Meanwhile, we also check if the QUIT
event has been generated by the Pygame library (which happens if the player closes the
window or shuts down their computer). In that case we terminate the program.
The call to the time.sleep() function is there because the computer can move,
bounce, and draw the blocks so fast that if the program ran at full speed, all the blocks would
just look like a blur. (Try commenting out the time.sleep(0.02) line and running the
program to see this.) This call to time.sleep() will stop the program for 20
Search WWH ::




Custom Search