Session 6 : Cheatsheet
Ouvrir une fenêtre pygame
import pygame
pygame.init()
WIDTH, HEIGHT = 800, 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((30, 30, 60))
pygame.display.flip()
clock.tick(60)
La boucle de gravité
GRAVITY = 0.5
vel_y = 0
# À chaque frame :
vel_y += GRAVITY
player_rect.y += int(vel_y)
on_ground = False
for platform in platforms:
if player_rect.colliderect(platform) and vel_y > 0:
player_rect.bottom = platform.top
vel_y = 0
on_ground = True
Sauter
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE] and on_ground:
vel_y = -12
Créer un Rect
platform = pygame.Rect(x, y, breedte, hoogte)
pygame.draw.rect(screen, kleur, platform)
Collision avec des items (liste)
for item in items[:]:
if player_rect.colliderect(item):
items.remove(item)
score += 1
Le son
import os
import pygame
pygame.mixer.init()
# _DIR fait que le chemin reste correct, peu importe d'où tu lances le script
_DIR = os.path.dirname(os.path.abspath(__file__))
try:
jump_snd = pygame.mixer.Sound(os.path.join(_DIR, "sounds/jump.wav"))
except Exception:
jump_snd = None
if jump_snd:
jump_snd.play()
Dessiner du texte
font = pygame.font.SysFont(None, 36)
tekst = font.render(f"Score : {score}", True, (255, 255, 255))
screen.blit(tekst, (10, 10))