Game Development Reference
In-Depth Information
the previous chapter for an explanation of that code.) We will use a list of
pygame.Rect objects to represent the food squares. Each pygame.Rect object in the
list represents a single food square. On each iteration through the game loop, our program
will read each pygame.Rect object in the list and draw a green square on the window.
Every forty iterations through the game loop we will add a new pygame.Rect to the list
so that the screen constantly has new food squares in it.
The bouncer is represented by a dictionary. The dictionary has a key named
'rect' (whose value is a pygame.Rect object) and a key named 'dir' (whose value
is one of the constant direction variables just like we had in last chapter's Animation
program). As the bouncer bounces around the window, we check if it collides with any of
the food squares. If it does, we delete that food square so that it will no longer be drawn on
the screen.
Type the following into a new file and save it as collisionDetection.py . If you don't want
to type all of this code, you can download the source from the topic's website at
http://inventwithpython.com/chapter18.
collisionDetection.py
This code can be downloaded from http://inventwithpython.com/collisionDetection.py
If you get errors after typing this code in, compare it to the topic's code with the online
diff tool at http://inventwithpython.com/diff or email the author at
al@inventwithpython.com
1. import pygame, sys, random
2. from pygame.locals import *
3.
4. def doRectsOverlap(rect1, rect2):
5. for a, b in [(rect1, rect2), (rect2, rect1)]:
6. # Check if a's corners are inside b
7. if ((isPointInsideRect(a.left, a.top, b)) or
8. (isPointInsideRect(a.left, a.bottom, b)) or
9. (isPointInsideRect(a.right, a.top, b)) or
10. (isPointInsideRect(a.right, a.bottom, b))):
11. return True
12.
13. return False
14.
15. def isPointInsideRect(x, y, rect):
16. if (x > rect.left) and (x < rect.right) and (y >
rect.top) and (y < rect.bottom):
17. return True
18. else:
19. return False
20.
21.
22. # set up pygame
23. pygame.init()
24. mainClock = pygame.time.Clock()
25.
26. # set up the window
27. WINDOWWIDTH = 400
Search WWH ::




Custom Search