Files
python-maze/README.md
2025-11-20 23:38:31 -05:00

296 lines
7.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Maze Generator
A comprehensive Python-based maze generation and solving application featuring **8 different algorithms**, an interactive **Neo-Brutalism web interface**, and advanced analysis tools.
![License](https://img.shields.io/badge/license-MIT-blue)
![Python](https://img.shields.io/badge/python-3.11%2B-blue)
![Tests](https://img.shields.io/badge/coverage-90%2B%25-green)
## Features
### 🎨 8 Maze Generation Algorithms
- **Recursive Backtracking** - Depth-first search with backtracking
- **Kruskal's Algorithm** - Minimum spanning tree using union-find
- **Prim's Algorithm** - Greedy minimum spanning tree
- **Sidewinder Algorithm** - Row-by-row generation with horizontal bias
- **Hunt-and-Kill Algorithm** - Random walks with hunting phase
- **Eller's Algorithm** - Memory-efficient row-by-row generation
- **Wilson's Algorithm** - Loop-erased random walks (uniform spanning trees)
- **Aldous-Broder Algorithm** - Random walk-based generation
### 🔍 2 Solving Algorithms
- **Depth-First Search (DFS)** - Memory-efficient pathfinding
- **Breadth-First Search (BFS)** - Guaranteed shortest path
### 🎯 Interactive Web Interface
Built with **Neo-Brutalism** design aesthetics featuring:
- Bold, thick borders (6px)
- High contrast neon colors (yellow, pink, cyan, green)
- Hard drop shadows
- Chunky typography (Space Grotesk font)
- Asymmetric layouts
- **Animated solving** with pause/stop controls and adjustable speed
### 📊 Analysis Tools
- Dead end counting and percentage
- Longest path detection
- Branching factor calculation
- Algorithm performance benchmarking
### 🖼️ Visualization
- Real-time canvas rendering
- PNG image export
- Solution path highlighting
- Visited cell tracking
### 💾 Persistence
- Save/load mazes as JSON
- File management system
- Reproducible generation with seeds
## Installation
### Local Setup
1. **Clone the repository:**
```bash
git clone <repository-url>
cd mazer
```
2. **Create virtual environment:**
```bash
python -m venv venv
# Windows
venv\Scripts\activate
# Linux/Mac
source venv/bin/activate
```
3. **Install dependencies:**
```bash
pip install -r requirements.txt
```
4. **Run the application:**
```bash
python api/app.py
```
5. **Open your browser:**
Navigate to `http://localhost:5000`
### Docker Setup
1. **Build and run with Docker Compose:**
```bash
cd docker
docker-compose up --build
```
2. **Access the application:**
Navigate to `http://localhost:5000`
## Usage
### Web Interface
The web interface provides 9 main operations:
1. **Generate Maze** - Create a new maze with selected algorithm and dimensions
2. **Visualize** - Display the maze on canvas
3. **Download Image** - Save maze as PNG file
4. **Save to File** - Persist maze as JSON
5. **Load from File** - Restore saved maze
6. **Solve (DFS)** - Find path using Depth-First Search with animated visualization
7. **Solve (BFS)** - Find shortest path using Breadth-First Search with animated visualization
8. **Analyze** - Compute maze statistics and metrics
9. **Benchmark** - Compare algorithm performance
#### Animation Controls
When solving a maze, you can:
- **Pause/Resume** - Pause the animation and resume where you left off
- **Stop** - Stop the animation and show the final result
- **Adjust Speed** - Use the slider to control animation speed (slow to fast)
### API Endpoints
#### Generate Maze
```bash
POST /api/generate
Content-Type: application/json
{
"algorithm": "recursive_backtracking",
"rows": 15,
"cols": 15,
"seed": 42
}
```
#### Solve Maze
```bash
POST /api/solve
Content-Type: application/json
{
"maze_id": 0,
"algorithm": "bfs"
}
```
#### Analyze Maze
```bash
GET /api/analyze/<maze_id>
```
#### Download Maze Image
```bash
GET /api/download/<maze_id>?solution=true&solver=bfs&format=png
# Parameters:
# - solution: true/false (include solution path)
# - solver: dfs/bfs (which algorithm to use)
# - format: png/jpg (image format, defaults to png)
```
#### Benchmark Algorithms
```bash
POST /api/benchmark
Content-Type: application/json
{
"type": "quick"
}
```
### Python API
```python
from src.generators import RecursiveBacktrackingGenerator
from src.solvers import BFSSolver
from src.analysis.analyzer import MazeAnalyzer
# Generate a maze
generator = RecursiveBacktrackingGenerator()
maze = generator.generate(rows=20, cols=20, seed=42)
# Solve the maze
solver = BFSSolver()
solution = solver.solve(maze)
# Analyze the maze
analysis = MazeAnalyzer.analyze(maze)
print(f"Dead ends: {analysis['dead_ends']}")
print(f"Longest path: {analysis['longest_path_length']}")
```
## Testing
Run the test suite with coverage:
```bash
# Run all tests
pytest
# Run with coverage report
pytest --cov=src --cov-report=html
# Run specific test file
pytest tests/unit/test_maze.py
# Run specific test
pytest tests/unit/test_generators.py::TestGenerators::test_generator_creates_valid_maze
```
### Test Coverage
- Overall: >90%
- Core modules: >95%
- Generators: >90%
- Solvers: >90%
- API: >85%
## Project Structure
```
mazer/
├── src/ # Core application code
│ ├── core/ # Maze and Cell classes
│ ├── generators/ # 8 generation algorithms
│ ├── solvers/ # DFS and BFS solvers
│ ├── visualization/ # Image and web rendering
│ ├── analysis/ # Analysis and benchmarking
│ └── storage/ # File I/O operations
├── api/ # Flask web API
│ └── app.py # Main application
├── web/ # Frontend
│ ├── static/
│ │ ├── css/ # Neo-Brutalism styles
│ │ └── js/ # Interactive controls
│ └── templates/ # HTML templates
├── tests/ # Test suite
│ ├── unit/ # Unit tests
│ └── integration/ # Integration tests
├── docker/ # Docker configuration
├── requirements.txt # Python dependencies
└── README.md # This file
```
## Algorithm Complexity
| Algorithm | Time Complexity | Space Complexity | Characteristics |
|-----------|----------------|------------------|-----------------|
| Recursive Backtracking | O(n) | O(n) | Long winding paths |
| Kruskal's | O(E log E) | O(V) | Many short paths |
| Prim's | O(E log V) | O(V) | Short dead ends |
| Sidewinder | O(n) | O(cols) | Horizontal bias |
| Hunt-and-Kill | O(n²) | O(1) | Few dead ends |
| Eller's | O(n) | O(cols) | Memory efficient |
| Wilson's | O(n) expected | O(n) | Uniform spanning tree |
| Aldous-Broder | O(n log n) | O(1) | Uniform, slow |
## Performance Targets
- 5×5 maze: <10ms generation
- 25×25 maze: <100ms generation
- 50×50 maze: <1s generation
- API response time: <2s for all operations
## Technologies Used
- **Backend:** Python 3.11+
- **Web Framework:** Flask 3.0
- **Image Processing:** Pillow
- **Testing:** pytest, pytest-cov
- **Containerization:** Docker, Docker Compose
- **Frontend:** HTML5, CSS3, JavaScript
- **Design:** Neo-Brutalism aesthetic
## Contributing
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## License
This project is licensed under the MIT License.
## Acknowledgments
- Maze generation algorithms based on ["Mazes for Programmers" by Jamis Buck](http://www.mazesforprogrammers.com/)
- Neo-Brutalism design inspiration from [neobrutalism.dev](https://neobrutalism.dev/)
## Future Enhancements
- Additional solving algorithms (A*, Dijkstra)
- 3D maze support
- Multi-start/multi-end points
- Difficulty ratings
- WebSocket real-time updates
- Mobile app version