Session 7: Cheatsheet
Writing a class
class Bug:
def __init__(self, x, y):
self.x = x
self.y = y
self.alive = True
def update(self):
self.y += 2
def draw(self, screen):
pygame.draw.circle(screen, GREEN, (int(self.x), int(self.y)), 15)
Using a class
mijn_bug = Bug(200, 0) # create
mijn_bug.update() # call a method
mijn_bug.draw(screen)
Subclass (inheritance)
class SlingerBug(Bug):
def __init__(self, x, y):
super().__init__(x, y) # calls Bug.__init__
self.timer = 0
def update(self): # overrides Bug.update
self.timer += 0.05
self.x = self.start_x + math.sin(self.timer) * 60
self.y += 1.5
math.sin for swinging
import math
self.x = start_x + math.sin(timer) * amplitude
# increase the timer every frame: timer += 0.05
Keeping track of bullets
bullets = []
# Create:
bullets.append(pygame.Rect(x - 3, y - 20, 6, 12))
# Move:
for b in bullets[:]:
b.y -= 10
if b.y < 0:
bullets.remove(b)
Collision bullet ↔ bug
bug_rect = pygame.Rect(bug.x - 15, bug.y - 15, 30, 30)
for bullet in bullets[:]:
if bullet.colliderect(bug_rect):
bug.alive = False
bullets.remove(bullet)
score += 1
break
Spawn timer with USEREVENT
SPAWN = pygame.USEREVENT + 1
pygame.time.set_timer(SPAWN, 1500) # every 1.5 seconds
for event in pygame.event.get():
if event.type == SPAWN:
bugs.append(Bug(random.randint(30, WIDTH - 30), -20))