Make raycast game in pygame, generate forest
Rate quality
Private research annotation
Sign in to add a private research label or note.
- User
Make raycast game in pygame, generate forest
- Assistant
Sign in to add a private research label or note.
Make raycast game in pygame, generate forest
Creating a raycasting game in Pygame that generates a forest environment is an exciting project that combines procedural generation with classic game rendering techniques. Below, I'll guide you through the process step-by-step and provide code snippets to help you build the game.
Note: Raycasting is a rendering technique used to create a 3D perspective in a 2D game world, popularized by games like Wolfenstein 3D.
First, make sure you have Pygame installed:
pip install pygame
Create a new Python file, e.g., raycast_forest.py, and import the necessary modules:
import pygame
import math
import random
Initialize Pygame and set up the display:
pygame.init()
WIDTH, HEIGHT = 800, 600
HALF_WIDTH = WIDTH // 2
HALF_HEIGHT = HEIGHT // 2
FPS = 60
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
In raycasting, we simulate rays cast from the player’s position, checking where they intersect with walls in the 2D map, and then render vertical slices on the screen to create a 3D effect.
We'll represent the forest as a 2D grid map where 0 indicates empty space, and 1 indicates a tree.
Let's procedurally generate a map with random trees:
MAP_WIDTH, MAP_HEIGHT = 50, 50
map_data = []
def generate_forest():
global map_data
map_data = []
for y in range(MAP_HEIGHT):
row = []
for x in range(MAP_WIDTH):
# Randomly place trees with a certain density
if random.random() < 0.2: # 20% chance of a tree
row.append(1)
else:
row.append(0)
map_data.append(row)
generate_forest()
Here's a simplified raycasting function:
def cast_rays(px, py, pa):
rays = []
ray_angle = pa - math.radians(30) # 60-degree FOV
for ray in range(120): # Number of rays
for depth in range(20):
# Calculate ray coordinates
target_x = px + math.cos(ray_angle) * depth
target_y = py + math.sin(ray_angle) * depth
# Map indices
mx = int(target_x)
my = int(target_y)
# Check for map boundaries
if 0 <= mx < MAP_WIDTH and 0 <= my < MAP_HEIGHT:
if map_data[my][mx] == 1: # Hit a tree
# Record the distance and angle
distance = depth * math.cos(pa - ray_angle)
rays.append((ray, distance))
break
else:
# No wall hit
rays.append((ray, 20))
ray_angle += math.radians(0.5) # Adjust angle for next ray
return rays
Set up player variables and handle input:
player_x, player_y = MAP_WIDTH // 2, MAP_HEIGHT // 2
player_angle = 0
def handle_input():
global player_x, player_y, player_angle
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_angle -= 0.05
if keys[pygame.K_RIGHT]:
player_angle += 0.05
if keys[pygame.K_UP]:
player_x += math.cos(player_angle) * 0.1
player_y += math.sin(player_angle) * 0.1
if keys[pygame.K_DOWN]:
player_x -= math.cos(player_angle) * 0.1
player_y -= math.sin(player_angle) * 0.1
Render the 3D view based on the raycasting results:
def render_scene(rays):
screen.fill((135, 206, 235)) # Sky blue
for ray, distance in rays:
# Calculate the height of the wall slice
shade = 255 / (1 + distance * distance * 0.1)
color = (0, int(shade), 0) # Dark green trees
line_height = HEIGHT / (distance + 0.1)
line_offset = HALF_HEIGHT - line_height / 2
pygame.draw.rect(screen, color, (ray * (WIDTH // 120), line_offset, (WIDTH // 120), line_height))
Combine everything in the main loop:
running = True
while running:
clock.tick(FPS)
handle_input()
rays = cast_rays(player_x, player_y, player_angle)
render_scene(rays)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
pygame.quit()
Here's the complete code combining all the sections above:
import pygame
import math
import random
pygame.init()
WIDTH, HEIGHT = 800, 600
HALF_WIDTH = WIDTH // 2
HALF_HEIGHT = HEIGHT // 2
FPS = 60
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
MAP_WIDTH, MAP_HEIGHT = 50, 50
map_data = []
def generate_forest():
global map_data
map_data = []
for y in range(MAP_HEIGHT):
row = []
for x in range(MAP_WIDTH):
# Randomly place trees with a certain density
if random.random() < 0.2: # 20% chance of a tree
row.append(1)
else:
row.append(0)
map_data.append(row)
def cast_rays(px, py, pa):
rays = []
ray_angle = pa - math.radians(30) # 60-degree FOV
for ray in range(120): # Number of rays
ray_angle += math.radians(0.5)
sin_a = math.sin(ray_angle)
cos_a = math.cos(ray_angle)
for depth in range(1, 20):
# Calculate ray coordinates
target_x = px + cos_a * depth * 0.5
target_y = py + sin_a * depth * 0.5
# Map indices
mx = int(target_x)
my = int(target_y)
# Check for map boundaries
if 0 <= mx < MAP_WIDTH and 0 <= my < MAP_HEIGHT:
if map_data[my][mx] == 1: # Hit a tree
# Record the distance and angle
distance = depth * 0.5 * math.cos(pa - ray_angle)
rays.append((ray, distance))
break
else:
# No wall hit
rays.append((ray, 20))
return rays
def render_scene(rays):
screen.fill((135, 206, 235)) # Sky blue
for ray, distance in rays:
# Calculate the height of the wall slice
shade = 255 / (1 + distance * distance * 0.1)
color = (0, int(shade), 0) # Dark green trees
line_height = HEIGHT / (distance + 0.1)
line_offset = HALF_HEIGHT - line_height / 2
pygame.draw.rect(screen, color, (ray * (WIDTH // 120), line_offset, (WIDTH // 120), line_height))
player_x, player_y = MAP_WIDTH // 2, MAP_HEIGHT // 2
player_angle = 0
def handle_input():
global player_x, player_y, player_angle
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_angle -= 0.05
if keys[pygame.K_RIGHT]:
player_angle += 0.05
if keys[pygame.K_UP]:
player_x += math.cos(player_angle) * 0.1
player_y += math.sin(player_angle) * 0.1
if keys[pygame.K_DOWN]:
player_x -= math.cos(player_angle) * 0.1
player_y -= math.sin(player_angle) * 0.1
generate_forest()
running = True
while running:
clock.tick(FPS)
handle_input()
rays = cast_rays(player_x, player_y, player_angle)
render_scene(rays)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
pygame.quit()
generate_forest() creates a 2D array representing the forest, randomly placing trees.cast_rays() simulates casting rays from the player's perspective to detect trees and calculate distances.render_scene() draws vertical slices representing trees, adjusting the height based on distance to create a 3D effect.handle_input() updates the player's position and angle based on keyboard input.This code provides a basic framework for a raycasting game in Pygame with a procedurally generated forest. From here, you can expand upon the mechanics, improve the graphics, and add new features to create a full-fledged game.
Happy coding!
Not yet included in a published release.