Sessie 5: Cheatsheet
Geluid laden en afspelen
import os
import pygame
pygame.mixer.init()
# os.path.abspath(__file__) geeft de map van dit bestand, niet de map waar je het script start.
# Zonder dit werkt het geluid alleen als je het script vanuit dezelfde map opent.
_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()
Bal stuitert op muren
if ball.left <= 0 or ball.right >= WIDTH:
ball_dx = -ball_dx
if ball.top <= 0:
ball_dy = -ball_dy
Bal stuitert op paddle
if ball.colliderect(paddle):
ball_dy = -ball_dy
Stenen breken (dict in lijst)
# Steen aanmaken
stenen.append({'rect': pygame.Rect(x, y, b, h), 'kleur': (220, 60, 60)})
# Botsing controleren
for steen in stenen[:]:
if ball.colliderect(steen['rect']):
stenen.remove(steen)
ball_dy = -ball_dy
score += 10
break
Stenen tekenen
for steen in stenen:
pygame.draw.rect(screen, steen['kleur'], steen['rect'])
Levens: bal resetten
if ball.top > HEIGHT:
levens -= 1
ball.center = (paddle.centerx, paddle.top - 12)
ball_dy = -4
Win / game over
if not stenen:
txt = font.render("JE WINT!", 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))