Untitled conversation
- Userpython
- Assistant
# raycaster.py
import math
import pygame
from map import game_map
class Raycaster:
def __init__(self, screen, player, textures, fov=60, max_depth=20):
self.screen = screen
self.player = player
self.textures = textures
self.map = game_map
self.screen_width, self.screen_height = self.screen.get_size()
self.fov = math.radians(fov)
self.max_depth = max_depth
# Количество лучей равное ширине экрана (1 луч на пиксель)
self.num_rays = self.screen_width
self.delta_angle = self.fov / self.num_rays
self.dist_proj_plane = (self.screen_width / 2) / math.tan(self.fov / 2)
def cast_single_ray(self, angle):
sin_a = math.sin(angle)
cos_a = math.cos(angle)
# Текущие координаты в сетке карты
map_x = int(self.player.x)
map_y = int(self.player.y)
# Расстояния до следующего пересечения по x и y
delta_dist_x = abs(1 / cos_a) if cos_a != 0 else 1e30
delta_dist_y = abs(1 / sin_a) if sin_a != 0 else 1e30
# Шаги по x и y
if cos_a < 0:
step_x = -1
side_dist_x = (self.player.x - map_x) * delta_dist_x
else:
step_x = 1
side_dist_x = (map_x + 1.0 - self.player.x) * delta_dist_x
if sin_a < 0:
step_y = -1
side_dist_y = (self.player.y - map_y) * delta_dist_y
else:
step_y = 1
side_dist_y = (map_y + 1.0 - self.player.y) * delta_dist_y
# DDA алгоритм
hit = False
side = None
while not hit:
if side_dist_x < side_dist_y:
side_dist_x += delta_dist_x
map_x += step_x
side = 'vert'
else:
side_dist_y += delta_dist_y
map_y += step_y
side = 'hor'
# Проверка на пересечение стены
if 0 <= map_x < len(self.map[0]) and 0 <= map_y < len(self.map):
if self.map[map_y][map_x] != 0:
hit = True
break
else:
# Выход за пределы карты
return self.max_depth, None, 0
# Вычисление расстояния до точки пересечения
if side == 'vert':
perp_wall_dist = (map_x - self.player.x + (1 - step_x) / 2) / cos_a
offset = self.player.y + perp_wall_dist * sin_a
else:
perp_wall_dist = (map_y - self.player.y + (1 - step_y) / 2) / sin_a
offset = self.player.x + perp_wall_dist * cos_a
offset -= math.floor(offset)
# Получение типа стены
wall_type = self.map[map_y][map_x]
# Загрузка текстуры
texture = self.textures.get(str(wall_type), self.textures['1'])
return perp_wall_dist, texture, offset
def render(self):
# 1. Отрисовка потолка и пола сначала
floor_texture = self.textures.get('floor')
ceiling_texture = self.textures.get('ceiling')
if floor_texture and ceiling_texture:
# Создание поверхностей для пола и потолка
floor_scaled = pygame.transform.scale(
floor_texture,
(self.screen_width, self.screen_height // 2)
)
ceiling_scaled = pygame.transform.scale(
ceiling_texture,
(self.screen_width, self.screen_height // 2)
)
# Отрисовка потолка и пола
self.screen.blit(ceiling_scaled, (0, 0))
self.screen.blit(floor_scaled, (0, self.screen_height // 2))
else:
# Если текстуры отсутствуют, рисуем однотонные цвета
pygame.draw.rect(self.screen, (100, 100, 100), (0, 0, self.screen_width, self.screen_height // 2)) # Потолок
pygame.draw.rect(self.screen, (70, 70, 70), (0, self.screen_height // 2, self.screen_width, self.screen_height // 2)) # Пол
# 2. Отрисовка стен
current_angle = self.player.angle - self.fov / 2
for ray in range(self.num_rays):
depth, texture, offset = self.cast_single_ray(current_angle)
# Коррекция эффекта "кошачьего глаза"
depth_corrected = depth * math.cos(self.player.angle - current_angle)
# Вычисление высоты проекции стены
if depth_corrected > 0:
proj_height = min(int(self.dist_proj_plane / (depth_corrected + 1e-5)), self.screen_height)
else:
proj_height = self.screen_height
# Затенение на основе расстояния
shade = max(255 - int(depth_corrected * 12), 30)
if texture:
# Вычисление координаты текстуры по x
tex_width, tex_height = texture.get_size()
tex_x = int(offset * tex_width)
tex_x = max(0, min(tex_x, tex_width - 1)) # Ограничение координаты
# Получение вертикального среза текстуры
wall_column = texture.subsurface(tex_x, 0, 1, tex_height).copy()
# Масштабирование вертикального среза текстуры по высоте стены
wall_column = pygame.transform.scale(wall_column, (1, proj_height))
# Применение затенения
wall_column.fill((shade, shade, shade), special_flags=pygame.BLEND_MULT)
# Отрисовка стены
self.screen.blit(wall_column, (ray, self.screen_height // 2 - proj_height // 2))
else:
# Если текстура не найдена, отрисовка однотонного цвета
pygame.draw.rect(self.screen, (shade, shade, shade),
(ray, self.screen_height // 2 - proj_height // 2, 1, proj_height))
# Увеличение угла для следующего луча
current_angle += self.delta_angle
# main.py
import pygame
import sys
import math
from player import Player
from raycaster import Raycaster
from map import game_map
def load_textures():
textures = {}
try:
# Загрузка текстуры для стен типа 1
textures['1'] = pygame.image.load('textures/wall1.png').convert_alpha()
textures['1'] = pygame.transform.scale(textures['1'], (64, 64))
except pygame.error:
print("Не удалось загрузить 'wall1.png'. Используется цвет по умолчанию.")
wall1 = pygame.Surface((64, 64))
wall1.fill((200, 0, 0))
textures['1'] = wall1
try:
# Загрузка текстуры для стен типа 2
textures['2'] = pygame.image.load('textures/wall2.png').convert_alpha()
textures['2'] = pygame.transform.scale(textures['2'], (64, 64))
except pygame.error:
print("Не удалось загрузить 'wall2.png'. Используется цвет по умолчанию.")
wall2 = pygame.Surface((64, 64))
wall2.fill((0, 200, 0))
textures['2'] = wall2
try:
# Загрузка текстуры пола
textures['floor'] = pygame.image.load('textures/floor.png').convert_alpha()
textures['floor'] = pygame.transform.scale(textures['floor'], (64, 64))
except pygame.error:
print("Не удалось загрузить 'floor.png'. Используется цвет по умолчанию.")
floor = pygame.Surface((64, 64))
floor.fill((50, 50, 50))
textures['floor'] = floor
try:
# Загрузка текстуры потолка
textures['ceiling'] = pygame.image.load('textures/ceiling.png').convert_alpha()
textures['ceiling'] = pygame.transform.scale(textures['ceiling'], (64, 64))
except pygame.error:
print("Не удалось загрузить 'ceiling.png'. Используется цвет по умолчанию.")
ceiling = pygame.Surface((64, 64))
ceiling.fill((80, 80, 80))
textures['ceiling'] = ceiling
return textures
def main():
pygame.init()
clock = pygame.time.Clock()
# Параметры окна
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Raycasting Game - Профессиональная Версия")
# Скрываем курсор и захватываем мышь
pygame.event.set_grab(True)
pygame.mouse.set_visible(False)
# Загрузка текстур
textures = load_textures()
# Инициализация игрока
# Инициализируем в свободной области карты, например, (1.5, 1.5)
player = Player(x=1.5, y=1.5, angle=0)
# Проверяем, что начальная позиция свободна
if game_map[int(player.y)][int(player.x)] != 0:
print("Ошибка: начальная позиция игрока занята стеной.")
pygame.quit()
sys.exit()
# Инициализация рэйкастера
raycaster = Raycaster(screen, player, textures)
# Основной игровой цикл
running = True
while running:
delta_time = clock.tick(60) / 1000.0 # Время с прошлого кадра (секунды)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
break
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
break
# Обработка ввода с клавиатуры
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
player.move(game_map, 'forward', delta_time)
if keys[pygame.K_s]:
player.move(game_map, 'backward', delta_time)
if keys[pygame.K_a]:
player.rotate('left', delta_time)
if keys[pygame.K_d]:
player.rotate('right', delta_time)
# Обработка ввода с мыши для вращения обзора
mouse_dx, _ = pygame.mouse.get_rel()
sensitivity = 0.002 # Настройка чувствительности мыши
player.angle += mouse_dx * sensitivity
player.angle %= 2 * math.pi # Ограничение угла в диапазоне [0, 2π]
# Рендеринг сцены
raycaster.render()
# Обновление экрана
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
# player.py
import math
class Player:
def __init__(self, x, y, angle=0):
self.x = x
self.y = y
self.angle = angle # В радианах
self.move_speed = 3.0 # Ячейки в секунду
self.rot_speed = 120.0 # Угловой поворот в градусах в секунду
def move(self, game_map, direction, delta_time):
# Направление движения: 'forward' или 'backward'
rad_angle = self.angle
if direction == 'backward':
rad_angle = (self.angle + math.pi) % (2 * math.pi)
dx = math.cos(rad_angle) * self.move_speed * delta_time
dy = math.sin(rad_angle) * self.move_speed * delta_time
new_x = self.x + dx
new_y = self.y + dy
# Проверка коллизий
if 0 <= int(new_y) < len(game_map) and 0 <= int(self.x) < len(game_map[0]):
if game_map[int(new_y)][int(self.x)] == 0:
self.y = new_y
if 0 <= int(self.y) < len(game_map) and 0 <= int(new_x) < len(game_map[0]):
if game_map[int(self.y)][int(new_x)] == 0:
self.x = new_x
def rotate(self, direction, delta_time):
# Направление поворота: 'left' или 'right'
rot_amount = math.radians(self.rot_speed) * delta_time
if direction == 'right':
self.angle += rot_amount
elif direction == 'left':
self.angle -= rot_amount
self.angle %= 2 * math.pi
Improve rendering, add shadows, optimize code, improve code and structure
Improving a raycasting engine involves enhancing the rendering quality, adding visual effects like shadows, optimizing performance, and refining the code structure for maintainability and scalability. Below are comprehensive enhancements to your existing codebase, addressing these aspects.
Rendering Enhancements:
Adding Shadows:
Code Optimization:
Code Structure Improvements:
Let's delve into each improvement step-by-step with the corresponding updated code.
Instead of scaling preloaded floor and ceiling textures, we'll implement floor and ceiling casting. This method accurately projects the floor and ceiling based on the player's perspective, providing a more immersive experience.
Enhance wall texture mapping by ensuring textures wrap correctly and minimizing distortion. This involves calculating the exact texture coordinates based on the intersection points.
Implement shading based on distance to simulate lighting effects, making walls farther away appear darker, thereby adding depth to the scene.
raycaster.pyPrecomputing Ray Angles, Sines, and Cosines:
Separated Rendering Methods:
render_walls and render_floor_ceiling methods to modularize rendering logic, improving code readability and maintainability.Floor and Ceiling Casting:
render_floor_ceiling to accurately project floor and ceiling textures based on the player's position and perspective.Dynamic Shading:
depth_corrected) to simulate lighting effects and add depth to the scene.Optimized Texture Mapping:
tex_x) are clamped within valid ranges to prevent texture bleeding or artifacts.Shadows can be simulated by adjusting the brightness of wall textures based on their distance from the player. This effect has already been incorporated in the render_walls method through dynamic shading. However, we can refine it further for a more nuanced shadow effect.
Use an exponential decay function for shading instead of a linear decrease. This approach provides a more natural attenuation of light with distance.
raycaster.py# Inside the render_walls method
# Shading based on distance using exponential decay
max_shade = 255
min_shade = 30
shade = max_shade * math.exp(-depth_corrected * 0.1)
shade = max(min_shade, min(int(shade), max_shade))
Exponential Shading:
math.exp(-depth_corrected * 0.1)) to calculate the shade value, providing a more realistic distance-based shading effect.min_shade and max_shade to ensure walls are never completely dark or overly bright.Flexible Shading Parameters:
0.1) to control how quickly the shading diminishes with distance. You can tweak this value to achieve the desired shadow intensity.Leveraging NumPy arrays for map data can significantly speed up access and manipulation times compared to standard Python lists.
Minimize the use of pygame.Surface operations within critical loops. For example, pre-scale textures or create lookup tables for repeated operations.
Move invariant calculations outside of loops to reduce computational overhead.
map.pyAssuming you have a map.py file defining game_map, let's optimize it using NumPy.
# map.py
import numpy as np
# Example game map (0 = empty space, 1, 2, etc. = different wall types)
game_map = np.array([
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 2, 0, 0, 0, 2, 0, 1],
[1, 0, 1, 0, 0, 0, 0, 0, 0, 1],
[1, 2, 0, 0, 3, 0, 0, 0, 2, 1],
[1, 0, 0, 3, 0, 0, 3, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
], dtype=int)
NumPy Array for Map Data:
game_map to a NumPy array with dtype=int for efficient storage and faster access during raycasting and collision detection.Benefits:
Ensure that the rendering loop minimizes the number of operations per ray.
# raycaster.py (modified render_walls method)
def render_walls(self):
half_screen_height = self.screen_height // 2
for i in range(self.num_rays):
depth, texture, offset = self.cast_single_ray(
self.ray_angles[i],
self.sines[i],
self.cosines[i]
)
# Correct the distance
depth_corrected = depth * self.cosines[i]
# Prevent division by zero
if depth_corrected < 0.0001:
depth_corrected = 0.0001
# Calculate wall height
proj_height = min(int(self.dist_proj_plane / depth_corrected), self.screen_height)
# Exponential shading
shade = max(30, min(int(255 * math.exp(-depth_corrected * 0.1)), 255))
if texture:
tex_width, tex_height = texture.get_size()
tex_x = int(offset * tex_width) % tex_width
# Extract the vertical texture slice
wall_column = texture.subsurface(tex_x, 0, 1, tex_height)
# Scale the texture slice to the projected wall height
wall_column = pygame.transform.scale(wall_column, (1, proj_height))
# Apply shading
wall_column.fill((shade, shade, shade), special_flags=pygame.BLEND_MULT)
# Blit the shaded wall column
self.screen.blit(
wall_column,
(i, half_screen_height - proj_height // 2)
)
else:
# If texture is missing, draw a solid shaded rectangle
pygame.draw.rect(
self.screen,
(shade, shade, shade),
(i, half_screen_height - proj_height // 2, 1, proj_height)
)
Optimized Distance Correction:
math.cos(self.player.angle - angle) with the precomputed cosines[i], which represents math.cos(angle) since angle = self.player.angle + ray_offset.Prevent Division by Zero:
0.0001) to prevent division by zero in cases where depth_corrected is extremely small.Modulo Operation for Texture Mapping:
tex_x to ensure it wraps around the texture width, preventing index errors.Reduced Redundant Calculations:
half_screen_height outside the loop to avoid recalculating it for each ray.Separate rendering, player handling, and game logic into distinct modules or classes to enhance maintainability and readability.
Add type hints across all classes and methods to improve code clarity and assist with debugging.
Refine collision detection to handle diagonal movements more smoothly, preventing the player from getting stuck or clipping through walls.
player.py# player.py
import math
from map import game_map
from typing import Literal
class Player:
def __init__(self, x: float, y: float, angle: float = 0.0):
self.x = x
self.y = y
self.angle = angle # In radians
self.move_speed = 3.0 # Cells per second
self.rot_speed = math.radians(120) # Radians per second
def move(self, direction: Literal['forward', 'backward'], delta_time: float):
# Calculate movement vector
move_step = self.move_speed * delta_time
dx = math.cos(self.angle) * move_step
dy = math.sin(self.angle) * move_step
if direction == 'backward':
dx = -dx
dy = -dy
# Check for collision in the X direction
new_x = self.x + dx
if self.is_walkable(new_x, self.y):
self.x = new_x
# Check for collision in the Y direction
new_y = self.y + dy
if self.is_walkable(self.x, new_y):
self.y = new_y
def rotate(self, direction: Literal['left', 'right'], delta_time: float):
rot_step = self.rot_speed * delta_time
if direction == 'right':
self.angle += rot_step
elif direction == 'left':
self.angle -= rot_step
self.angle %= 2 * math.pi # Keep angle within [0, 2π]
def is_walkable(self, x: float, y: float) -> bool:
map_x, map_y = int(x), int(y)
if 0 <= map_x < game_map.shape[1] and 0 <= map_y < game_map.shape[0]:
return game_map[map_y][map_x] == 0
return False
Type Hinting:
typing.Literal for allowed string values.Improved Collision Detection:
is_walkable method to centralize collision logic.Radians for Rotation Speed:
rot_speed from degrees to radians during initialization to maintain consistency.main.pyTexture Loading Utility Function:
load_texture function to streamline texture loading with default color fallback.Type Hinting:
Extended Texture Support:
'3') to demonstrate scalability.Player Angle Update:
update_player_angle method in the Raycaster class to refresh ray angles when the player rotates (implementation shown below).raycaster.py with update_player_angle Method# Inside the Raycaster class
def update_player_angle(self):
self.ray_angles = [
self.player.angle - self.fov / 2 + i * self.delta_angle
for i in range(self.num_rays)
]
self.sines = [math.sin(angle) for angle in self.ray_angles]
self.cosines = [math.cos(angle) for angle in self.ray_angles]
update_player_angle to recompute ray angles, sines, and cosines whenever the player rotates.By implementing these enhancements, your raycasting engine will exhibit improved rendering quality, dynamic shading effects simulating shadows, optimized performance, and a cleaner, more maintainable codebase. These changes not only elevate the visual fidelity of your game but also lay a solid foundation for future feature additions and scalability.
Implement Sprite Rendering:
Enhance Lighting Effects:
Optimize Further with Caching:
Use Shaders:
Profile and Benchmark:
Feel free to adapt and expand upon these improvements to suit the specific needs and goals of your game project. Happy coding!
Not yet included in a published release.
# raycaster.py
import math
import pygame
from map import game_map
from typing import Tuple, Optional
class Raycaster:
def __init__(
self,
screen: pygame.Surface,
player: 'Player',
textures: dict,
fov: int = 60,
max_depth: float = 20.0
):
self.screen = screen
self.player = player
self.textures = textures
self.map = game_map
self.screen_width, self.screen_height = self.screen.get_size()
self.fov = math.radians(fov)
self.max_depth = max_depth
self.num_rays = self.screen_width
self.delta_angle = self.fov / self.num_rays
self.dist_proj_plane = (self.screen_width / 2) / math.tan(self.fov / 2)
# Precompute sine and cosine for each ray angle
self.ray_angles = [
self.player.angle - self.fov / 2 + i * self.delta_angle
for i in range(self.num_rays)
]
self.sines = [math.sin(angle) for angle in self.ray_angles]
self.cosines = [math.cos(angle) for angle in self.ray_angles]
def cast_single_ray(
self, angle: float, sin_a: float, cos_a: float
) -> Tuple[float, Optional[pygame.Surface], float]:
map_x, map_y = int(self.player.x), int(self.player.y)
# Calculate the distance to the next x and y sides
delta_dist_x = abs(1 / cos_a) if cos_a != 0 else 1e30
delta_dist_y = abs(1 / sin_a) if sin_a != 0 else 1e30
# Determine the step direction and initial side distance
if cos_a < 0:
step_x = -1
side_dist_x = (self.player.x - map_x) * delta_dist_x
else:
step_x = 1
side_dist_x = (map_x + 1.0 - self.player.x) * delta_dist_x
if sin_a < 0:
step_y = -1
side_dist_y = (self.player.y - map_y) * delta_dist_y
else:
step_y = 1
side_dist_y = (map_y + 1.0 - self.player.y) * delta_dist_y
# DDA Algorithm
hit = False
side = None
while not hit:
if side_dist_x < side_dist_y:
side_dist_x += delta_dist_x
map_x += step_x
side = 'vert'
else:
side_dist_y += delta_dist_y
map_y += step_y
side = 'hor'
# Check for map boundaries
if 0 <= map_x < len(self.map[0]) and 0 <= map_y < len(self.map):
if self.map[map_y][map_x] != 0:
hit = True
break
else:
# Out of bounds
return self.max_depth, None, 0.0
# Calculate distance to the wall
if side == 'vert':
perp_dist = (map_x - self.player.x + (1 - step_x) / 2) / cos_a
offset = self.player.y + perp_dist * sin_a
else:
perp_dist = (map_y - self.player.y + (1 - step_y) / 2) / sin_a
offset = self.player.x + perp_dist * cos_a
offset %= 1.0 # Get the fractional part for texture mapping
# Get wall type and corresponding texture
wall_type = self.map[map_y][map_x]
texture = self.textures.get(str(wall_type), self.textures['1'])
return perp_dist, texture, offset
def render_walls(self):
for i in range(self.num_rays):
angle = self.ray_angles[i]
sin_a = self.sines[i]
cos_a = self.cosines[i]
depth, texture, offset = self.cast_single_ray(angle, sin_a, cos_a)
# Correct the distance to remove the fish-eye effect
depth_corrected = depth * math.cos(self.player.angle - angle)
# Calculate wall height based on distance
proj_height = min(int(self.dist_proj_plane / (depth_corrected + 1e-5)), self.screen_height)
# Shading based on distance
shade = max(255 - int(depth_corrected * 12), 30)
if texture:
tex_width, tex_height = texture.get_size()
tex_x = int(offset * tex_width)
tex_x = min(tex_x, tex_width - 1)
# Create a column surface
wall_column = texture.subsurface(tex_x, 0, 1, tex_height).copy()
wall_column = pygame.transform.scale(wall_column, (1, proj_height))
# Apply shading
wall_column.fill((shade, shade, shade), special_flags=pygame.BLEND_MULT)
# Draw the wall column
self.screen.blit(wall_column, (i, self.screen_height // 2 - proj_height // 2))
else:
# Draw a solid color if texture is missing
pygame.draw.rect(
self.screen,
(shade, shade, shade),
(i, self.screen_height // 2 - proj_height // 2, 1, proj_height)
)
def render_floor_ceiling(self):
floor_texture = self.textures.get('floor')
ceiling_texture = self.textures.get('ceiling')
if floor_texture and ceiling_texture:
# Precompute the floor and ceiling projection
floor_height = self.screen_height // 2
ceiling_height = self.screen_height // 2
floor_step = self.player.move_speed / self.dist_proj_plane
ceiling_step = self.player.move_speed / self.dist_proj_plane
floor_x, floor_y = self.player.x, self.player.y
for y in range(ceiling_height, self.screen_height):
ray_dist = self.dist_proj_plane / y
floor_x_step = ray_dist * math.cos(self.player.angle)
floor_y_step = ray_dist * math.sin(self.player.angle)
floor_map_x = int(floor_x + floor_x_step)
floor_map_y = int(floor_y + floor_y_step)
if 0 <= floor_map_x < len(self.map[0]) and 0 <= floor_map_y < len(self.map):
floor_col = floor_texture.get_at((
int((floor_x_step % 1) * floor_texture.get_width()),
int((floor_y_step % 1) * floor_texture.get_height())
))
ceiling_col = ceiling_texture.get_at((
int((floor_x_step % 1) * ceiling_texture.get_width()),
int((floor_y_step % 1) * ceiling_texture.get_height())
))
self.screen.set_at((y, y), floor_col)
self.screen.set_at((y, self.screen_height - y), ceiling_col)
else:
# Draw solid colors if textures are missing
pygame.draw.rect(
self.screen,
(100, 100, 100),
(0, 0, self.screen_width, self.screen_height // 2)
) # Ceiling
pygame.draw.rect(
self.screen,
(70, 70, 70),
(0, self.screen_height // 2, self.screen_width, self.screen_height // 2)
) # Floor
def render(self):
# Clear screen with a black background
self.screen.fill((0, 0, 0))
# Render floor and ceiling
self.render_floor_ceiling()
# Render walls
self.render_walls()
# main.py
import pygame
import sys
import math
import numpy as np
from player import Player
from raycaster import Raycaster
from map import game_map
from typing import Dict
def load_texture(path: str, default_color: Tuple[int, int, int], size: Tuple[int, int]) -> pygame.Surface:
try:
texture = pygame.image.load(path).convert_alpha()
texture = pygame.transform.scale(texture, size)
except pygame.error:
print(f"Failed to load {path}. Using default color.")
texture = pygame.Surface(size)
texture.fill(default_color)
return texture
def load_textures() -> Dict[str, pygame.Surface]:
textures = {}
textures['1'] = load_texture('textures/wall1.png', (200, 0, 0), (64, 64))
textures['2'] = load_texture('textures/wall2.png', (0, 200, 0), (64, 64))
textures['3'] = load_texture('textures/wall3.png', (0, 0, 200), (64, 64))
textures['floor'] = load_texture('textures/floor.png', (50, 50, 50), (64, 64))
textures['ceiling'] = load_texture('textures/ceiling.png', (80, 80, 80), (64, 64))
return textures
def main():
pygame.init()
clock = pygame.time.Clock()
# Window parameters
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Raycasting Game - Professional Version")
# Hide cursor and capture mouse
pygame.event.set_grab(True)
pygame.mouse.set_visible(False)
# Load textures
textures = load_textures()
# Initialize player at a free space, e.g., (1.5, 1.5)
player = Player(x=1.5, y=1.5, angle=0.0)
# Validate initial position
if not player.is_walkable(player.x, player.y):
print("Error: Player's initial position is occupied by a wall.")
pygame.quit()
sys.exit()
# Initialize raycaster
raycaster = Raycaster(screen, player, textures)
# Main game loop
running = True
while running:
delta_time = clock.tick(60) / 1000.0 # Time since last frame in seconds
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
# Handle keyboard input
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
player.move('forward', delta_time)
if keys[pygame.K_s]:
player.move('backward', delta_time)
if keys[pygame.K_a]:
player.rotate('left', delta_time)
if keys[pygame.K_d]:
player.rotate('right', delta_time)
# Handle mouse movement for rotation
mouse_dx, _ = pygame.mouse.get_rel()
sensitivity = 0.002 # Mouse sensitivity
player.angle += mouse_dx * sensitivity
player.angle %= 2 * math.pi # Keep angle within [0, 2π]
# Update raycaster's ray angles if the player has rotated
raycaster.update_player_angle()
# Render the scene
raycaster.render()
# Update the display
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()