Game Development Reference
In-Depth Information
18 - Collision Detection and Input
Remember, we are not done drawing things on the windowSurface object yet. We
still need to draw a green square for each food square in the foods list. And we are just
"drawing" rectangles on the windowSurface object. This pygame.Surface object is
only inside the computer's memory, which is much faster to modify than the pixels on the
screen. The window on the screen will not be updated until we call the
pygame.display.update() function.
Colliding with the Food Squares
114. # check if the bouncer has intersected with any food
squares.
115. for food in foods[:]:
Before we draw the food squares, we want to see if the bouncer has overlapped any of
the food squares. If it has, we will remove that food square from the foods list. This way,
the computer won't draw any food squares that the bouncer has "eaten".
On each iteration through the for loop, the current food square from the foods (plural)
list will be stored inside a variable called food (singular).
Don't Add to or Delete from a List while Iterating Over It
Notice that there is something slightly different with this for loop. If you look carefully
at line 116, we are not iterating over foods but actually over foods[:] . Just as foods
[:2] would return a copy of the list with the items from the start and up to (but not
including) the item at index 2, and just as foods[3:] would return a copy of the list with
the items from index 3 to the end of the list, foods[:] will give you a copy of the list
with the items from the start to the end. Basically, foods[:] creates a new list with a
copy of all the items in foods . (This is a shorter way to copy a list than our
getBoardCopy() function in the Tic Tac Toe game.)
Why would we want to iterate over a copy of the list instead of the list itself? It is
because we cannot add or remove items from a list while we are iterating over it. Python
can lose track of what the next value of food variable should be if the size of the foods
list is always changing. Think of how difficult it would be for you if you tried to count the
number of jelly beans in a jar while someone was adding or removing jelly beans. But if we
iterate over a copy of the list (and the copy never changes), then adding or removing items
from the original list won't be a problem.
Removing the Food Squares
116. if doRectsOverlap(bouncer['rect'], food):
117. foods.remove(food)
Search WWH ::




Custom Search