Session 2: Cheatsheet
Creating a list and adding to it
meteors = [] # empty list
rock = Actor('meteor')
meteors.append(rock) # add it
Looping over a list (with removal)
for rock in meteors[:]: # [:] = copy
rock.y += 4
if rock.y > HEIGHT + 30:
meteors.remove(rock)
Timer: doing something every N frames
timer = 0
def update():
global timer
timer += 1
if timer % 60 == 0: # every second
spawn_meteor()
Collision with several objects
for rock in meteors[:]:
if rock.colliderect(ship):
meteors.remove(rock)
lives -= 1
Stopping on game over
def update():
if game_over:
return
# rest of the code...
Text on screen
screen.draw.text(f"Score: {score}", (10, 10), color="white")
screen.draw.text(
"GAME OVER",
center=(WIDTH / 2, HEIGHT / 2),
color="red",
fontsize=60,
)
Random position
import random
x = random.randint(30, WIDTH - 30)