Session 2 : Cheatsheet
Créer une liste et y ajouter des éléments
meteors = [] # liste vide
rock = Actor('meteor')
meteors.append(rock) # ajoute
Parcourir une liste (avec suppression)
for rock in meteors[:]: # [:] = une copie
rock.y += 4
if rock.y > HEIGHT + 30:
meteors.remove(rock)
Timer : faire quelque chose toutes les N frames
timer = 0
def update():
global timer
timer += 1
if timer % 60 == 0: # chaque seconde
spawn_meteor()
Collision avec plusieurs objets
for rock in meteors[:]:
if rock.colliderect(ship):
meteors.remove(rock)
lives -= 1
Arrêter quand c’est game over
def update():
if game_over:
return
# le reste du code...
Du texte à l’écran
screen.draw.text(f"Score: {score}", (10, 10), color="white")
screen.draw.text(
"GAME OVER",
center=(WIDTH / 2, HEIGHT / 2),
color="red",
fontsize=60,
)
Position aléatoire
import random
x = random.randint(30, WIDTH - 30)