Game Development Reference
In-Depth Information
17 - Graphics and Animation
the window. If it has, we want to "bounce" the block, which in the code means set a new
value for the block's 'dir' key. When the direction is set, the block will move in the new
direction on the next iteration of the game loop.
We need to check if the block has moved passed each of the four edges of the window.
In the above if statement, we decide the block has moved past the top edge of the window
if the block's Rect object's top attribute is less than 0 . If it is, then we need to change the
direction based on what direction the block was moving.
Changing the Direction of the Bouncing Block
Look at the bouncing diagram earlier in this chapter. In order to move past the top edge
of the window, the block had to either be moving in the UPLEFT or UPRIGHT directions.
If the block was moving in the UPLEFT direction, the new direction (according to our
bounce diagram) will be DOWNLEFT . If the block was moving in the UPRIGHT direction,
the new direction will be DOWNRIGHT .
66. if b['rect'].bottom > WINDOWHEIGHT:
67. # block has moved past the bottom
68. if b['dir'] == DOWNLEFT:
69. b['dir'] = UPLEFT
70. if b['dir'] == DOWNRIGHT:
71. b['dir'] = UPRIGHT
Here we see if the block has moved past the bottom edge of the window by checking if
the bottom attribute (not the top attribute) is greater than the value in WINDOWHEIGHT .
Remember that the Y-coordinates start at 0 at the top of the window and increase to
WINDOWHEIGHT because we passed WINDOWHEIGHT as the height in our call to
pygame.display.set_mode() .
The rest of the code changes the direction based on what our bounce diagram says.
72. if b['rect'].left < 0:
73. # block has moved past the left side
74. if b['dir'] == DOWNLEFT:
75. b['dir'] = DOWNRIGHT
76. if b['dir'] == UPLEFT:
77. b['dir'] = UPRIGHT
This is similar to the above code, but checks if the left side of the block has moved to the
left of the left edge of the window. Remember, the X-coordinates start at 0 on the left edge
of the window and increase to WINDOWWIDTH on the right edge of the window.
78. if b['rect'].right > WINDOWWIDTH:
79. # block has moved past the right side
Search WWH ::




Custom Search