Make raycast game in pygame
- User
Make raycast game in pygame
- Assistant
Make raycast game in pygame
Creating a raycast-based game in Pygame is a fantastic project that can help you understand the fundamentals of 3D rendering and game development. Raycasting is the technique used in early 3D games like Wolfenstein 3D to simulate a 3D environment using 2D maps. This guide will walk you through building a simple raycasting engine in Pygame, covering essential aspects such as map creation, player movement, raycasting logic, and rendering.
Before diving into the project, ensure you have the following:
Python 3.x installed on your system.
Pygame library installed. If not, you can install it using pip:
pip install pygame
For simplicity, we'll have a single Python script. However, as your project grows, you might want to organize your code into multiple files and directories.
raycasting_game/
│
├── wall_texture.png # (Optional) Wall texture image
└── main.py # Main game script
Note: The
wall_texture.pngis optional and used if you decide to add textured walls.
First, let's set up the basic Pygame environment, including initializing Pygame, creating the game window, and defining some global constants.
import pygame
import math
import sys
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 640, 480
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Raycasting Game in Pygame")
# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
DARK_BLUE = (0, 0, 155)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# Clock for controlling frame rate
clock = pygame.time.Clock()
The game map is a 2D grid where each cell represents a wall (1) or empty space (0). Here's an example map:
# Define the map layout
game_map = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,1],
[1,0,1,0,1,1,1,0,0,1],
[1,0,1,0,0,0,1,0,0,1],
[1,0,1,1,1,0,1,0,0,1],
[1,0,0,0,1,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1],
]
MAP_WIDTH = len(game_map[0])
MAP_HEIGHT = len(game_map)
Each 1 represents a wall, and 0 represents an empty space where the player can move.
We'll define the player's position, direction (angle), and the camera plane, which determines the field of view (FOV).
# Player starting position and direction
player_x, player_y = 3.0, 3.0 # Starting coordinates
player_dir = 0.0 # Facing right (0 radians)
# Camera plane (perpendicular to the direction)
FOV = math.pi / 3 # 60 degrees
plane_x = math.cos(player_dir + math.pi / 2) * math.tan(FOV / 2)
plane_y = math.sin(player_dir + math.pi / 2) * math.tan(FOV / 2)
# Movement parameters
move_speed = 0.05
rot_speed = 0.03
player_x, player_y: Player's position on the map.player_dir: Direction the player is facing, in radians.plane_x, plane_y: Define the camera's plane, influencing the FOV.move_speed, rot_speed: Control movement and rotation speeds.The core of the raycasting engine involves casting a ray for each vertical column of the screen to determine wall intersections and render them appropriately.
def cast_rays(player_x, player_y, player_dir, plane_x, plane_y, screen):
for x in range(WIDTH):
# Calculate ray position and direction
camera_x = 2 * x / WIDTH - 1 # x-coordinate in camera space
ray_dir_x = math.cos(player_dir) + plane_x * camera_x
ray_dir_y = math.sin(player_dir) + plane_y * camera_x
# Which box of the map we're in
map_x = int(player_x)
map_y = int(player_y)
# Length of ray from current position to next x or y-side
delta_dist_x = abs(1 / ray_dir_x) if ray_dir_x != 0 else float('inf')
delta_dist_y = abs(1 / ray_dir_y) if ray_dir_y != 0 else float('inf')
# Calculate step and initial sideDist
if ray_dir_x < 0:
step_x = -1
side_dist_x = (player_x - map_x) * delta_dist_x
else:
step_x = 1
side_dist_x = (map_x + 1.0 - player_x) * delta_dist_x
if ray_dir_y < 0:
step_y = -1
side_dist_y = (player_y - map_y) * delta_dist_y
else:
step_y = 1
side_dist_y = (map_y + 1.0 - player_y) * delta_dist_y
# Perform DDA
hit = False
side = 0
while not hit:
# Jump to next map square, either in x or y direction
if side_dist_x < side_dist_y:
side_dist_x += delta_dist_x
map_x += step_x
side = 0 # 0 for x-side
else:
side_dist_y += delta_dist_y
map_y += step_y
side = 1 # 1 for y-side
# Check if ray has hit a wall
if map_x >= MAP_WIDTH or map_x < 0 or map_y >= MAP_HEIGHT or map_y < 0:
hit = True
perp_wall_dist = float('inf')
elif game_map[map_y][map_x] > 0:
hit = True
# Calculate distance to the point of impact
if side == 0:
perp_wall_dist = (map_x - player_x + (1 - step_x) / 2) / ray_dir_x
else:
perp_wall_dist = (map_y - player_y + (1 - step_y) / 2) / ray_dir_y
# Calculate height of line to draw on screen
line_height = int(HEIGHT / perp_wall_dist) if perp_wall_dist > 0 else HEIGHT
# Calculate lowest and highest pixel to fill in current stripe
draw_start = max(-line_height // 2 + HEIGHT // 2, 0)
draw_end = min(line_height // 2 + HEIGHT // 2, HEIGHT - 1)
# Choose wall color with simple shading based on distance
if perp_wall_dist < float('inf'):
shade = max(50, min(255, int(255 / (1 + perp_wall_dist * perp_wall_dist * 0.1))))
color = (shade, shade, shade) if side == 0 else (shade // 2, shade // 2, shade)
else:
color = BLACK
# Draw the vertical line
pygame.draw.line(screen, color, (x, draw_start), (x, draw_end))
Loop Through Each Screen Column: For each vertical pixel column (x) on the screen, we cast a ray into the game world.
Calculate Ray Direction:
camera_x: Represents the position of the ray in camera space, ranging from -1 to 1.ray_dir_x, ray_dir_y: The direction vector of the ray based on the player's direction and camera plane.Determine Initial Map Square: Converts the player's floating-point position to integer map square indices.
Calculate delta_dist_x and delta_dist_y: These represent the distance the ray has to travel to cross a grid line in the x or y direction.
Determine Step and Initial Side Distances:
step_x, step_y: Direction to step in the grid (+1 or -1).side_dist_x, side_dist_y: Initial distances to the first x and y side.Digital Differential Analyzer (DDA) Algorithm:
Calculate Perpendicular Wall Distance: Correction to remove the fish-eye effect by calculating the perpendicular distance from the player to the wall.
Determine Wall Slice Height: Based on the distance, calculate how tall the wall slice should appear on the screen.
Simple Shading: Darkens walls that are further away or hit on y-sides to simulate depth.
Draw the Wall Slice: Uses pygame.draw.line to render each vertical slice of the wall.
Now, integrate the raycasting function into the game loop, handle player movements, and render the map for debugging purposes.
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Handle key presses
keys = pygame.key.get_pressed()
if keys[pygame.K_ESCAPE]:
pygame.quit()
sys.exit()
# Movement: Forward
if keys[pygame.K_w]:
new_x = player_x + move_speed * math.cos(player_dir)
new_y = player_y + move_speed * math.sin(player_dir)
if game_map[int(new_y)][int(new_x)] == 0:
player_x = new_x
player_y = new_y
# Movement: Backward
if keys[pygame.K_s]:
new_x = player_x - move_speed * math.cos(player_dir)
new_y = player_y - move_speed * math.sin(player_dir)
if game_map[int(new_y)][int(new_x)] == 0:
player_x = new_x
player_y = new_y
# Rotation: Right
if keys[pygame.K_d]:
player_dir += rot_speed
plane_x = math.cos(player_dir + math.pi / 2) * math.tan(FOV / 2)
plane_y = math.sin(player_dir + math.pi / 2) * math.tan(FOV / 2)
# Rotation: Left
if keys[pygame.K_a]:
player_dir -= rot_speed
plane_x = math.cos(player_dir + math.pi / 2) * math.tan(FOV / 2)
plane_y = math.sin(player_dir + math.pi / 2) * math.tan(FOV / 2)
# Rendering
# Draw ceiling and floor
screen.fill(BLACK)
pygame.draw.rect(screen, (100, 100, 100), (0, 0, WIDTH, HEIGHT // 2)) # Ceiling
pygame.draw.rect(screen, (50, 50, 50), (0, HEIGHT // 2, WIDTH, HEIGHT // 2)) # Floor
# Cast rays and draw walls
cast_rays(player_x, player_y, player_dir, plane_x, plane_y, screen)
# Optional: Draw 2D map for debugging
map_scale = 32 # Scale for the mini-map
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
rect = pygame.Rect(x * map_scale, y * map_scale, map_scale, map_scale)
color = WHITE if game_map[y][x] > 0 else (50, 50, 50)
pygame.draw.rect(screen, color, rect)
pygame.draw.rect(screen, BLACK, rect, 1) # Grid lines
# Draw player on the map
pygame.draw.circle(screen, RED, (int(player_x * map_scale), int(player_y * map_scale)), 5)
# Draw direction line
pygame.draw.line(screen, GREEN,
(int(player_x * map_scale), int(player_y * map_scale)),
(int((player_x + math.cos(player_dir)) * map_scale),
int((player_y + math.sin(player_dir)) * map_scale)), 2)
# Update display
pygame.display.flip()
# Control frame rate
clock.tick(60) # 60 FPS
Event Handling: Listens for the quit event to close the game.
Key Presses:
W: Move forward.S: Move backward.A: Rotate left.D: Rotate right.ESC: Exit the game.Movement Logic:
Rotation Logic:
Rendering:
cast_rays function to render the walls using raycasting.Display Update: Updates the Pygame display with the new frame.
Frame Rate Control: Maintains a consistent frame rate of 60 FPS.
Once you have the basic raycasting engine working, consider adding the following features to enhance your game:
Textured Walls:
Sprites:
Collision Detection:
Lighting and Shading:
Minimap Interface:
User Interface (UI):
Sound Effects and Music:
Level Design:
Putting it all together, here's the complete code for the basic raycasting game in Pygame:
import pygame
import math
import sys
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 640, 480
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Raycasting Game in Pygame")
# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
DARK_BLUE = (0, 0, 155)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# Clock for controlling frame rate
clock = pygame.time.Clock()
# Define the map layout
game_map = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,1],
[1,0,1,0,1,1,1,0,0,1],
[1,0,1,0,0,0,1,0,0,1],
[1,0,1,1,1,0,1,0,0,1],
[1,0,0,0,1,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1],
]
MAP_WIDTH = len(game_map[0])
MAP_HEIGHT = len(game_map)
# Player starting position and direction
player_x, player_y = 3.0, 3.0 # Starting coordinates
player_dir = 0.0 # Facing right (0 radians)
# Camera plane (perpendicular to the direction)
FOV = math.pi / 3 # 60 degrees
plane_x = math.cos(player_dir + math.pi / 2) * math.tan(FOV / 2)
plane_y = math.sin(player_dir + math.pi / 2) * math.tan(FOV / 2)
# Movement parameters
move_speed = 0.05
rot_speed = 0.03
def cast_rays(player_x, player_y, player_dir, plane_x, plane_y, screen):
for x in range(WIDTH):
# Calculate ray position and direction
camera_x = 2 * x / WIDTH - 1 # x-coordinate in camera space
ray_dir_x = math.cos(player_dir) + plane_x * camera_x
ray_dir_y = math.sin(player_dir) + plane_y * camera_x
# Which box of the map we're in
map_x = int(player_x)
map_y = int(player_y)
# Length of ray from current position to next x or y-side
delta_dist_x = abs(1 / ray_dir_x) if ray_dir_x != 0 else float('inf')
delta_dist_y = abs(1 / ray_dir_y) if ray_dir_y != 0 else float('inf')
# Calculate step and initial sideDist
if ray_dir_x < 0:
step_x = -1
side_dist_x = (player_x - map_x) * delta_dist_x
else:
step_x = 1
side_dist_x = (map_x + 1.0 - player_x) * delta_dist_x
if ray_dir_y < 0:
step_y = -1
side_dist_y = (player_y - map_y) * delta_dist_y
else:
step_y = 1
side_dist_y = (map_y + 1.0 - player_y) * delta_dist_y
# Perform DDA
hit = False
side = 0
while not hit:
# Jump to next map square, either in x or y direction
if side_dist_x < side_dist_y:
side_dist_x += delta_dist_x
map_x += step_x
side = 0 # 0 for x-side
else:
side_dist_y += delta_dist_y
map_y += step_y
side = 1 # 1 for y-side
# Check if ray has hit a wall
if map_x >= MAP_WIDTH or map_x < 0 or map_y >= MAP_HEIGHT or map_y < 0:
hit = True
perp_wall_dist = float('inf')
elif game_map[map_y][map_x] > 0:
hit = True
# Calculate distance to the point of impact
if side == 0:
perp_wall_dist = (map_x - player_x + (1 - step_x) / 2) / ray_dir_x
else:
perp_wall_dist = (map_y - player_y + (1 - step_y) / 2) / ray_dir_y
# Calculate height of line to draw on screen
line_height = int(HEIGHT / perp_wall_dist) if perp_wall_dist > 0 else HEIGHT
# Calculate lowest and highest pixel to fill in current stripe
draw_start = max(-line_height // 2 + HEIGHT // 2, 0)
draw_end = min(line_height // 2 + HEIGHT // 2, HEIGHT - 1)
# Choose wall color with simple shading based on distance and side
if perp_wall_dist < float('inf'):
shade = max(50, min(255, int(255 / (1 + perp_wall_dist * perp_wall_dist * 0.1))))
color = (shade, shade, shade) if side == 0 else (shade // 2, shade // 2, shade)
else:
color = BLACK
# Draw the vertical line
pygame.draw.line(screen, color, (x, draw_start), (x, draw_end))
# Main game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Handle key presses
keys = pygame.key.get_pressed()
if keys[pygame.K_ESCAPE]:
pygame.quit()
sys.exit()
# Movement: Forward
if keys[pygame.K_w]:
new_x = player_x + move_speed * math.cos(player_dir)
new_y = player_y + move_speed * math.sin(player_dir)
if game_map[int(new_y)][int(new_x)] == 0:
player_x = new_x
player_y = new_y
# Movement: Backward
if keys[pygame.K_s]:
new_x = player_x - move_speed * math.cos(player_dir)
new_y = player_y - move_speed * math.sin(player_dir)
if game_map[int(new_y)][int(new_x)] == 0:
player_x = new_x
player_y = new_y
# Rotation: Right
if keys[pygame.K_d]:
player_dir += rot_speed
plane_x = math.cos(player_dir + math.pi / 2) * math.tan(FOV / 2)
plane_y = math.sin(player_dir + math.pi / 2) * math.tan(FOV / 2)
# Rotation: Left
if keys[pygame.K_a]:
player_dir -= rot_speed
plane_x = math.cos(player_dir + math.pi / 2) * math.tan(FOV / 2)
plane_y = math.sin(player_dir + math.pi / 2) * math.tan(FOV / 2)
# Rendering
# Draw ceiling and floor
screen.fill(BLACK)
pygame.draw.rect(screen, (100, 100, 100), (0, 0, WIDTH, HEIGHT // 2)) # Ceiling
pygame.draw.rect(screen, (50, 50, 50), (0, HEIGHT // 2, WIDTH, HEIGHT // 2)) # Floor
# Cast rays and draw walls
cast_rays(player_x, player_y, player_dir, plane_x, plane_y, screen)
# Optional: Draw 2D map for debugging
map_scale = 32 # Scale for the mini-map
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
rect = pygame.Rect(x * map_scale, y * map_scale, map_scale, map_scale)
color = WHITE if game_map[y][x] > 0 else (50, 50, 50)
pygame.draw.rect(screen, color, rect)
pygame.draw.rect(screen, BLACK, rect, 1) # Grid lines
# Draw player on the map
pygame.draw.circle(screen, RED, (int(player_x * map_scale), int(player_y * map_scale)), 5)
# Draw direction line
pygame.draw.line(screen, GREEN,
(int(player_x * map_scale), int(player_y * map_scale)),
(int((player_x + math.cos(player_dir)) * map_scale),
int((player_y + math.sin(player_dir)) * map_scale)), 2)
# Update display
pygame.display.flip()
# Control frame rate
clock.tick(60) # 60 FPS
Save the Code: Save the complete code in a file named main.py within your project directory.
Execute the Script: Open your terminal or command prompt, navigate to the project directory, and run:
python main.py
Controls:
You should see a 3D-rendered environment where you can navigate through walls and empty spaces. The mini-map is displayed in the top-left corner for reference.
This tutorial provided a foundational understanding of how raycasting works in generating a 3D-like environment within a 2D grid-based map. By implementing this basic engine, you've learned about:
From here, you can expand your game by adding textures, sprites, collision detection enhancements, interactive objects, and more sophisticated graphics and controls. Raycasting serves as an excellent stepping stone into the world of game development and 3D rendering. Happy coding!
Not yet included in a published release.