Session 5 : Cheatsheet

Charger et jouer un son

import os
import pygame

pygame.mixer.init()

# os.path.abspath(__file__) donne le dossier de ce fichier, pas le dossier depuis lequel tu lances le script.
# Sans ça, le son ne marche que si tu ouvres le script depuis le même dossier.
_DIR = os.path.dirname(os.path.abspath(__file__))
try:
    snd_hit = pygame.mixer.Sound(os.path.join(_DIR, 'sounds/hit.wav'))
except:
    snd_hit = None

if snd_hit:
    snd_hit.play()

La balle rebondit sur les murs

if ball.left <= 0 or ball.right >= WIDTH:
    ball_dx = -ball_dx
if ball.top <= 0:
    ball_dy = -ball_dy

La balle rebondit sur la raquette

if ball.colliderect(paddle):
    ball_dy = -ball_dy

Casser des briques (dict dans une liste)

# Créer une brique
stenen.append({'rect': pygame.Rect(x, y, b, h), 'kleur': (220, 60, 60)})

# Vérifier la collision
for steen in stenen[:]:
    if ball.colliderect(steen['rect']):
        stenen.remove(steen)
        ball_dy = -ball_dy
        score += 10
        break

Dessiner les briques

for steen in stenen:
    pygame.draw.rect(screen, steen['kleur'], steen['rect'])

Vies : remettre la balle en place

if ball.top > HEIGHT:
    levens -= 1
    ball.center = (paddle.centerx, paddle.top - 12)
    ball_dy = -4

Victoire / game over

if not stenen:
    txt = font.render("TU GAGNES !", True, (255, 220, 0))
    screen.blit(txt, (WIDTH//2 - txt.get_width()//2, HEIGHT//2))

if levens <= 0:
    txt = font.render("GAME OVER", True, (220, 50, 50))
    screen.blit(txt, (WIDTH//2 - txt.get_width()//2, HEIGHT//2))