Session 7 : Cheatsheet

Écrire une classe

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)

Utiliser une classe

mijn_bug = Bug(200, 0)   # créer
mijn_bug.update()         # appeler une méthode
mijn_bug.draw(screen)

Sous-classe (héritage)

class SlingerBug(Bug):
    def __init__(self, x, y):
        super().__init__(x, y)   # appelle Bug.__init__
        self.timer = 0

    def update(self):            # remplace Bug.update
        self.timer += 0.05
        self.x = self.start_x + math.sin(self.timer) * 60
        self.y += 1.5

math.sin pour osciller

import math
self.x = start_x + math.sin(timer) * amplitude
# augmenter le timer à chaque frame : timer += 0.05

Garder les projectiles dans une liste

bullets = []
# Créer :
bullets.append(pygame.Rect(x - 3, y - 20, 6, 12))
# Déplacer :
for b in bullets[:]:
    b.y -= 10
    if b.y < 0:
        bullets.remove(b)

Collision projectile ↔ 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

Timer de spawn avec USEREVENT

SPAWN = pygame.USEREVENT + 1
pygame.time.set_timer(SPAWN, 1500)  # toutes les 1,5 secondes

for event in pygame.event.get():
    if event.type == SPAWN:
        bugs.append(Bug(random.randint(30, WIDTH - 30), -20))