Sessie 6: Cheatsheet
Pygame venster openen
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)
Zwaartekracht-loop
GRAVITY = 0.5
vel_y = 0
# Elke 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
Springen
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE] and on_ground:
vel_y = -12
Rect-aanmaken
platform = pygame.Rect(x, y, breedte, hoogte)
pygame.draw.rect(screen, kleur, platform)
Botsing met items (lijst)
for item in items[:]:
if player_rect.colliderect(item):
items.remove(item)
score += 1
Geluid
import os
import pygame
pygame.mixer.init()
# _DIR zorgt dat het pad klopt ongeacht vanwaar je het script start
_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()
Tekst tekenen
font = pygame.font.SysFont(None, 36)
tekst = font.render(f"Score: {score}", True, (255, 255, 255))
screen.blit(tekst, (10, 10))