This document provides comprehensive technical documentation for all classes, methods, and functions in the Infinite Maze codebase. This reference is intended for developers who want to understand, modify, or extend the game.
- Core Module (
infinite_maze.core) - Entities Module (
infinite_maze.entities) - Utils Module (
infinite_maze.utils) - Constants & Enums
The main game engine responsible for the game loop, input handling, and coordination between game components.
DO_NOTHING = 0
RIGHT = 1
LEFT = 2
UP = 3
DOWN = 4Movement direction constants used throughout the engine.
Primary game entry point and main game loop.
Description: Initializes the game components and runs the main gameplay loop. Handles all user input, game state management, collision detection, and rendering.
Usage:
from infinite_maze.core.engine import maze
maze() # Starts the gameGame Loop Flow:
- Initialize game, player, and maze components
- Process keyboard input (WASD/Arrow keys)
- Handle collision detection with maze walls
- Update game pace and position adjustments
- Render the game screen
- Control frame rate
- Handle game over and restart logic
Key Features:
- Real-time collision detection
- Progressive pace acceleration
- Pause/resume functionality
- Clean game state transitions
Alternative game loop for external control (AI/testing).
Parameters:
wrapper: External controller object withcontrol()andgameover()methodscounter: Iteration counter for external tracking
Description: Provides a controlled version of the main game loop where movement decisions can be made by external systems (AI agents, automated testing, etc.). Returns game state information to the controller and processes the controller's movement decisions.
Usage:
class AIController:
def control(self, values):
# Process game state and return movement decision
return movement_action
def gameover(self, final_score):
# Handle game over event
pass
ai = AIController()
controlled_run(ai, 0)State Information Provided:
- Current action being performed
- Whether score was increased this frame
- Distance to closest wall/obstacle
Central game state management class handling all game configuration, scoring, timing, and rendering coordination.
# Display configuration
WIDTH = 640 # Screen width in pixels
HEIGHT = 480 # Screen height in pixels
X_MIN = 80 # Left boundary for player movement
Y_MIN = 40 # Top boundary for player movement
X_MAX = WIDTH / 2 # Right boundary for player movement
Y_MAX = HEIGHT - 32 # Bottom boundary for player movement
# Gameplay configuration
SCORE_INCREMENT = 1 # Points awarded per rightward movement
# Visual configuration
BG_COLOR = pygame.Color(255, 255, 255) # Background color (white)
FG_COLOR = pygame.Color(0, 0, 0) # Foreground color (black)def __init__(self, headless=False)Parameters:
headless(bool): If True, runs without graphics for testing/AI (default: False)
Description: Initializes the game state, pygame systems, fonts, display, and game variables.
Example:
# Standard game initialization
game = Game()
# Headless mode for testing
test_game = Game(headless=True)Updates and renders the game screen.
Parameters:
player(Player): Player object to renderlines(List[Line]): List of maze line objects to render
Description: Handles all screen rendering including player sprite, maze walls, UI text, borders, and timing updates. Also manages pace acceleration triggers.
Features:
- Automatic pace acceleration every 30 seconds
- Pause state visual feedback
- Score and time display
- Border and boundary rendering
Renders the game over screen.
Description: Displays the final score and prompts user for restart decision.
def end() -> None # Trigger game over
def cleanup() -> None # Clean up pygame resources
def isActive() -> bool # Check if game is currently active
def quit() -> None # Quit the entire application
def isPlaying() -> bool # Check if game should continue running
def reset() -> None # Reset game state for new gamedef getClock() -> Clock # Get the game clock object
def getScreen() -> pygame.Surface # Get the game screen surface
def getScore() -> int # Get current score
def isPaused() -> bool # Check if game is paused
def getPace() -> int # Get current pace valuedef updateScore(amount: int) -> None # Add/subtract arbitrary amount
def incrementScore() -> None # Add standard score increment
def decrementScore() -> None # Subtract score (minimum 0)
def setScore(newScore: int) -> None # Set score to specific valuedef changePaused(player: Player) -> NoneDescription: Toggles pause state and updates visual elements (colors, player sprite) to reflect the current state.
Parameters:
player(Player): Player object to update sprite for
def setPace(newPace: int) -> NoneDescription: Manually set the game pace value.
Parameters:
newPace(int): New pace value
Game timing and frame rate management system.
def __init__(self)Description: Initializes the clock with pygame's built-in clock and timing variables.
Updates the clock and timing information.
Description: Called each frame to update current time, calculate deltas, and maintain timing state.
Resets all timing values to initial state.
Description: Used when starting a new game to ensure clean timing state.
def getTicks() -> int # Get total game ticks
def getMillis() -> int # Get current milliseconds
def getPrevMillis() -> int # Get previous frame milliseconds
def getSeconds() -> int # Get current seconds
def getPrevSeconds() -> int # Get previous frame seconds
def getTimeString() -> str # Get formatted time string (MM:SS)Rollback milliseconds for pause functionality.
Parameters:
amount(int): Milliseconds to subtract from current time
Description: Used during pause to prevent time advancement while maintaining accurate timing.
Player character representation and movement management.
def __init__(self, xPosition: int, yPosition: int, headless: bool = False)Parameters:
xPosition(int): Initial X coordinateyPosition(int): Initial Y coordinateheadless(bool): Whether to load graphics (default: False)
Description: Creates a player object with specified starting position. Loads player sprite or creates a simple shape if in headless mode.
Example:
# Create player at starting position
player = Player(80, 223)
# Create headless player for testing
test_player = Player(100, 200, headless=True)width = 10 # Player width in pixels
height = 10 # Player height in pixels
speed = 1 # Movement speed per framedef setX(xPosition: int) -> None # Set X coordinate
def setY(yPosition: int) -> None # Set Y coordinate
def getX() -> int # Get current X coordinate
def getY() -> int # Get current Y coordinate
def getPosition() -> Tuple[int, int] # Get (x, y) position tupledef moveX(units: int) -> None # Move horizontally
def moveY(units: int) -> None # Move verticallyParameters:
units(int): Distance to move (positive or negative)
Description: Movement is multiplied by the player's speed value. Positive X moves right, positive Y moves down.
Example:
player.moveX(1) # Move right by speed pixels
player.moveX(-1) # Move left by speed pixels
player.moveY(-1) # Move up by speed pixelsdef setCursor(image: str) -> None # Set player sprite image
def getCursor() -> pygame.Surface # Get current sprite surfacedef getSpeed() -> int # Get movement speed
def getWidth() -> int # Get player width
def getHeight() -> int # Get player height
def reset(xPosition: int, yPosition: int) -> None # Reset to new positionMaze generation and wall management system.
Represents individual wall segments in the maze.
def __init__(self, xStart: int, yStart: int, xEnd: int, yEnd: int)Parameters:
xStart, yStart(int): Starting coordinatesxEnd, yEnd(int): Ending coordinates
Description: Creates a line segment representing a wall. Can be horizontal or vertical.
def getXStart() -> int # Get starting X coordinate
def getYStart() -> int # Get starting Y coordinate
def getXEnd() -> int # Get ending X coordinate
def getYEnd() -> int # Get ending Y coordinate
def getStart() -> Tuple[int, int] # Get starting point tuple
def getEnd() -> Tuple[int, int] # Get ending point tupledef setXStart(x: int) -> None # Set starting X coordinate
def setYStart(y: int) -> None # Set starting Y coordinate
def setXEnd(x: int) -> None # Set ending X coordinate
def setYEnd(y: int) -> None # Set ending Y coordinatedef getIsHorizontal() -> bool # Check if line is horizontalReturns:
Trueif the line is horizontal (yStart == yEnd)Falseif the line is vertical
Generates a random maze layout.
Parameters:
game(Game): Game object for configurationrows(int): Number of maze rowscols(int): Number of maze columns
Returns:
List[Line]: List of line objects representing maze walls
Description: Creates a procedurally generated maze using random wall placement. Ensures the maze is navigable while providing appropriate challenge.
Example:
# Generate a 15x20 maze
lines = Line.generateMaze(game, 15, 20)Find the rightmost X coordinate among all lines.
Parameters:
lines(List[Line]): List of line objects
Returns:
int: Maximum X coordinate found
Description: Used for maze generation and line repositioning to maintain the infinite maze illusion.
Centralized configuration management system.
Central configuration class containing all game settings and constants.
SCREEN_WIDTH: int = 800 # Game window width
SCREEN_HEIGHT: int = 600 # Game window height
FPS: int = 60 # Target frames per secondPLAYER_START_X: int = 80 # Player starting X position
PLAYER_START_Y: int = 223 # Player starting Y position
PLAYER_SPEED: int = 5 # Player movement speed
PLAYER_WIDTH: int = 20 # Player width in pixels
PLAYER_HEIGHT: int = 20 # Player height in pixelsMAZE_ROWS: int = 15 # Default maze rows
MAZE_COLS: int = 20 # Default maze columnsCOLORS: Dict[str, Tuple[int, int, int]] = {
"BLACK": (0, 0, 0),
"WHITE": (255, 255, 255),
"RED": (255, 0, 0),
# ... more colors
}CONTROLS: Dict[str, Any] = {
"MOVE_RIGHT": ["RIGHT", "d"],
"MOVE_LEFT": ["LEFT", "a"],
"MOVE_UP": ["UP", "w"],
"MOVE_DOWN": ["DOWN", "s"],
"PAUSE": ["SPACE"],
"QUIT": ["ESCAPE", "q"],
"RESTART": ["r"],
}IMAGES: Dict[str, str] = {
"player": "assets/images/player.png",
"player_paused": "assets/images/player_paused.png",
"icon": "assets/images/icon.png",
}Get RGB color tuple by name.
Parameters:
color_name(str): Name of the color
Returns:
Tuple[int, int, int]: RGB color tuple
Example:
red = GameConfig.get_color("red") # Returns (255, 0, 0)
blue = GameConfig.get_color("blue") # Returns (0, 0, 255)Get full path for an image asset.
Parameters:
image_name(str): Name of the image
Returns:
str: Full path to the image file
Example:
player_img = GameConfig.get_image_path("player")
# Returns "assets/images/player.png"Build path relative to assets directory.
Parameters:
*path_parts(str): Path components to join
Returns:
str: Full asset path
Example:
sound_path = GameConfig.get_asset_path("sounds", "jump.wav")
# Returns "assets/sounds/jump.wav"Get movement constant by action name.
Parameters:
action(str): Action name
Returns:
int: Movement constant value
Example:
right_action = GameConfig.get_movement_constant("RIGHT") # Returns 1config = GameConfig()A default configuration instance available for import:
from infinite_maze.utils.config import config
player_speed = config.PLAYER_SPEEDCentralized logging system for debugging and monitoring.
Provides structured logging capabilities for the game.
def __init__(self, name: str = "infinite_maze", level: str = "INFO")Parameters:
name(str): Logger name (default: "infinite_maze")level(str): Logging level (default: "INFO")
def debug(message: str) -> None # Debug level messages
def info(message: str) -> None # Info level messages
def warning(message: str) -> None # Warning level messages
def error(message: str) -> None # Error level messages
def critical(message: str) -> None # Critical level messagesdef log_game_start() -> None # Log game initialization
def log_game_end(score: int) -> None # Log game completion
def log_player_movement(direction: str) -> None # Log player actions
def log_collision(details: str) -> None # Log collision events
def log_score_change(old: int, new: int) -> None # Log score updateslogger = GameLogger()Usage example:
from infinite_maze.utils.logger import logger
logger.info("Game started")
logger.debug(f"Player position: {player.getPosition()}")
logger.warning("Performance slow")DO_NOTHING = 0 # No movement action
RIGHT = 1 # Move right
LEFT = 2 # Move left
UP = 3 # Move up
DOWN = 4 # Move downACTIVE = "active" # Game is running
PAUSED = "paused" # Game is paused
GAME_OVER = "game_over" # Game has ended
QUIT = "quit" # Application should exitfrom infinite_maze import Game, Player, Line
# Create game components
game = Game()
player = Player(80, 223)
maze_lines = Line.generateMaze(game, 15, 20)
# Game loop would go here
while game.isPlaying():
# Handle input, update state, render
game.updateScreen(player, maze_lines)from infinite_maze.utils.config import GameConfig
# Create custom configuration
class CustomConfig(GameConfig):
PLAYER_SPEED = 10 # Faster player
SCREEN_WIDTH = 1024 # Larger screen
SCREEN_HEIGHT = 768
# Use custom config
config = CustomConfig()from infinite_maze import Game, Player
# Create headless game for testing
game = Game(headless=True)
player = Player(80, 223, headless=True)
# Test game logic without graphics
assert player.getX() == 80
player.moveX(5)
assert player.getX() == 85This API reference provides comprehensive documentation for extending and modifying the Infinite Maze game. For implementation examples and usage patterns, refer to the existing codebase and other documentation files.