Session 6: Cheatsheet
Opening a Pygame window
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)
Gravity loop
GRAVITY = 0.5
vel_y = 0
# Every 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
Jumping
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE] and on_ground:
vel_y = -12
Creating a Rect
platform = pygame.Rect(x, y, breedte, hoogte)
pygame.draw.rect(screen, kleur, platform)
Collision with items (list)
for item in items[:]:
if player_rect.colliderect(item):
items.remove(item)
score += 1
Sound
import os
import pygame
pygame.mixer.init()
# _DIR makes sure the path is right wherever you start the script from
_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()
Drawing text
font = pygame.font.SysFont(None, 36)
tekst = font.render(f"Score: {score}", True, (255, 255, 255))
screen.blit(tekst, (10, 10))