|
| 1 | +#Credit the Invent With Python book (http://inventwithpython.com) |
| 2 | +#for doRectsOverlap and isPointInsideRect functions |
| 3 | + |
| 4 | +#used to detect collisions in our game |
| 5 | +def doRectsOverlap(rect1, rect2): |
| 6 | + for a, b in [(rect1, rect2), (rect2, rect1)]: |
| 7 | + # Check if a's corners are inside b |
| 8 | + if ((isPointInsideRect(a.left, a.top, b)) or |
| 9 | + (isPointInsideRect(a.left, a.bottom, b)) or |
| 10 | + (isPointInsideRect(a.right, a.top, b)) or |
| 11 | + (isPointInsideRect(a.right, a.bottom, b))): |
| 12 | + return True |
| 13 | + |
| 14 | + return False |
| 15 | + |
| 16 | +#used the by the doRectsOverlap function (won't be called directly from game code) |
| 17 | +def isPointInsideRect(x, y, rect): |
| 18 | + if (x > rect.left) and (x < rect.right) and (y > rect.top) and (y < rect.bottom): |
| 19 | + return True |
| 20 | + else: |
| 21 | + return False |
| 22 | + |
| 23 | +import pygame, sys |
| 24 | +pygame.init() |
| 25 | + |
| 26 | +SCREEN_WIDTH = 640 |
| 27 | +SCREEN_HEIGHT = 480 |
| 28 | + |
| 29 | +screen = pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT]) |
| 30 | + |
| 31 | +class Spaceship: |
| 32 | + xpos = 0 |
| 33 | + ypos = 0 |
| 34 | + |
| 35 | + def __init__(self, x, y): |
| 36 | + self.xpos = x |
| 37 | + self.ypos = y |
| 38 | + |
| 39 | +class Alien: |
| 40 | + xpos = 0 |
| 41 | + ypos = 0 |
| 42 | + xspeed = 2 |
| 43 | + picture = pygame.image.load('alien1.png') |
| 44 | + |
| 45 | + def __init__(self, x, y): |
| 46 | + self.xpos = x |
| 47 | + self.ypos = y |
| 48 | + |
| 49 | + |
| 50 | +class Missile: |
| 51 | + xpos = 0 |
| 52 | + ypos = 0 |
| 53 | + xspeed = 2 |
| 54 | + yspeed = 2 |
| 55 | + |
| 56 | + def __init__(self, x, y): |
| 57 | + self.xpos = x |
| 58 | + self.ypos = y |
| 59 | + |
0 commit comments