Game Development Reference
In-Depth Information
20 - Dodger
If the slow cheat has been activated, then the baddie should move downwards, but only
by the slow speed of one pixel per iteration through the game loop. The baddie's normal
speed (which is stored in the 'speed' key of the baddie's data structure) will be ignored
while the slow cheat is activated.
Removing the Baddies
162. # Delete baddies that have fallen past the
bottom.
163. for b in baddies[:]:
After moving the baddies down the window, we want to remove any baddies that fell
below the bottom edge of the window from the baddies list. Remember that we while we
are iterating through a list, we should not modify the contents of the list by adding or
removing items. So instead of iterating through the baddies list with our baddies loop,
we will iterate through a copy of the baddies list.
Remember that a list slice will evaluate a copy of a list's items. For example, spam
[2:4] will return a new list with the items from index 2 up to (but not including) index 4 .
Leaving the first index blank will indicate that index 0 should be used. For example, spam
[:4] will return a list with items from the start of the list up to (but not including) the item
at index 4 . Leaving the second index blank will indicate that up to (and including) the last
index should be used. For example, spam[2:] will return a list with items from index 2
all the way to (and including) the last item in the list.
But leaving both indexes in the slice blank is a way to represent the entire list. The
baddies[:] expression is a list slice of the whole list, so it evaluates to a copy of the
entire list. This is useful because while we are iterating on the copy of the list, we can
modify the original list and remove any baddie data structures that have fallen past the
bottom edge of the window.
Our for loop on line 163 uses a variable b for the current item in the iteration through
baddies[:] .
164. if b['rect'].top > WINDOWHEIGHT:
165. baddies.remove(b)
Let's evaluate the expression b['rect'].top. b is the current baddie data structure from the
baddies[:] list. Each baddie data structure in the list is a dictionary with a 'rect' key,
which stores a Rect object. So b['rect'] is the Rect object for the baddie. Finally, the top is
the Y-coordinate of the top edge of the rectangular area. Remember that in the coordinate
system, the Y-coordinates increase going down. So b['rect'].top >
WINDOWHEIGHT will check if the top edge of the baddie is below the bottom of the
window.
Search WWH ::




Custom Search