Table of Contents
- Introduction
- Prerequisites
- Setting Up
- Creating the Maze
- Moving the Player
- Collision Detection
- Winning the Game
- Conclusion
Introduction
In this tutorial, we will learn how to create a maze game using Python. The game will involve navigating a player through a maze and reaching the goal. By the end of this tutorial, you will have a basic understanding of how to create a simple game and apply concepts such as collision detection and winning conditions.
Prerequisites
To follow along with this tutorial, you should have a basic understanding of Python programming language fundamentals, including variables, loops, and functions. Additionally, it would be helpful to have some knowledge of the Pygame library, which we will be using to create the game. However, don’t worry if you’re new to Pygame, as we will cover the necessary steps to get started.
Setting Up
To start, we need to install the Pygame library. Open your terminal and run the following command:
bash
pip install pygame
Once Pygame is installed, we can proceed with setting up our project structure. Create a new directory for your project and navigate to it in the terminal. Inside the project directory, create a new Python script called maze_game.py
.
Creating the Maze
To create the maze, we will use a 2D list where each element represents a cell in the maze. We will use the ‘#’ character to represent walls and empty spaces for the empty cells. Open the maze_game.py
file and add the following code:
```python
import pygame
# Initialize Pygame
pygame.init()
# Define the maze dimensions
maze_width = 10
maze_height = 10
# Define the colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Set the width and height of each cell in the maze
cell_width = 20
cell_height = 20
# Set the margin between each cell
margin = 5
# Create a 2D list to represent the maze
maze = [['#' for _ in range(maze_width)] for _ in range(maze_height)]
# Set up the display
window_width = maze_width * (cell_width + margin) + margin
window_height = maze_height * (cell_height + margin) + margin
window = pygame.display.set_mode((window_width, window_height))
# Set the window title
pygame.display.set_caption("Maze Game")
# Game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Fill the window with the background color
window.fill(WHITE)
# Draw the maze
for row in range(maze_height):
for column in range(maze_width):
color = BLACK if maze[row][column] == '#' else WHITE
pygame.draw.rect(window, color, [(margin + cell_width) * column + margin,
(margin + cell_height) * row + margin,
cell_width,
cell_height])
# Update the display
pygame.display.update()
# Quit the game
pygame.quit()
``` The code above initializes Pygame and sets up the window for the game. It defines the maze dimensions, cell size, colors, margin, and creates the 2D list to represent the maze. The game loop handles the events, fills the window with the background color, draws the maze using rectangles, and updates the display. The game loop will continue running until the user closes the window.
To run the code, save the file and execute it from the terminal:
bash
python maze_game.py
You should see a blank window with a grid representing the maze.
Moving the Player
Now that we have our maze displayed, let’s add a player character that can be moved around the maze. To do this, we will create a Player
class and update the game loop logic.
Add the following code below the maze
definition:
```python
class Player:
def init(self, x, y):
self.x = x
self.y = y
def move(self, dx, dy):
if 0 <= self.x + dx < maze_width and 0 <= self.y + dy < maze_height and \
maze[self.y + dy][self.x + dx] != '#':
self.x += dx
self.y += dy
# Create the player
player = Player(0, 0)
``` At the beginning of the game loop, add the following code:
```python
# Handle player movement
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
player.move(0, -1)
elif keys[pygame.K_DOWN]:
player.move(0, 1)
elif keys[pygame.K_LEFT]:
player.move(-1, 0)
elif keys[pygame.K_RIGHT]:
player.move(1, 0)
``` To render the player, modify the drawing code inside the maze loop:
```python
# Draw the maze and player
for row in range(maze_height):
for column in range(maze_width):
color = BLACK if maze[row][column] == '#' else WHITE
pygame.draw.rect(window, color, [(margin + cell_width) * column + margin,
(margin + cell_height) * row + margin,
cell_width,
cell_height])
# Draw the player
pygame.draw.rect(window, (255, 0, 0), [(margin + cell_width) * player.x + margin,
(margin + cell_height) * player.y + margin,
cell_width,
cell_height])
``` Now, when you run the game, you can use the arrow keys to move the player around the maze.
Collision Detection
We want to make sure that the player cannot move through walls or exit the boundaries of the maze. To do this, we will implement collision detection in the Player
class. Update the move
method as follows:
python
def move(self, dx, dy):
if 0 <= self.x + dx < maze_width and 0 <= self.y + dy < maze_height and \
maze[self.y + dy][self.x + dx] != '#':
self.x += dx
self.y += dy
We check if the desired move is within the maze boundaries and if the target cell is not a wall (‘#’). If the move is valid, we update the player’s position.
Winning the Game
To make the game interesting, let’s add a goal that the player must reach to win. Modify the maze
definition to include the goal cell:
python
# Create a 2D list to represent the maze
maze = [['#' for _ in range(maze_width)] for _ in range(maze_height)]
maze[4][4] = 'G'
Add the following code below the collision detection check:
python
# Check if the player reached the goal
if maze[player.y][player.x] == 'G':
print("Congratulations, you reached the goal!")
running = False
Now, if the player reaches the ‘G’ cell in the maze, a winning message will be displayed in the console, and the game will exit.
Conclusion
In this tutorial, we learned how to create a simple maze game using Python and the Pygame library. We covered how to create the maze, move the player, implement collision detection, and add a winning condition. With this knowledge, you can expand upon the game by adding more features, levels, or even creating your own maze generator algorithm. Have fun exploring and experimenting with your maze game!