# Mice!

Mice! is a strategic game where players must kill rats with bombs before they reproduce and become too numerous. The game is a clone of the classic game Rats! for Windows 95.

## Compatibility
*It's developed in Python 3.11, please use it*

## Features

- **Maze Generation**: Randomly generated mazes using Depth First Search (DFS) algorithm.
- **Units**: Different types of units such as rats, bombs, and points with specific behaviors.
- **Graphics**: Custom graphics for maze tiles, units, and effects.
- **Sound Effects**: Audio feedback for various game events.
- **Scoring**: Points system to track player progress.

## Engine Architecture

The Mice! game engine is built on a modular architecture designed for flexibility and maintainability. The engine follows a component-based design pattern where different systems handle specific aspects of the game.

### Core Engine Components

#### 1. **Rendering System** (`engine/sdl2.py`)
- **GameWindow Class**: Central rendering manager using SDL2
- **Features**:
  - Hardware-accelerated rendering via SDL2
  - Texture management and caching
  - Sprite rendering with transparency support
  - Text rendering with custom fonts
  - Resolution-independent scaling
  - Fullscreen/windowed mode switching
- **Implementation**:
  - Uses SDL2 renderer for efficient GPU-accelerated drawing
  - Implements double buffering for smooth animation
  - Manages texture atlas for optimized memory usage
  - Handles viewport transformations for different screen resolutions

#### 2. **Input System** (`engine/controls.py`)
- **KeyBindings Class**: Handles all user input
- **Features**:
  - Keyboard input mapping and handling
  - Joystick/gamepad support
  - Configurable key bindings
  - Input state management
- **Implementation**:
  - Event-driven input processing
  - Key state buffering for smooth movement
  - Support for multiple input devices simultaneously
  - Customizable control schemes

#### 3. **Map System** (`engine/maze.py`)
- **Map Class**: Manages the game world structure
- **Features**:
  - Maze data loading and parsing
  - Collision detection system
  - Tile-based world representation
  - Pathfinding support for AI units
- **Implementation**:
  - Grid-based coordinate system
  - Efficient collision detection using spatial partitioning
  - Support for different tile types (walls, floors, special tiles)
  - Integration with maze generation algorithms

#### 4. **Audio System**
- **Sound Management**: Handles all audio playback
- **Features**:
  - Sound effect playback
  - Background music support
  - Volume control
  - Multiple audio channels
- **Implementation**:
  - Uses subprocess module for audio playback
  - Asynchronous sound loading and playing
  - Audio file format support (WAV, MP3, OGG)

### Game Loop Architecture

The main game loop follows the standard pattern:
1. **Input Processing**: Capture and process user input
2. **Update Phase**: Update game state, unit logic, and physics
3. **Render Phase**: Draw all game objects to the screen
4. **Timing Control**: Maintain consistent frame rate

```
Input → Update → Render → Present → Repeat
```

## Units Implementation

The game uses an object-oriented approach for all game entities. Each unit type inherits from a base unit class and implements specific behaviors.

### Base Unit Architecture

All units share common properties and methods:
- **Position and Movement**: 2D coordinates with movement capabilities
- **Unique Identification**: UUID-based unique identifiers
- **Collision Detection**: Bounding box collision system
- **State Management**: Current state tracking (alive, dead, exploding, etc.)
- **Rendering**: Sprite-based visual representation

### Unit Types Implementation

#### 1. **Rat Units** (`units/rat.py`)

**Base Rat Class**:
- **AI Behavior**: Implements pathfinding using A* algorithm
- **Movement**: Grid-based movement with smooth interpolation
- **State Machine**: Multiple states (wandering, fleeing, reproducing)

**Male Rat Class**:
- **Reproduction Logic**: Seeks female rats for mating
- **Territorial Behavior**: Defends territory from other males
- **Lifespan Management**: Age-based death system

**Female Rat Class**:
- **Pregnancy System**: Gestation period simulation
- **Offspring Generation**: Creates new rat units
- **Maternal Behavior**: Protects offspring from threats

**Implementation Details**:
```python
# Simplified rat behavior structure
class Rat:
    def update(self):
        self.process_ai()      # Decision making
        self.handle_movement() # Position updates
        self.check_collisions() # Collision detection
        self.update_state()    # State transitions
```

#### 2. **Bomb Units** (`units/bomb.py`)

**Bomb Class**:
- **Timer System**: Countdown mechanism before explosion
- **Placement Logic**: Player-controlled positioning
- **Damage Calculation**: Blast radius and damage computation

**Explosion Class**:
- **Visual Effects**: Animated explosion graphics
- **Damage Dealing**: Affects units within blast radius
- **Temporary Entity**: Self-destructs after animation

**Implementation Details**:
- **State Machine**: Armed → Countdown → Exploding → Cleanup
- **Collision System**: Different collision behaviors per state
- **Effect Propagation**: Chain reaction support for multiple bombs

#### 3. **Point Units** (`units/points.py`)

**Point Class**:
- **Collection Mechanics**: Player interaction system
- **Value System**: Different point values for different achievements
- **Visual Feedback**: Pickup animations and effects

### Unit Interaction System

Units interact through a centralized collision and event system:

1. **Collision Detection**: 
   - Grid-based broad phase for efficiency
   - Precise bounding box narrow phase
   - Custom collision responses per unit type pair

2. **Event System**:
   - Unit death events
   - Reproduction events
   - Explosion events
   - Point collection events

3. **AI Communication**:
   - Shared pathfinding data
   - Pheromone trail system for rat behavior
   - Danger awareness (bombs, explosions)

## Technical Details

- **Language**: Python 3.11
- **Libraries**: 
    - `sdl2` for graphics and window management
    - `Pillow` for image processing
    - `uuid` for unique unit identification
    - `subprocess` for playing sound effects
    - `tkinter` for maze generation visualization
- **Performance Optimizations**:
    - Spatial partitioning for collision detection
    - Texture atlasing for reduced memory usage
    - Object pooling for frequently created/destroyed units
    - Delta time-based updates for frame rate independence
- **Memory Management**:
    - Automatic cleanup of dead units
    - Texture caching and reuse
    - Efficient data structures for large numbers of units

## Environment Variables

- `SDL_VIDEODRIVER`: Set the video driver (x11, wayland, etc.)
- `RESOLUTION`: Set the screen resolution (format: WIDTHxHEIGHT)
- `FULLSCREEN`: Enable/disable fullscreen mode (true/false)
- `SOUND_ENABLED`: Enable/disable sound effects (true/false)

## Installation

1. **Clone the repository**:
        ```bash
        git clone https://github.com/yourusername/mice-maze-game.git
        cd mice-maze-game
        ```
2. **Create a virtual environment**:
        ```bash
        python3 -m venv venv
        source venv/bin/activate
        ```
3. **Install the dependencies**:
        ```bash
        pip install -r requirements.txt
        ```
4. **Run the game**:
        ```bash
        python rats.py
        ```

## Project Structure

```
mice/
├── engine/                 # Core engine components
│   ├── controls.py        # Input handling system
│   ├── maze.py           # Map and collision system
│   └── sdl2.py           # Rendering and window management
├── units/                 # Game entity implementations
│   ├── bomb.py           # Bomb and explosion logic
│   ├── rat.py            # Rat AI and behavior
│   └── points.py         # Collectible points
├── assets/               # Game resources
│   ├── images/           # Sprites and textures
│   └── fonts/            # Text rendering fonts
├── sound/                # Audio files
├── maze.py              # Maze generation algorithms
├── rats.py              # Main game entry point
├── requirements.txt     # Python dependencies
├── .env                 # Environment configuration
└── README.md           # This documentation
```

## Game Files Details

- `maze.py`: Contains the `MazeGenerator` class implementing DFS algorithm for procedural maze generation
- `rats.py`: Main game controller, initializes engine systems and manages game state
- `engine/controls.py`: Input abstraction layer with configurable key bindings
- `engine/maze.py`: World representation with collision detection and pathfinding support
- `engine/sdl2.py`: Low-level graphics interface wrapping SDL2 functionality
- `units/bomb.py`: Explosive units with timer mechanics and blast radius calculations
- `units/rat.py`: AI-driven entities with reproduction, pathfinding, and survival behaviors
- `units/points.py`: Collectible scoring items with visual feedback systems
- `assets/`: Game resources including sprites, textures, and fonts
- `sound/`: Audio assets for game events and feedback
- `scores.txt`: Persistent high score storage
- `.env`: Runtime configuration and environment settings
- `.gitignore`: Version control exclusion rules

