write the code for a game like doom using pygame, implement a fast ray-casting algorithm, the game should be fully playable with a start menu and controls, score, etc. the aiming should be controlled using the keyboard with a 32 cm/360, the movement WASD, space jump, shift run.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is an example of a “Doom‐like” raycasting game built with Pygame. This single–file code implements a basic DDA-based raycaster, a start menu screen, a simple scoring system (increases with survival time), and player controls. (Note that “Doom” is a full–featured shooter, and this example is a simplified “Wolfenstein‐style” raycaster meant for learning purposes.)
To run this code you’ll need Python 3 and Pygame installed (e.g. via pip install pygame). Save the code into a file (for example, doom_game.py) and run it. Feel free to modify it further!
Below is the full code:
python
import pygame
import math
import sys
# -------------------- GAME SETTINGS --------------------
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# Field of view and ray settings:
FOV = math.radians(60) # 60° field of view
NUM_RAYS = SCREEN_WIDTH # one ray per vertical column (can be optimized)
HALF_FOV = FOV / 2
DELTA_ANGLE = FOV / NUM_RAYS
MAX_DEPTH = 20
# Player movement parameters
MOVE_SPEED = 3.0 # walking speed units per second
RUN_MULTIPLIER = 1.75 # shift multiplier
ROT_SPEED = math.radians(120) # radians per second rotation (aiming left/right)
JUMP_SPEED = 6.5 # jump initial upward speed
GRAVITY = 20.0 # gravity acceleration
# Colors
CEILING_COLOR = (100, 100, 100)
FLOOR_COLOR = (50, 50, 50)
WALL_COLOR = (200, 0, 0) # base wall color
WALL_SHADE = (0, 0, 0) # color to subtract for distance shading
# Map world: 1 = wall, 0 = empty space
game_map = [
"11111111111111111111",
"1........1.........1",
"1........1.........1",
"1..................1",
"1........11111.....1",
"1........1.........1",
"1.........1........1",
"1.........1........1",
"1..................1",
"1...111111111......1",
"1..................1",
"1.........1........1",
"1.........1........1",
"1........1.........1",
"11111111111111111111",
]
MAP_WIDTH = len(game_map[0])
MAP_HEIGHT = len(game_map)
TILE_SIZE = 1 # world unit per map cell
# -------------------- GAME CLASSES --------------------
class Player:
def __init__(self, x, y, angle=0.0):
self.x = x
self.y = y
self.angle = angle # view direction in radians
self.jump_velocity = 0.0
self.on_ground = True
self.camera_height = 0.5 # base camera height inside player
def update(self, dt, keys_pressed):
# Movement (WASD for forward/back/strafe). Rotation (Left/Right arrows)
sin_a = math.sin(self.angle)
cos_a = math.cos(self.angle)
# Determine movement speed – running or not
speed = MOVE_SPEED
if keys_pressed[pygame.K_LSHIFT] or keys_pressed[pygame.K_RSHIFT]:
speed *= RUN_MULTIPLIER
dx, dy = 0, 0
# W/S: forward/backward (based on view angle)
if keys_pressed[pygame.K_w]:
dx += cos_a * speed * dt
dy += sin_a * speed * dt
if keys_pressed[pygame.K_s]:
dx -= cos_a * speed * dt
dy -= sin_a * speed * dt
# A/D: strafe left/right
if keys_pressed[pygame.K_a]:
dx += sin_a * speed * dt
dy -= cos_a * speed * dt
if keys_pressed[pygame.K_d]:
dx -= sin_a * speed * dt
dy += cos_a * speed * dt
# Collision: check new position before moving
if not is_wall(self.x + dx, self.y):
self.x += dx
if not is_wall(self.x, self.y + dy):
self.y += dy
# Rotation: Left/Right arrow keys to rotate view
if keys_pressed[pygame.K_LEFT]:
self.angle -= ROT_SPEED * dt
if keys_pressed[pygame.K_RIGHT]:
self.angle += ROT_SPEED * dt
# Normalize angle
self.angle %= 2 * math.pi
# Jumping mechanics (space to jump)
if keys_pressed[pygame.K_SPACE] and self.on_ground:
self.jump_velocity = JUMP_SPEED
self.on_ground = False
# Handle vertical movement (jumping/falling)
if not self.on_ground:
self.jump_velocity -= GRAVITY * dt
# simulate landing when falling back down to a base of 0 height
# (we use a simple 1D jump; the camera height is offset by jump velocity)
if self.jump_velocity < -JUMP_SPEED:
self.jump_velocity = -JUMP_SPEED # clamp fall speed
# Once the “jump” comes back down, consider the player landed.
# Here we assume the “ground” is at vertical offset = 0.
# For simplicity, we use the jump velocity to compute an offset.
# In a more complex engine, you’d simulate vertical position.
# We just use jump_velocity != 0 for visual offset.
if self.jump_velocity <= 0 and abs(self.jump_velocity) < 0.1:
self.jump_velocity = 0.0
self.on_ground = True
def get_camera_offset(self):
"""Return vertical camera offset for jump effect (a number to add to wall projection)."""
# This offset is proportional to jump vertical speed.
# A negative jump_velocity represents an upward movement (jumping).
# For simplicity, use the jump_velocity itself (scaled) as an offset.
return -self.jump_velocity * 10 # tweak multiplier as needed
def is_wall(x, y):
# Check if the given floating-point position is inside a wall tile.
map_x = int(x)
map_y = int(y)
if map_x < 0 or map_x >= MAP_WIDTH or map_y < 0 or map_y >= MAP_HEIGHT:
return True # outside map boundaries counts as wall
return game_map[map_y][map_x] != '.' and game_map[map_y][map_x] != '0'
class RayCaster:
def __init__(self, screen, player):
self.screen = screen
self.player = player
def cast_rays(self):
"""Cast rays and draw vertical wall slices."""
# Clear ceiling and floor:
pygame.draw.rect(self.screen, CEILING_COLOR, (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT // 2))
pygame.draw.rect(self.screen, FLOOR_COLOR, (0, SCREEN_HEIGHT // 2, SCREEN_WIDTH, SCREEN_HEIGHT // 2))
# For each vertical column of the display, shoot a ray:
for ray in range(NUM_RAYS):
# Compute the angle of this ray relative to player's view:
ray_angle = (self.player.angle - HALF_FOV) + ray * DELTA_ANGLE
ray_angle %= 2 * math.pi
# Use DDA to find distance to the nearest wall:
distance, wall_hit = self._cast_single_ray(ray_angle)
# Remove fish-eye effect by multiplying by cos of angle offset:
angle_offset = self.player.angle - ray_angle
distance *= math.cos(angle_offset)
# Calculate projected wall height (simple projection formula):
if distance == 0:
distance = 0.0001
wall_height = min(int((TILE_SIZE / distance) * 277), SCREEN_HEIGHT)
# Compute vertical offset for jumping:
jump_offset = self.player.get_camera_offset()
# Calculate shading based on distance (closer walls are brighter)
shade = max(0, 255 - int(distance * 20)) # tweak shading effect
color = (shade, 0, 0)
# Draw a vertical slice (as a filled rectangle):
x = ray # one ray per column
start_y = (SCREEN_HEIGHT // 2) - (wall_height // 2) + int(jump_offset)
pygame.draw.line(self.screen, color, (x, start_y), (x, start_y + wall_height))
def _cast_single_ray(self, ray_angle):
"""
Cast a single ray using the DDA algorithm.
Returns (distance, hit_info).
"""
# Which box the player is in:
px, py = self.player.x, self.player.y
map_x = int(px)
map_y = int(py)
# Calculate the ray direction vector:
ray_dx = math.cos(ray_angle)
ray_dy = math.sin(ray_angle)
# Length of ray from current position to next x or y side:
if ray_dx == 0:
delta_dist_x = float('inf')
else:
delta_dist_x = abs(1 / ray_dx)
if ray_dy == 0:
delta_dist_y = float('inf')
else:
delta_dist_y = abs(1 / ray_dy)
# Calculate step direction and initial sideDist
if ray_dx < 0:
step_x = -1
side_dist_x = (px - map_x) * delta_dist_x
else:
step_x = 1
side_dist_x = (map_x + 1.0 - px) * delta_dist_x
if ray_dy < 0:
step_y = -1
side_dist_y = (py - map_y) * delta_dist_y
else:
step_y = 1
side_dist_y = (map_y + 1.0 - py) * delta_dist_y
hit = False
distance = 0.0
while not hit and distance < MAX_DEPTH:
# Jump to next map square, either in x-direction or y-direction:
if side_dist_x < side_dist_y:
map_x += step_x
distance = side_dist_x
side_dist_x += delta_dist_x
hit_side = 0 # vertical wall hit
else:
map_y += step_y
distance = side_dist_y
side_dist_y += delta_dist_y
hit_side = 1 # horizontal wall hit
# Check if the ray has hit a wall
if map_y < 0 or map_y >= MAP_HEIGHT or map_x < 0 or map_x >= MAP_WIDTH:
hit = True
distance = MAX_DEPTH
elif game_map[map_y][map_x] != '.' and game_map[map_y][map_x] != '0':
hit = True
return distance, (map_x, map_y)
# -------------------- UI FUNCTIONS --------------------
def draw_text(surface, text, pos, size=36, color=(255, 255, 255)):
font = pygame.font.SysFont("Arial", size)
text_surface = font.render(text, True, color)
surface.blit(text_surface, pos)
def show_start_menu(screen):
menu = True
clock = pygame.time.Clock()
while menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
# Any key press starts the game. (Enter can be used.)
menu = False
screen.fill((0, 0, 0))
draw_text(screen, "DOOM-LIKE RAYCASTER", (SCREEN_WIDTH//2 - 180, SCREEN_HEIGHT//2 - 50), 48)
draw_text(screen, "Press any key to start", (SCREEN_WIDTH//2 - 150, SCREEN_HEIGHT//2 + 10), 32)
draw_text(screen, "Movement: WASD | Turn: ← → | Run: Shift | Jump: Space", (SCREEN_WIDTH//2 - 320, SCREEN_HEIGHT//2 + 60), 24)
pygame.display.flip()
clock.tick(15)
def draw_minimap(screen, player):
"""Draw a small overhead map in the corner to show player position."""
mini_scale = 8
map_surface = pygame.Surface((MAP_WIDTH * mini_scale, MAP_HEIGHT * mini_scale))
map_surface.fill((20, 20, 20))
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
if game_map[y][x] != '.' and game_map[y][x] != '0':
pygame.draw.rect(map_surface, (200, 200, 200), (x * mini_scale, y * mini_scale, mini_scale, mini_scale))
# Draw player on minimap
px = player.x * mini_scale
py = player.y * mini_scale
pygame.draw.circle(map_surface, (0, 255, 0), (int(px), int(py)), 3)
# Draw view direction line
end_x = px + math.cos(player.angle) * 10
end_y = py + math.sin(player.angle) * 10
pygame.draw.line(map_surface, (0, 255, 0), (px, py), (end_x, end_y), 2)
screen.blit(map_surface, (10, 10))
# -------------------- MAIN GAME LOOP --------------------
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Doom-like Raycaster")
clock = pygame.time.Clock()
# Create the player. Start in the middle of an open space.
player = Player(3.5, 3.5, angle=0.0)
raycaster = RayCaster(screen, player)
# Show the start menu.
show_start_menu(screen)
# Score: simply count elapsed time in seconds.
score = 0
score_timer = 0
running = True
while running:
dt = clock.tick(60) / 1000.0 # Delta time in seconds (frame rate capped at 60 FPS)
score_timer += dt
score = int(score_timer * 10) # e.g. 10 points per second
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Process keys:
keys_pressed = pygame.key.get_pressed()
player.update(dt, keys_pressed)
# Draw everything (raycasted view):
raycaster.cast_rays()
# Optionally, draw the mini-map:
draw_minimap(screen, player)
# Draw score (upper right corner)
draw_text(screen, f"Score: {score}", (SCREEN_WIDTH - 180, 20), 30)
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Explanation
Map and World:
The game_map is an array of strings. In the strings a dot (.) represents empty space; any other character (here, '1') represents a wall.
Player Controls:
Movement: Use W (forward), S (backward), A (strafe left) and D (strafe right).
Rotation/Aiming: Use Left and Right arrow keys to rotate the player's view. (The turning speed is controlled by ROT_SPEED.)
Run and Jump: Hold Shift for a run multiplier and press Space to jump. The jump is simulated as a simple vertical offset.
Raycasting Engine:
The RayCaster class implements a DDA (Digital Differential Analyzer) algorithm to trace rays from the player's position into the map. For each vertical slice of the screen, the ray is cast, its distance is computed and then used to determine the height of the vertical slice drawn.
Start Menu and Score:
The game begins at a start menu screen. After pressing a key, the main game loop begins. The score increases proportionally to the time played.
Minimap:
A simple minimap in the upper left corner shows the player's position and viewing direction.
This code is intended as a starting point. You can enhance it by adding enemy sprites, textures, sound, and more sophisticated physics or collision handling. Enjoy coding!