Make raycast game in pygame and add advanced lightning
- User
Make raycast game in pygame and add advanced lightning
- Assistant
Make raycast game in pygame and add advanced lightning
Creating a raycasting game in Pygame with advanced lighting effects is an exciting project that combines 2D rendering with 3D-like visuals. Raycasting is a rendering technique used to create a 3D perspective in a 2D game world by casting rays from the player's position to detect walls and calculate distances.
Below, I'll guide you through the process of building a basic raycasting engine using Pygame and then add advanced lighting effects to enhance the visual experience.
Python 3.x: Ensure you have Python installed. You can download it from python.org.
Pygame: Install Pygame using pip:
pip install pygame
First, import the necessary modules and initialize Pygame:
import pygame
import math
import sys
pygame.init()
Set up the game window dimensions and create a display surface:
WIDTH, HEIGHT = 800, 600
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Raycasting Game with Advanced Lighting")
Define some colors:
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
Set the frames per second (FPS):
FPS = 60
Create a simple map for the player to navigate. The map will be a 2D grid where 1 represents a wall and 0 represents empty space.
GAME_MAP = [
'1111111111111111',
'1..............1',
'1..............1',
'1......11......1',
'1..............1',
'1..............1',
'1......11......1',
'1..............1',
'1111111111111111',
]
MAP_WIDTH = len(GAME_MAP[0])
MAP_HEIGHT = len(GAME_MAP)
TILE_SIZE = 64
Define the player's attributes:
player_pos = [TILE_SIZE * 1.5, TILE_SIZE * 1.5]
player_angle = 0
player_speed = 2
Create a function to handle the raycasting:
def cast_rays():
FOV = math.pi / 3
NUM_RAYS = 120
MAX_DEPTH = 800
DELTA_ANGLE = FOV / NUM_RAYS
DISTANCE_PROJE_PLANE = (WIDTH // 2) / math.tan(FOV / 2)
SCALE = WIDTH // NUM_RAYS
current_angle = player_angle - FOV / 2
for ray in range(NUM_RAYS):
sin_a = math.sin(current_angle)
cos_a = math.cos(current_angle)
for depth in range(MAX_DEPTH):
target_x = player_pos[0] + depth * cos_a
target_y = player_pos[1] + depth * sin_a
col = int(target_x // TILE_SIZE)
row = int(target_y // TILE_SIZE)
if 0 <= col < MAP_WIDTH and 0 <= row < MAP_HEIGHT:
if GAME_MAP[row][col] == '1':
# Calculate wall shading based on depth
depth *= math.cos(player_angle - current_angle)
depth = max(depth, 0.0001)
proj_height = min(int(DISTANCE_PROJE_PLANE / depth * TILE_SIZE), 2 * HEIGHT)
color_intensity = 255 / (1 + depth * depth * 0.0001)
wall_color = (color_intensity, color_intensity, color_intensity)
pygame.draw.rect(
WINDOW,
wall_color,
(ray * SCALE, (HEIGHT // 2) - proj_height // 2, SCALE, proj_height)
)
break # Hit a wall, move to next ray
current_angle += DELTA_ANGLE
Create a function to handle player movement and rotation:
def move_player():
keys = pygame.key.get_pressed()
sin_a = math.sin(player_angle)
cos_a = math.cos(player_angle)
dx, dy = 0, 0
speed = player_speed
if keys[pygame.K_w]:
dx += cos_a * speed
dy += sin_a * speed
if keys[pygame.K_s]:
dx -= cos_a * speed
dy -= sin_a * speed
if keys[pygame.K_a]:
dx += sin_a * speed
dy -= cos_a * speed
if keys[pygame.K_d]:
dx -= sin_a * speed
dy += cos_a * speed
# Collision detection
next_x = player_pos[0] + dx
next_y = player_pos[1] + dy
if GAME_MAP[int(next_y // TILE_SIZE)][int(next_x // TILE_SIZE)] != '1':
player_pos[0] = next_x
player_pos[1] = next_y
Create the main game loop:
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Update
move_player()
# Rotate player
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_angle -= 0.02
if keys[pygame.K_RIGHT]:
player_angle += 0.02
# Draw
WINDOW.fill(BLACK)
cast_rays()
pygame.display.flip()
clock.tick(FPS)
To add advanced lighting, we'll implement a basic shading model that simulates light diminishing over distance and angle between the player's view and the wall's normal.
First, define a function to calculate the shading based on distance and angle:
def calculate_lighting(depth, angle_diff):
# Ambient lighting
ambient = 30
# Light diminishes with square of distance
depth_coeff = max(depth * depth * 0.0001, 1)
# Diffuse shading based on angle
diffuse = max(math.cos(angle_diff), 0)
# Calculate final intensity
intensity = ambient + (255 - ambient) * diffuse / depth_coeff
intensity = min(max(intensity, 0), 255)
return intensity
Update the cast_rays function to use this lighting model:
def cast_rays():
FOV = math.pi / 3
NUM_RAYS = 120
MAX_DEPTH = 800
DELTA_ANGLE = FOV / NUM_RAYS
DISTANCE_PROJE_PLANE = (WIDTH // 2) / math.tan(FOV / 2)
SCALE = WIDTH // NUM_RAYS
current_angle = player_angle - FOV / 2
for ray in range(NUM_RAYS):
sin_a = math.sin(current_angle)
cos_a = math.cos(current_angle)
for depth in range(MAX_DEPTH):
target_x = player_pos[0] + depth * cos_a
target_y = player_pos[1] + depth * sin_a
col = int(target_x // TILE_SIZE)
row = int(target_y // TILE_SIZE)
if 0 <= col < MAP_WIDTH and 0 <= row < MAP_HEIGHT:
if GAME_MAP[row][col] == '1':
# Correct fish-eye effect
depth *= math.cos(player_angle - current_angle)
depth = max(depth, 0.0001)
proj_height = min(int(DISTANCE_PROJE_PLANE / depth * TILE_SIZE), 2 * HEIGHT)
# Calculate lighting
angle_diff = math.atan2(target_y - player_pos[1], target_x - player_pos[0]) - player_angle
color_intensity = calculate_lighting(depth, angle_diff)
wall_color = (color_intensity, color_intensity, color_intensity)
pygame.draw.rect(
WINDOW,
wall_color,
(ray * SCALE, (HEIGHT // 2) - proj_height // 2, SCALE, proj_height)
)
break # Hit a wall, move to next ray
current_angle += DELTA_ANGLE
Here's the complete code with all the components combined:
import pygame
import math
import sys
pygame.init()
WIDTH, HEIGHT = 800, 600
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Raycasting Game with Advanced Lighting")
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
FPS = 60
GAME_MAP = [
'1111111111111111',
'1..............1',
'1..............1',
'1......11......1',
'1..............1',
'1..............1',
'1......11......1',
'1..............1',
'1111111111111111',
]
MAP_WIDTH = len(GAME_MAP[0])
MAP_HEIGHT = len(GAME_MAP)
TILE_SIZE = 64
player_pos = [TILE_SIZE * 1.5, TILE_SIZE * 1.5]
player_angle = 0
player_speed = 2
def calculate_lighting(depth, angle_diff):
ambient = 30
depth_coeff = max(depth * depth * 0.0001, 1)
diffuse = max(math.cos(angle_diff), 0)
intensity = ambient + (255 - ambient) * diffuse / depth_coeff
intensity = min(max(intensity, 0), 255)
return intensity
def cast_rays():
FOV = math.pi / 3
NUM_RAYS = 240
MAX_DEPTH = 800
DELTA_ANGLE = FOV / NUM_RAYS
DISTANCE_PROJE_PLANE = (WIDTH // 2) / math.tan(FOV / 2)
SCALE = WIDTH // NUM_RAYS
current_angle = player_angle - FOV / 2
for ray in range(NUM_RAYS):
sin_a = math.sin(current_angle)
cos_a = math.cos(current_angle)
for depth in range(MAX_DEPTH):
target_x = player_pos[0] + depth * cos_a
target_y = player_pos[1] + depth * sin_a
col = int(target_x // TILE_SIZE)
row = int(target_y // TILE_SIZE)
if 0 <= col < MAP_WIDTH and 0 <= row < MAP_HEIGHT:
if GAME_MAP[row][col] == '1':
depth *= math.cos(player_angle - current_angle)
depth = max(depth, 0.0001)
proj_height = min(int(DISTANCE_PROJE_PLANE / depth * TILE_SIZE), 2 * HEIGHT)
angle_diff = math.atan2(target_y - player_pos[1], target_x - player_pos[0]) - player_angle
color_intensity = calculate_lighting(depth, angle_diff)
wall_color = (color_intensity, color_intensity, color_intensity)
pygame.draw.rect(
WINDOW,
wall_color,
(ray * SCALE, (HEIGHT // 2) - proj_height // 2, SCALE, proj_height)
)
break
current_angle += DELTA_ANGLE
def move_player():
keys = pygame.key.get_pressed()
sin_a = math.sin(player_angle)
cos_a = math.cos(player_angle)
dx, dy = 0, 0
speed = player_speed
if keys[pygame.K_w]:
dx += cos_a * speed
dy += sin_a * speed
if keys[pygame.K_s]:
dx -= cos_a * speed
dy -= sin_a * speed
if keys[pygame.K_a]:
dx += sin_a * speed
dy -= cos_a * speed
if keys[pygame.K_d]:
dx -= sin_a * speed
dy += cos_a * speed
next_x = player_pos[0] + dx
next_y = player_pos[1] + dy
if GAME_MAP[int(next_y // TILE_SIZE)][int(next_x // TILE_SIZE)] != '1':
player_pos[0] = next_x
player_pos[1] = next_y
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
move_player()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_angle -= 0.03
if keys[pygame.K_RIGHT]:
player_angle += 0.03
WINDOW.fill(BLACK)
cast_rays()
pygame.display.flip()
clock.tick(FPS)
Save the Code: Copy the complete code and save it in a file named raycasting_game.py.
Run the Game:
python raycasting_game.py
Use the following controls to navigate:
You've now created a raycasting game in Pygame with advanced lighting effects! This basic engine can be expanded upon to include textures, more complex lighting models, and additional game features like enemies and items.
Next Steps:
Feel free to ask if you have any questions or need further assistance with expanding the game!
Not yet included in a published release.