gomoku/ARCHITECTURE.md

8.8 KiB

Gomoku Game Design Document

1. Overview

A simple turn-based multiplayer Gomoku (Five-in-a-Row) web game for casual play between friends. The system prioritizes simplicity and ease of deployment over scalability.

2. Tech Stack

  • Backend: Elysia (Bun runtime)
  • Frontend: HTML/CSS/TypeScript + HTMX
  • Real-time communication: WebSockets (Elysia built-in)
  • Database: SQLite with Bun:sqlite

3. System Requirements

3.1 Functional Requirements

FR1: Game Creation

  • The system SHALL allow players to create new game sessions
  • The system SHALL generate unique game IDs for each session
  • The system SHALL support maximum 2 players per game

FR2: Player Connection

  • The system SHALL establish WebSocket connections for real-time communication
  • The system SHALL handle player disconnection gracefully
  • The system SHALL allow players to reconnect to existing games

FR3: Game Logic

  • The system SHALL implement standard Gomoku rules (15x15 board)
  • The system SHALL detect win conditions (5 stones in a row: horizontal, vertical, diagonal)
  • The system SHALL validate moves (prevent placing stones on occupied positions)
  • The system SHALL enforce turn-based play

FR4: Real-time Updates

  • The system SHALL broadcast moves to all connected players immediately
  • The system SHALL notify players of game state changes (turn, win, draw)
  • The system SHALL update UI in real-time without page refresh

3.2 Non-Functional Requirements

NFR1: Performance

  • The system SHALL respond to moves within 100ms
  • The system SHALL support concurrent games (minimum 10 simultaneous games)

NFR2: Usability

  • The system SHALL provide intuitive click-to-place stone interaction
  • The system SHALL display current turn indicator
  • The system SHALL show game status (waiting, playing, finished)

NFR3: Reliability

  • The system SHALL maintain game state during temporary disconnections
  • The system SHALL prevent cheating through client-side validation bypass

4. System Architecture

4.1 High-Level Architecture

┌─────────────────┐    WebSocket    ┌─────────────────┐
│   Client A      │◄─────────────►  │                 │
│  (Browser)      │                 │   Elysia        │
└─────────────────┘                 │   Server        │
                                    │                 │
┌─────────────────┐    WebSocket    │                 │
│   Client B      │◄─────────────►  │                 │
│  (Browser)      │                 └─────────────────┘
└─────────────────┘                          │
                                             │
                                   ┌─────────────────┐
                                   │   SQLite DB     │
                                   │   (Optional)    │
                                   └─────────────────┘

4.2 Component Design

4.2.1 Server Components

GameManager

  • Responsibilities: Create/destroy games, manage active game instances, handle matchmaking
  • Interface:
    createGame(): GameInstance
    joinGame(gameId: string, playerId: string): boolean
    getGame(gameId: string): GameInstance | null
    removeGame(gameId: string): void
    

GameInstance

  • Responsibilities: Maintain game state, validate moves, detect win conditions
  • State:
    {
      id: string
      board: (null | 'black' | 'white')[][]
      currentPlayer: 'black' | 'white'
      status: 'waiting' | 'playing' | 'finished'
      winner: null | 'black' | 'white' | 'draw'
      players: { black?: string, white?: string }
    }
    

WebSocketHandler

  • Responsibilities: Manage connections, route messages, handle disconnections

  • Message Types:

    // Client → Server
    { type: 'join_game', gameId: string, playerId: string }
    { type: 'make_move', row: number, col: number }
    { type: 'ping' }
    
    // Server → Client
    { type: 'game_state', state: GameState }
    { type: 'move_result', success: boolean, error?: string }
    { type: 'player_joined', playerId: string }
    { type: 'player_disconnected', playerId: string }
    

4.2.2 Client Components

GameBoardUI

  • Responsibilities: Render 15x15 grid, handle stone placement clicks
  • The component SHALL highlight the last move
  • The component SHALL show stone colors (black/white)
  • The component SHALL disable interaction when not player's turn

GameStateManager

  • Responsibilities: Track local game state, sync with server updates
  • The component SHALL maintain local copy of game state
  • The component SHALL handle optimistic updates with rollback capability

WebSocketClient

  • Responsibilities: Manage WebSocket connection, send/receive messages
  • The component SHALL automatically reconnect on connection loss
  • The component SHALL queue messages during disconnection

5. API Design

5.1 WebSocket Messages

Join Game Request

{
  "type": "join_game",
  "gameId": "optional-game-id",
  "playerId": "player-uuid"
}

Make Move Request

{
  "type": "make_move",
  "row": 7,
  "col": 7
}

Game State Update

{
  "type": "game_state",
  "state": {
    "id": "game-uuid",
    "board": "15x15 array",
    "currentPlayer": "black",
    "status": "playing",
    "winner": null,
    "players": {
      "black": "player1-uuid",
      "white": "player2-uuid"
    }
  }
}

5.2 HTTP Endpoints (HTMX)

GET /

  • Returns main game interface HTML

GET /game/:gameId

  • Returns game-specific interface (for sharing game links)

6. Database Schema

6.1 Tables (Optional - MVP can work without persistence)

games

CREATE TABLE games (
    id TEXT PRIMARY KEY,
    board TEXT NOT NULL,  -- JSON serialized board
    current_player TEXT NOT NULL,
    status TEXT NOT NULL,
    winner TEXT,
    created_at INTEGER NOT NULL,
    updated_at INTEGER NOT NULL
);

players

CREATE TABLE players (
    id TEXT PRIMARY KEY,
    name TEXT,
    created_at INTEGER NOT NULL
);

game_players

CREATE TABLE game_players (
    game_id TEXT NOT NULL,
    player_id TEXT NOT NULL,
    color TEXT NOT NULL,  -- 'black' or 'white'
    FOREIGN KEY (game_id) REFERENCES games(id),
    FOREIGN KEY (player_id) REFERENCES players(id),
    PRIMARY KEY (game_id, player_id)
);

7. User Flow

7.1 Happy Path

  1. Player A opens game URL
  2. System creates new game, assigns Player A as 'black'
  3. Player A shares game link with Player B
  4. Player B joins game, assigned as 'white'
  5. Game starts, Player A (black) makes first move
  6. Players alternate turns until win/draw condition
  7. System displays game result

7.2 Error Scenarios

Player Disconnection

  • The system SHALL maintain game state for 5 minutes
  • The system SHALL notify remaining player of disconnection
  • The system SHALL allow reconnection using same player ID

Invalid Move

  • The system SHALL reject invalid moves
  • The system SHALL send error message to client
  • The system SHALL maintain current game state

8. Security Considerations

8.1 Move Validation

  • The system SHALL validate all moves server-side
  • The system SHALL prevent players from making moves out of turn
  • The system SHALL prevent overwriting existing stones

8.2 Game Integrity

  • The system SHALL generate cryptographically secure game IDs
  • The system SHALL prevent players from joining games they're not invited to
  • The system SHALL rate-limit move requests to prevent spam

9. Deployment

9.1 Development Environment

# Start development server
bun run dev

# Run tests
bun test

# Build for production
bun run build

9.2 Production Considerations

  • Single server deployment (no load balancing needed)
  • SQLite database file backup strategy
  • Environment variable configuration
  • Basic logging for debugging

10. Future Enhancements

10.1 Phase 2 Features

  • Spectator mode
  • Game replay functionality
  • Player statistics tracking
  • Tournament bracket system

10.2 Technical Improvements

  • Redis for session management (multi-server support)
  • Move history with undo functionality
  • AI opponent option
  • Mobile-responsive design optimization

11. Testing Strategy

11.1 Unit Tests

  • Game logic validation (win detection, move validation)
  • WebSocket message handling
  • Database operations (if implemented)

11.2 Integration Tests

  • End-to-end game flow
  • Multi-player scenarios
  • Reconnection handling

11.3 Manual Testing

  • Cross-browser compatibility
  • Network interruption scenarios
  • Simultaneous player actions