Arts >> Theater >> Playwriting

Python Maze Runner Game Code Example Using Pygame

Below is a complete Pygame example for a simple maze runner. It initializes a window, draws a maze grid, and allows player movement with arrow keys.

import pygame

# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# Screen setup
size = [700, 500]
screen = pygame.display.set_mode(size)

# Game loop
done = False
clock = pygame.time.Clock()

# Player position and speed
x_speed = 0
y_speed = 0
x_coord = 10
y_coord = 10

# Maze layout (1 = wall, 0 = path)
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)

    # Draw maze
    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])

    # Draw player
    pygame.draw.rect(screen, WHITE, [x_coord, y_coord, 25, 25])

    # Movement
    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

    # Wall collision
    if maze[int(y_coord/25)][int(x_coord/25)] == 1:
        x_speed = 0
        y_speed = 0

    pygame.display.flip()

pygame.quit()

Playwriting

Related Categories