Skip to content

kigster/gomoku.py

Repository files navigation

Gomoku — Python Version

logo

A modern implementation of the classic Gomoku (Five in a Row) board game featuring:

  • 🐍 Python 3.13+ Backend with FastAPI and advanced AI
  • ⚛️ React TypeScript Frontend with smooth animations
  • 🤖 Intelligent AI Player using minimax with alpha-beta pruning
  • 🎨 Modern UI/UX with futuristic styling and responsive design
  • Real-time Gameplay with session management and live updates
  • 🧪 Comprehensive Testing with pytest and full coverage

About Gomoku

Gomoku is a strategic board game traditionally played on a 15×15 or 19×19 grid. Players alternate placing black and white stones, with the objective of being the first to create an unbroken line of five stones horizontally, vertically, or diagonally.

Game Rules:

  • Black always moves first
  • Players alternate turns placing stones
  • First player to get 5 stones in a row wins
  • Game ends in a draw if the board fills up

Quick Start

Prerequisites

  • Python 3.13+ with uv package manager
  • Node.js 18+ with npm
  • Make (for development automation)

Installation

  1. Clone the repository:

    git clone https://github.com/kigster/gomoku-py.git
    cd gomoku-py
  2. Install dependencies:

    make install          # Install Python dependencies
    make install-frontend # Install React dependencies
  3. Start the development servers:

    make dev              # Start both backend and frontend

    Or start them separately:

    make dev-backend      # Backend only (http://localhost:8000)
    make dev-frontend     # Frontend only (http://localhost:3000)
  4. Open your browser:

How to Play

  1. Start a New Game: The application automatically creates a new game session
  2. Choose Your Color: Select whether you want to play as Black (first move) or White
  3. Make Your Move: Click on any empty cell on the board to place your stone
  4. AI Response: The AI will automatically make its move (watch the thinking indicator!)
  5. Win Condition: Get 5 stones in a row (horizontal, vertical, or diagonal) to win

Game Features

  • Real-time AI Thinking: See how many positions per second the AI evaluates
  • Move Timers: Track time spent by each player
  • Move History: Review all moves with timestamps and evaluation metrics
  • Responsive Design: Play on desktop, tablet, or mobile
  • Smooth Animations: Enjoy fluid stone placement and board interactions

AI Implementation

The AI uses a sophisticated minimax algorithm with alpha-beta pruning:

  • Pattern Recognition: Evaluates threats, open lines, and defensive positions
  • Move Ordering: Prioritizes promising moves for better pruning efficiency
  • Timeout Management: Configurable time limits with graceful degradation
  • Performance Optimization:
    • Only evaluates "interesting" moves near existing stones
    • Caches position evaluations
    • Uses NumPy for efficient board operations

AI Difficulty Levels:

  • Easy: Depth 2-3 (fast, beginner-friendly)
  • Medium: Depth 4-5 (balanced challenge)
  • Hard: Depth 6+ (strong tactical play)

Development

Available Commands

# Development
make dev              # Start both backend and frontend
make dev-backend      # Start backend only
make dev-frontend     # Start frontend only

# Dependencies
make install          # Install Python dependencies
make install-dev      # Install Python dev dependencies
make install-frontend # Install frontend dependencies

# Code Quality
make test             # Run all tests
make test-backend     # Run backend tests only
make lint             # Run linting (ruff, mypy)
make format           # Format code (black, isort)

# Utilities
make clean            # Clean build artifacts
make build            # Build for production
make help             # Show all available commands

Testing

The project includes comprehensive tests:

make test-backend     # Run backend tests with pytest
cd frontend && npm test  # Run frontend tests with Jest

Test Coverage:

  • ✅ Board logic and game rules
  • ✅ AI minimax algorithm
  • ✅ API endpoints and error handling
  • ✅ Session management
  • ✅ Move validation and game state

Code Quality

  • Linting: Ruff for fast Python linting
  • Type Checking: MyPy for static type analysis
  • Formatting: Black + isort for consistent code style
  • Standards: Python 3.13+ features, modern async/await patterns

Architecture

Backend (Python + FastAPI)

  • FastAPI: Modern, fast web framework with automatic OpenAPI docs
  • Pydantic: Data validation and serialization with type hints
  • NumPy: Efficient numerical operations for board state
  • Session Management: In-memory sessions with cleanup and timeout handling
  • RESTful API: Clean endpoints for game creation, moves, and status

Frontend (React + TypeScript)

  • React 18: Modern functional components with hooks
  • TypeScript: Type-safe development with excellent IDE support
  • Styled Components: CSS-in-JS for component-scoped styling
  • Framer Motion: Smooth animations and transitions
  • Axios: HTTP client with interceptors and error handling

Key Design Patterns

  • Repository Pattern: Clean separation of data access
  • Strategy Pattern: Pluggable AI algorithms
  • Observer Pattern: Real-time game state updates
  • Factory Pattern: Session and game creation
  • Command Pattern: Move execution and validation

Performance

AI Performance Metrics:

  • Positions/Second: 10K-100K+ depending on search depth
  • Response Time: < 5 seconds for most moves (configurable timeout)
  • Memory Usage: Efficient board representation with NumPy arrays
  • Scalability: Multiple concurrent game sessions supported

Frontend Performance:

  • Initial Load: < 2 seconds on modern devices
  • Move Response: < 100ms for user interactions
  • Animation: 60 FPS smooth stone placement and board effects
  • Bundle Size: Optimized with code splitting and tree shaking

Research & References

This implementation draws from academic research and existing implementations:

Research Papers (in /doc/)

  • Allis 1994: "Go-Moku and Threat-Space Search" - threat detection algorithms
  • Wagner et al. 2001: "Solving Renju" - advanced minimax techniques
  • Stanford AI: "AI Agent for Playing Gomoku" - evaluation functions

Related Implementations

Contributing

Contributions are welcome! Please feel free to submit issues, feature requests, or pull requests.

Development Setup

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes and add tests
  4. Run the test suite: make test
  5. Commit with clear messages: git commit -m "Add amazing feature"
  6. Push to your fork: git push origin feature/amazing-feature
  7. Submit a pull request

Code Style

  • Follow existing code patterns and conventions
  • Add type hints for all new Python code
  • Include tests for new functionality
  • Update documentation as needed

License

MIT License - see LICENSE for details.

Acknowledgments

  • Classic Gomoku game rules and strategy
  • Academic research in game AI and minimax algorithms
  • Open source community for excellent tools and libraries
  • The original C implementation that inspired this Python version

Happy Gaming! Enjoy playing Gomoku and may the best strategist win!

About

Python version of the Gomoku game.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors