Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- import math
- # Initialize Pygame
- pygame.init()
- # Screen dimensions
- WIDTH, HEIGHT = 640, 480
- screen = pygame.display.set_mode((WIDTH, HEIGHT))
- # Map setup
- MAP = [
- "########",
- "#......#",
- "#.##...#",
- "#......#",
- "#..###.#",
- "#......#",
- "#......#",
- "########"
- ]
- MAP_WIDTH = len(MAP[0])
- MAP_HEIGHT = len(MAP)
- # Player setup
- player_x, player_y = 3.5, 3.5 # Start in the center of the map
- player_angle = 0
- FOV = math.pi / 3 # Field of view (60 degrees)
- MOVE_SPEED = 0.1
- ROTATE_SPEED = 0.05
- # Raycasting
- def cast_ray(angle):
- sin_a = math.sin(angle)
- cos_a = math.cos(angle)
- for depth in range(1, 20):
- target_x = player_x + depth * cos_a
- target_y = player_y + depth * sin_a
- if MAP[int(target_y)][int(target_x)] == '#':
- return depth, target_x, target_y
- return None, None, None
- # Main loop
- running = True
- while running:
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- running = False
- # Player movement
- keys = pygame.key.get_pressed()
- if keys[pygame.K_a]: # Rotate left
- player_angle -= ROTATE_SPEED
- if keys[pygame.K_d]: # Rotate right
- player_angle += ROTATE_SPEED
- if keys[pygame.K_w]: # Move forward
- new_x = player_x + math.cos(player_angle) * MOVE_SPEED
- new_y = player_y + math.sin(player_angle) * MOVE_SPEED
- if MAP[int(new_y)][int(new_x)] != '#': # Check for collision
- player_x, player_y = new_x, new_y
- if keys[pygame.K_s]: # Move backward
- new_x = player_x - math.cos(player_angle) * MOVE_SPEED
- new_y = player_y - math.sin(player_angle) * MOVE_SPEED
- if MAP[int(new_y)][int(new_x)] != '#': # Check for collision
- player_x, player_y = new_x, new_y
- # Drawing the scene
- screen.fill((0, 0, 0))
- for column in range(WIDTH):
- angle = player_angle - FOV / 2 + FOV * column / WIDTH
- depth, _, _ = cast_ray(angle)
- if depth:
- wall_height = HEIGHT / (depth * math.cos(angle - player_angle))
- color = 255 / (1 + depth * depth * 0.1)
- pygame.draw.rect(screen, (color, color, color),
- (column, HEIGHT // 2 - wall_height // 2, 1, wall_height))
- pygame.display.flip()
- pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement