Unten steht ein komplettes Pygame-Beispiel für einen einfachen Maze Runner. Es initialisiert ein Fenster, zeichnet ein Labyrinth-Gitter und erlaubt Spielerbewegung mit Pfeiltasten.
import pygame
# Farben
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Bildschirm-Setup
size = [700, 500]
screen = pygame.display.set_mode(size)
# Game Loop
done = False
clock = pygame.time.Clock()
# Spielerposition und Geschwindigkeit
x_speed = 0
y_speed = 0
x_coord = 10
y_coord = 10
# Labyrinth-Layout (1 = Wand, 0 = Pfad)
maze = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,1,0,1,0,1,0,1,1],
[1,0,0,0,1,0,0,0,1,1],
[1,0,1,0,1,1,1,0,1,1],
[1,0,1,0,0,0,1,0,1,1],
[1,0,1,1,1,0,1,0,1,1],
[1,0,0,0,0,0,1,0,0,1],
[1,0,1,1,1,1,1,0,1,1],
[1,1,1,1,1,1,1,1,1,1]
]
while not done:
clock.tick(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(BLACK)
# Labyrinth zeichnen
for row in range(9):
for col in range(10):
if maze[row][col] == 1:
pygame.draw.rect(screen, WHITE, [25*col, 25*row, 25, 25])
# Spieler zeichnen
pygame.draw.rect(screen, WHITE, [x_coord, y_coord, 25, 25])
# Bewegung
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
y_speed = -5
elif keys[pygame.K_DOWN]:
y_speed = 5
elif keys[pygame.K_LEFT]:
x_speed = -5
elif keys[pygame.K_RIGHT]:
x_speed = 5
x_coord += x_speed
y_coord += y_speed
# Wandkollision
if maze[int(y_coord/25)][int(x_coord/25)] == 1:
x_speed = 0
y_speed = 0
pygame.display.flip()
pygame.quit()