snakerun package

class snakerun.SnakeGame(test_mode=False)[source]

Bases: object

A terminal-based Snake game implemented using the curses library.

width

Width of the game area.

Type:

int

height

Height of the game area.

Type:

int

snake

Deque representing the snake’s body coordinates.

Type:

deque

direction

Current moving direction of the snake.

Type:

str

next_direction

Next direction input from the user.

Type:

str

food

Coordinates of the current food item.

Type:

tuple or None

score

Player’s current score.

Type:

int

game_over

Flag indicating if the game has ended.

Type:

bool

running

Flag indicating if the game loop is running.

Type:

bool

delay

Delay between snake moves in milliseconds.

Type:

int

stdscr

The main curses screen.

Type:

curses.window

game_win

Window displaying the game area.

Type:

curses.window

test_mode

Whether running in test mode (no curses initialization).

Type:

bool

check_collision(position)[source]

Check if a given position results in a collision.

Parameters:

position (tuple) – The (x, y) coordinates to check for collision.

Returns:

True if collision detected, False otherwise.

Return type:

bool

Collision detection includes: - Wall collision: position is at or beyond game area boundaries - Self collision: position overlaps with any part of snake body

The method checks boundaries against the playable area (excluding the border positions) and iterates through the snake deque to detect self-intersection.

cleanup()[source]

Clean up curses environment and restore terminal state.

Properly shuts down the curses interface by: - Disabling cbreak mode (restoring line buffering) - Re-enabling echo for normal terminal input - Restoring cursor visibility - Ending the curses session

This method is essential for leaving the terminal in a usable state after the game exits. Called automatically in the finally block of the run() method to ensure cleanup occurs even if the game exits unexpectedly.

draw_border()[source]

Draw the dark green border around the game area.

Creates a visual boundary for the playing field using curses border characters. The border is drawn in green with bold formatting to make it clearly visible and distinguish the game area from the surrounding terminal space.

draw_food()[source]

Draw the red food item on the game area.

Renders the food as a circular bullet character “●” in red color with bold formatting. Only draws the food if it exists (self.food is not None), positioning it at the stored coordinates within the game window.

draw_game_over()[source]

Draw the game over screen with final score and restart options.

Displays centered text on the game area including: - “GAME OVER!” message in yellow with bold formatting - Final score display in white - Restart/quit instructions in white

All text is centered both horizontally and vertically within the game window to create a clear, prominent game over screen that provides the player with their final score and next steps.

draw_instructions()[source]

Draw game control instructions to the right of the game area.

Displays a list of available controls and commands: - Movement controls (WASD or Arrow Keys) - Quit command (‘q’) - Restart command (‘r’)

Instructions are positioned to the right of the game border in white text, providing players with easily accessible reference for game controls.

draw_score()[source]

Draw the current score at the bottom right outside the game border.

Displays the score in the format “Score: X” positioned below and to the right of the game area. The text is right-aligned and rendered in white with bold formatting for visibility.

Position calculation accounts for: - Game window position and dimensions - Text length for proper alignment - Border spacing for clean layout

draw_snake()[source]

Draw the green snake on the game area.

Renders each segment of the snake using the block character “█” in green color with bold formatting. Iterates through all segments in the snake deque and draws them at their respective coordinates within the game window.

draw_welcome()[source]

Draw the welcome screen and wait for player input to start.

Displays the initial game screen with: - “SNAKE GAME” title in green with bold formatting - “Press any key to start!” instruction in white - Game border for visual context

The method temporarily disables non-blocking input to wait for a key press before starting the game, then re-enables non-blocking mode for gameplay. All text is centered within the game window for an attractive welcome presentation.

handle_input()[source]

Handle keyboard input in a separate thread for real-time control.

Runs continuously while the game is active, processing keyboard input without blocking the main game loop. Supports both WASD and arrow key controls with collision prevention (can’t reverse directly into snake body).

Supported controls: - W/Up Arrow: Move up (if not currently moving down) - S/Down Arrow: Move down (if not currently moving up) - A/Left Arrow: Move left (if not currently moving right) - D/Right Arrow: Move right (if not currently moving left) - Q: Quit game - R: Restart game (only when game over)

Input is case-insensitive. Includes small delay to prevent excessive CPU usage while maintaining responsiveness.

init_curses()[source]

Initialize the curses display and configure game window.

Sets up:
  • Main screen with proper input/output settings

  • Input and display options (no echo, non-blocking input)

  • Color pairs for snake, food, border, and text elements

  • Game window with borders and keypad support

  • Non-blocking input for real-time gameplay

Color pairs defined:

1: Green snake on default background 2: Red food on default background 3: Green border on default background 4: White text on default background 5: Yellow game over text on default background

init_snake()[source]

Initialize the snake at the center of the screen.

Creates a new snake with 3 segments positioned horizontally in the center of the game area. The snake starts facing right with the head at the center and two body segments trailing to the left. This provides a consistent starting state for each new game.

move_snake()[source]

Move the snake in the current direction and handle game logic.

Performs the core game movement logic: 1. Calculates new head position based on current direction 2. Checks for collisions with walls or snake body 3. Adds new head to snake 4. Handles food consumption (grows snake, increases score, spawns new food) 5. Removes tail segment if no food was eaten 6. Increases game speed slightly when food is consumed

Sets game_over flag to True if collision is detected. Updates score and respawns food when food is consumed. Implements speed increase mechanism for progressive difficulty.

restart_game()[source]

Reset the game to its initial state for a fresh start.

Clears all game state and reinitializes core components: - Clears snake body - Resets score to 0 - Sets direction back to RIGHT - Clears game over flag - Resets game speed to initial value - Reinitializes snake position - Spawns new food

This method is called when the player presses ‘R’ during the game over screen, allowing for immediate replay without restarting the entire program.

run()[source]

Main game execution method that runs the complete game loop.

Orchestrates the entire game flow:

  1. Shows welcome screen and waits for start

  2. Initializes snake and food

  3. Starts input handling thread for real-time controls

  4. Runs main game loop until quit/exit:
    • Updates snake direction from input

    • Moves snake (if game not over)

    • Updates display

    • Controls game speed with delay

  5. Handles cleanup on exit

Exception Handling:
  • Catches KeyboardInterrupt (Ctrl+C) for graceful exit.

  • Ensures proper curses cleanup in finally block.

The method uses threading for input handling to maintain responsive controls while managing game timing and display updates in the main thread.

spawn_food()[source]

Spawn food at a random empty location within the game area.

Continuously generates random coordinates within the playable area (excluding border positions) until finding a location that doesn’t overlap with any part of the snake’s body. This ensures food is always accessible and visible to the player.

The food coordinates are stored in self.food as a tuple (x, y).

update_display()[source]

Update the entire game display with current game state.

Performs a complete refresh of all visual elements: 1. Clears the game area (preserving border) 2. Draws game border 3. Draws snake at current position 4. Draws food at current position 5. Shows game over screen if applicable 6. Updates score display 7. Updates instruction display 8. Refreshes both main screen and game window

This method is called every game loop iteration to ensure the display accurately reflects the current game state. The clearing and redrawing approach prevents visual artifacts and ensures clean animation.

window_terminal_validity()[source]

Check if the current terminal size is sufficient for the game.

Validates that the terminal dimensions are large enough to display the game area plus borders and UI elements. The minimum required size accounts for the game area plus 4 additional characters for borders and spacing.

Raises:

Exception – If the terminal is smaller than required dimensions (height+4 x width+4). Includes current and required dimensions in the error message.