A sophisticated Python game where two AI-controlled snakes compete against each other in real-time. This project showcases advanced AI concepts, clean software architecture, and sophisticated game development techniques with multiple AI strategies, intelligent pathfinding algorithms, and polished user interface.
- Project Overview
- Core Architecture
- Key Features
- AI Strategies
- Technical Quality
- Installation
- Usage
- Project Structure
- Game Mechanics
- Configuration
- Extending the Game
- Contributing
AI Snake Battle is a production-quality game that demonstrates excellent software engineering practices combined with advanced AI concepts. Two AI-controlled snakes compete in a grid-based arena using intelligent pathfinding algorithms and strategic decision-making. The game features a modular architecture with well-separated concerns, comprehensive error handling, and performance optimizations.
- Multiple AI Personalities: Three distinct AI strategies with unique behaviors
- Advanced Pathfinding: BFS algorithm with intelligent obstacle avoidance
- Production Code Quality: Type hints, comprehensive documentation, robust error handling
- Real-time Competition: Dynamic AI adaptation based on game state
- Performance Optimized: Cached rendering, FPS monitoring, efficient algorithms
- User-Friendly Interface: Interactive menu system and polished visuals
The project follows a clean modular architecture with well-separated concerns:
main.py- Entry point with comprehensive error handling and game lifecycle managementconfig.py- Centralized configuration for all game settingsenums.py- Direction enumeration for snake movement
game_state.py- Core game state manager handling snakes, food, collisions, and win conditionsai_controller.py- Abstract base class for AI decision making with safety mechanismsai_strategies.py- Three distinct AI implementations (Balanced, Aggressive, Defensive)
snake.py- Snake entity with movement, collision detection, and statistics tracking
renderer.py- Comprehensive rendering system with performance optimizationsmenu.py- Interactive AI selection menu with smooth navigation
pathfinding.py- Advanced pathfinding algorithms (BFS, A*) with obstacle detection
Three distinct AI personalities with unique decision-making patterns:
- Balanced AI: Equilibrium between aggression and safety
- Aggressive AI: Prioritizes blocking opponents and risk-taking
- Defensive AI: Focuses on survival and careful play
- BFS (Breadth-First Search) algorithm guaranteeing shortest paths
- A* pathfinding for complex scenarios
- Intelligent obstacle avoidance
- Dynamic path recalculation
- Multi-type collision detection (walls, self, snake-to-snake)
- Dynamic food generation with validation
- Real-time scoring and statistics tracking
- Graceful win/tie condition handling
- Performance monitoring and optimization
- Extensive logging system for debugging and monitoring
- Graceful error recovery at multiple levels
- Validation and safety checks throughout
- Fallback mechanisms for critical operations
- Cached surfaces for improved performance
- FPS monitoring and display
- Smooth animations and visual effects
- Efficient draw calls and memory management
The codebase demonstrates excellent software engineering practices:
- Type Hints: Throughout codebase for better maintainability and IDE support
- Comprehensive Documentation: Detailed docstrings explaining functionality and usage
- Modular Design: Clear separation of concerns with well-defined interfaces
- Error Handling: Multiple levels of error recovery with graceful degradation
- Logging System: Comprehensive logging for debugging and monitoring
- Configuration Management: Centralized settings for easy customization
- Performance Optimization: Caching, efficient algorithms, and resource management
The game features three sophisticated AI strategies, each with unique decision-making patterns and behavioral characteristics:
All AI strategies use BFS for pathfinding, which guarantees finding the shortest path to the food when one exists.
- Graph Representation: The game grid is treated as a graph where each cell is a node
- Queue-based Exploration: Starting from the snake's head, BFS explores all neighboring cells level by level
- Obstacle Avoidance: The algorithm marks cells containing snake bodies as obstacles
- Path Reconstruction: Once food is found, the algorithm reconstructs the path from head to food
def bfs_pathfind(start, target, obstacles):
queue = [(start, [])]
visited = {start}
while queue:
current, path = queue.pop(0)
for neighbor in get_neighbors(current):
if neighbor == target:
return path + [neighbor]
if neighbor not in visited and neighbor not in obstacles:
visited.add(neighbor)
queue.append((neighbor, path + [neighbor]))
return [] # No path foundEach AI makes decisions following a priority hierarchy:
- Path to Food: If a clear path exists, follow it
- Competitive Analysis: Consider opponent's position and strategy
- Strategic Movement: Execute strategy-specific behaviors
- Survival Mode: If no safe food path exists, find any safe direction
- Philosophy: Equilibrium between aggression and safety
- Decision Priority:
- Follow safe path to food if available
- Avoid opponent if they're closer to food
- Move toward food directly if safe
- Take any safe direction if no food path
- Risk Assessment: Takes moderate risks for food acquisition
- Competitive Behavior: Considers opponent's position when making decisions
- Philosophy: Prioritizes blocking opponents and risk-taking
- Decision Priority:
- Block opponent's path to food when possible
- Take direct path to food if available
- Move aggressively toward food even without clear path
- Avoid head-on collisions as last resort
- Risk Assessment: Willing to take high risks for competitive advantage
- Competitive Behavior: Actively tries to cut off opponent's path to food
- Philosophy: Prioritizes survival and avoiding risks
- Decision Priority:
- Ensure multiple escape routes
- Maintain distance from walls and opponent
- Only pursue food with safe, verified paths
- Choose positions with maximum safety score
- Risk Assessment: Prefers positions with multiple escape routes
- Competitive Behavior: Maintains distance from opponent and walls
-
Food Racing
- Calculates Manhattan distance to food
- Compares distance with opponent
- Chooses optimal path when winning the race
-
Blocking Strategy
- When opponent is closer to food (within 3-5 cells)
- Attempts to cut off opponent's path
- Falls back to safe movement if blocking fails
-
Survival Instinct
- Prioritizes avoiding immediate death
- Checks all directions for safe moves
- Avoids walls and snake bodies (including own tail)
-
Opportunistic Movement
- Even without clear path, moves toward food
- Takes calculated risks when necessary
- Adapts strategy based on game state
The project uses minimal, well-established dependencies:
pygame>=2.1.0- Game framework and graphics librarypathfinding>=1.0.1- Advanced pathfinding algorithmsnumpy>=1.21.0- Numerical computations and array operationstyping-extensions>=4.0.0- Enhanced type hints for better code quality
- Python 3.7 or higher
- pip (Python package installer)
-
Clone the Repository
git clone https://github.com/yourusername/ai-snake-battle.git cd ai-snake-battle -
Create Virtual Environment (Recommended)
python -m venv venv # On Windows venv\Scripts\activate # On macOS/Linux source venv/bin/activate
-
Install Dependencies
pip install -r requirements.txt
Navigate to the project directory and run:
python main.pyWhen you start the game, you'll see an AI selection menu:
- Choose an AI strategy for the Orange snake (Balanced, Aggressive, or Defensive)
- Press ENTER to confirm
- Choose an AI strategy for the Cyan snake
- Press ENTER to start the game
- Arrow Keys: Navigate the AI selection menu
- ENTER: Confirm selection
- R: Restart the game (returns to AI selection menu)
- Q: Quit the game
- Window Close: Exit the game
- Menu Phase: Interactive AI strategy selection for both snakes
- Game Phase: Real-time AI battle with pathfinding and collision detection
- Results Phase: Winner determination with comprehensive statistics
- Restart: Return to menu for new AI combinations
The game runs automatically once AI strategies are selected. You can:
- Observe different AI strategies competing against each other
- Monitor scores and statistics in the UI panel
- Watch for interesting emergent behaviors and strategy interactions
- Analyze which strategies perform better in different scenarios
- Observe the sophisticated pathfinding and decision-making in real-time
AI_Snake_Battle_Game/
│
├── main.py # Entry point and game loop
├── config.py # Game configuration and constants
├── enums.py # Direction enumeration
│
├── models/
│ ├── __init__.py
│ └── snake.py # Snake class and collision logic
│
├── game/
│ ├── __init__.py
│ ├── game_state.py # Game state management
│ └── ai_controller.py # AI decision making
│
├── ui/
│ ├── __init__.py
│ └── renderer.py # Game rendering and UI
│
└── utils/
├── __init__.py
└── pathfinding.py # BFS and pathfinding utilities
main.py: Entry point with comprehensive error handling and game lifecycle managementconfig.py: Centralized configuration for all game settingsenums.py: Direction enumeration for snake movementmodels/snake.py: Snake entity with movement, collision detection, and statistics trackinggame/game_state.py: Core game state manager handling snakes, food, collisions, and win conditionsgame/ai_controller.py: Abstract base class for AI decision making with safety mechanismsgame/ai_strategies.py: Three distinct AI implementations (Balanced, Aggressive, Defensive)ui/renderer.py: Comprehensive rendering system with performance optimizationsui/menu.py: Interactive AI selection menu with smooth navigationutils/pathfinding.py: Advanced pathfinding algorithms (BFS, A*) with obstacle detection
- Food Consumption: +10 points
- Length: Increases by 1 segment per food
- Winner: Highest score when game ends
- Wall Collision: Snake dies
- Self Collision: Snake dies (hitting own body)
- Head-to-Head: Both snakes die
- Head-to-Body: Attacking snake dies
- Single Survivor: Last snake alive wins
- Both Dead: Higher score wins
- Tie: Equal scores result in a tie
- Size: 40x30 cells (800x600 pixels)
- Cell Size: 20x20 pixels
- UI Height: 100 pixels (separate from game area)
Edit config.py to customize:
# Game Speed
FPS = 20 # Increase for faster game
# Window Dimensions
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 700
# Colors (RGB)
ORANGE = (255, 165, 0)
CYAN = (0, 255, 255)
# Scoring
FOOD_SCORE = 10-
Increase Challenge:
- Increase FPS for faster gameplay
- Reduce grid size for tighter space
- Add more sophisticated blocking algorithms
-
Modify AI Behavior:
- Adjust blocking distance threshold
- Change path preference calculations
- Add randomness for unpredictability
-
Power-ups
class PowerUp: def __init__(self, type, position): self.type = type # speed, invincibility, etc. self.position = position
-
Multiple AI Strategies
class AggressiveAI(AIController): # Prioritize blocking over food class DefensiveAI(AIController): # Prioritize survival over scoring
-
Obstacles
- Add static obstacles to the grid
- Create moving obstacles
- Implement destructible barriers
- Spatial Hashing: For faster collision detection
- A Pathfinding*: For more efficient pathfinding
- Caching: Store calculated paths for reuse
Contributions are welcome! Please feel free to submit a Pull Request. For major changes:
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- Additional AI strategies
- Performance optimizations
- New game modes
- Visual enhancements
- Documentation improvements
- Built with Pygame
- Inspired by classic Snake games
- BFS algorithm implementation based on graph theory principles
Enjoy watching the AI snakes battle!