Let’s go through the code, and explaining the each part:
pygame for game development and random for generating random numbers.import pygame import random |
# Constants SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600 ROWS, COLS = 30, 40 CELL_SIZE = min(SCREEN_WIDTH // COLS, SCREEN_HEIGHT // ROWS) WALL_WIDTH = 1 PLAYER_COLOR = (0, 255, 0) END_COLOR = (255, 255, 0) BACKGROUND_COLOR = (50, 50, 50) FONT_COLOR = (255, 255, 255) TIMER_BG_COLOR = (0, 0, 0) # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) |
MazeGame class responsible for managing the game.class MazeGame: def __init__(self): pygame.init() self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption(“Maze Game”) self.clock = pygame.time.Clock() self.font = pygame.font.SysFont(None, 36) self.state = “start” self.maze = None self.player = None self.end = None self.start_time = 0 |
generate_maze method within the MazeGame class to create a maze using a recursive backtracking algorithm.def generate_maze(self): maze = [[True] * COLS for _ in range(ROWS)] def backtrack(row, col): directions = [(0, –2), (0, 2), (-2, 0), (2, 0)] random.shuffle(directions) for dr, dc in directions: r, c = row + dr, col + dc if 0 <= r < ROWS and 0 <= c < COLS and maze[r][c]: maze[row + dr // 2][col + dc // 2] = False maze[r][c] = False backtrack(r, c) maze[0][0] = False backtrack(0, 0) return maze |
create_entity method to create player and end point entities with specified color, position, and scale.def create_entity(self, color, pos, scale): entity_rect = pygame.Rect(pos[1] * CELL_SIZE, pos[0] * CELL_SIZE, CELL_SIZE * scale, CELL_SIZE * scale) return { ‘color’: color, ‘rect’: entity_rect, ‘pos’: pos } |
move_entity method to move the player entity based on keyboard inputs (arrow keys).def move_entity(self, entity, direction): new_pos = (entity[‘pos’][0] + direction[0], entity[‘pos’][1] + direction[1]) new_rect = pygame.Rect(new_pos[1] * CELL_SIZE, new_pos[0] * CELL_SIZE, entity[‘rect’].width, entity[‘rect’].height) if 0 <= new_pos[0] < ROWS and 0 <= new_pos[1] < COLS and not self.maze[new_pos[0]][new_pos[1]]: entity[‘pos’] = new_pos entity[‘rect’] = new_rect |