Session 10: Cheatsheet (all sessions)
An overview of all the patterns from sessions 1 to 9. Use it as a reference while you build your own game.
Pygame game loop (session 6+)
import pygame
pygame.init()
WIDTH, HEIGHT = 800, 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 36)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
pass # action on SPACE
screen.fill((20, 20, 50))
# update logic here
# draw logic here
pygame.display.flip()
clock.tick(60)
pygame.quit()Pgzrun game loop (sessions 1 to 5)
import pgzrun
WIDTH = 600
HEIGHT = 400
def draw():
screen.fill((20, 20, 50))
def update():
pass # replace with your own logic
pgzrun.go()Keyboard
# Pgzrun style:
if keyboard.left:
speler.x -= 5
# Pygame style:
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
speler_rect.x -= 5
if keys[pygame.K_RIGHT]:
speler_rect.x += 5
if keys[pygame.K_UP]:
speler_rect.y -= 5
if keys[pygame.K_DOWN]:
speler_rect.y += 5Mouse input
# Position:
mx, my = pygame.mouse.get_pos()
# Clicking (in the event loop):
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # left mouse button
passActor / Sprite (pgzrun)
speler = Actor('speler') # loads images/speler.png
speler.pos = (300, 380)
def draw():
speler.draw()
if speler.colliderect(ster):
pass # collision!Creating and drawing a Rect (pygame)
speler_rect = pygame.Rect(x, y, breedte, hoogte)
pygame.draw.rect(screen, (0, 128, 255), speler_rect)
# Circle:
pygame.draw.circle(screen, (255, 255, 0), (x, y), straal)
# Line:
pygame.draw.line(screen, (255, 0, 0), (x1, y1), (x2, y2), dikte)Collision detection
# Two Rects:
if rect_a.colliderect(rect_b):
pass
# Point in Rect:
if rect.collidepoint(mx, my):
pass
# Pgzrun:
if actor_a.colliderect(actor_b):
passGravity and jumping (session 6)
GRAVITY = 0.5
vel_y = 0
on_ground = False
# Every frame:
vel_y += GRAVITY
speler_rect.y += int(vel_y)
for platform in platforms:
if speler_rect.colliderect(platform) and vel_y > 0:
speler_rect.bottom = platform.top
vel_y = 0
on_ground = True
# Jumping:
if keys[pygame.K_SPACE] and on_ground:
vel_y = -12Classes (session 7)
class Vijand:
def __init__(self, x, y):
self.x = x
self.y = y
self.alive = True
def update(self):
self.y += 2
def draw(self, screen):
pygame.draw.circle(screen, (0, 200, 0), (int(self.x), int(self.y)), 15)
# Using it:
v = Vijand(200, 0)
v.update()
v.draw(screen)Inheritance (session 7)
class SlingerVijand(Vijand):
def __init__(self, x, y):
super().__init__(x, y)
self.timer = 0
self.start_x = x
def update(self):
import math
self.timer += 0.05
self.x = self.start_x + math.sin(self.timer) * 60
self.y += 1.5Scrolling background (session 8)
scroll_x = 0
speed = 4
# Every frame:
scroll_x -= speed
if scroll_x <= -WIDTH:
scroll_x = 0
screen.blit(bg_image, (int(scroll_x), 0))
screen.blit(bg_image, (int(scroll_x) + WIDTH, 0))Spawning objects (session 8)
import random
SPAWN_EVENT = pygame.USEREVENT + 1
pygame.time.set_timer(SPAWN_EVENT, 1500)
for event in pygame.event.get():
if event.type == SPAWN_EVENT:
objecten.append(pygame.Rect(WIDTH, random.randint(50, HEIGHT - 100), 30, 60))
# Move and remove:
for obj in objecten[:]:
obj.x -= speed
if obj.x < -obj.width:
objecten.remove(obj)Drawing an HP bar (session 9)
MAX_HP = 100
# Background:
pygame.draw.rect(screen, (80, 0, 0), (10, 10, 300, 20))
# Filled part:
breedte = max(0, int(300 * hp / MAX_HP))
pygame.draw.rect(screen, (220, 0, 0), (10, 10, breedte, 20))State machine / phases (session 9)
if hp > 50:
fase = 1
snelheid = 3
elif hp > 25:
fase = 2
snelheid = 5
else:
fase = 3
snelheid = 7Keeping track of bullets
kogels = []
# Create (on a key press):
kogels.append(pygame.Rect(speler_rect.centerx - 3, speler_rect.top - 15, 6, 15))
# Move and remove:
for k in kogels[:]:
k.y -= 8
if k.y < 0:
kogels.remove(k)
continue
pygame.draw.rect(screen, (255, 255, 0), k)
# Collision with enemy:
if k.colliderect(vijand_rect):
kogels.remove(k)
vijand.alive = False
score += 1
breakSound (session 6)
pygame.mixer.init()
sprong_snd = pygame.mixer.Sound("sounds/sprong.wav")
sprong_snd.play()
# Background music:
pygame.mixer.music.load("sounds/muziek.mp3")
pygame.mixer.music.play(-1) # -1 = repeat foreverDrawing text
font = pygame.font.SysFont(None, 36)
tekst = font.render(f"Score: {score}", True, (255, 255, 255))
screen.blit(tekst, (10, 10))
# Centred:
screen.blit(tekst, (WIDTH // 2 - tekst.get_width() // 2, HEIGHT // 2))Score and global variables
score = 0 # outside all functions
# In pgzrun update():
global score
score += 1
# In pygame (score is already global if it is outside the loop):
score += 1Random numbers
import random
x = random.randint(0, WIDTH) # whole number between 0 and WIDTH
k = random.choice(['red', 'blue']) # random element from a list
r = random.random() # floating point number between 0.0 and 1.0Timer pattern (frame-based)
timer = 0
interval = 90 # every 90 frames (= 1.5 sec at 60 FPS)
# Every frame:
timer += 1
if timer >= interval:
timer = 0
# do somethingWin and game over screen
# Game over:
screen.fill((0, 0, 0))
go = font.render("GAME OVER", True, (220, 0, 0))
screen.blit(go, (WIDTH // 2 - go.get_width() // 2, HEIGHT // 2))
pygame.display.flip()
pygame.time.wait(3000)
# Win:
win = font.render("You win!", True, (255, 220, 0))
screen.blit(win, (WIDTH // 2 - win.get_width() // 2, HEIGHT // 2))
pygame.display.flip()
pygame.time.wait(3000)