Sessie 7: Cheatsheet
Klasse schrijven
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)
Klasse gebruiken
mijn_bug = Bug(200, 0) # aanmaken
mijn_bug.update() # methode aanroepen
mijn_bug.draw(screen)
Subklasse (overerving)
class SlingerBug(Bug):
def __init__(self, x, y):
super().__init__(x, y) # roept Bug.__init__ aan
self.timer = 0
def update(self): # overschrijft Bug.update
self.timer += 0.05
self.x = self.start_x + math.sin(self.timer) * 60
self.y += 1.5
math.sin voor slingeren
import math
self.x = start_x + math.sin(timer) * amplitude
# timer ophogen elke frame: timer += 0.05
Kogels bijhouden
bullets = []
# Aanmaken:
bullets.append(pygame.Rect(x - 3, y - 20, 6, 12))
# Bewegen:
for b in bullets[:]:
b.y -= 10
if b.y < 0:
bullets.remove(b)
Botsing kogel ↔ 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 met USEREVENT
SPAWN = pygame.USEREVENT + 1
pygame.time.set_timer(SPAWN, 1500) # elke 1,5 seconden
for event in pygame.event.get():
if event.type == SPAWN:
bugs.append(Bug(random.randint(30, WIDTH - 30), -20))