Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions chess-game/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.vscode/
.idea/
*.log
.DS_Store
*.swp
*.bak
*.tmp
244 changes: 148 additions & 96 deletions chess-game/README.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
# Chess Game Example

A full-stack web-based chess game built with the XTC language, featuring a turn-based gameplay system with an automated AI opponent.
A full-stack web-based chess game built with the XTC language, featuring both single-player mode with an intelligent AI opponent and online multiplayer with real-time chat.

## Overview

This project demonstrates a complete web application using the XTC platform:
- **Server**: RESTful API built with XTC web framework and OODB (Object-Oriented Database)
- **Client**: Single-page application with vanilla JavaScript and modern CSS
- **Game Logic**: Complete chess rule implementation with simplified mechanics
- **AI Opponent**: Heuristic-based move selection for automated gameplay
- **Game Logic**: Complete chess rule implementation including castling and en passant
- **AI Opponent**: Diverse, randomized AI with opening book and heuristic evaluation
- **Online Multiplayer**: Play against others with game codes and real-time chat

### Key Features

- ♟️ **Turn-based Gameplay**: Play as White against an automated Black opponent
- 🎮 **Simplified Chess Rules**: No castling, en passant, or explicit check detection
- 🤖 **AI Opponent**: Smart move selection based on piece values and positional strategy
- 💾 **Persistent State**: Game state saved in OODB database
- 🎨 **Modern UI**: Responsive design with smooth animations
- ♟️ **Two Game Modes**: Single-player vs AI or online multiplayer
- 🎮 **Complete Chess Rules**: Full implementation including castling, en passant, and pawn promotion
- 🤖 **Intelligent & Diverse AI**: Randomized move selection with opening book for varied gameplay
- 🌐 **Online Multiplayer**: Create or join games with unique game codes
- 💬 **Real-time Chat**: Modern chat interface for online games
- 💾 **Session Isolation**: Each browser tab has its own independent game
- 🎨 **Modern UI**: Responsive design with smooth animations and gradients
- ⚡ **Real-time Updates**: Auto-refresh during opponent's turn
- ⏱️ **Time Controls**: Optional chess clocks for competitive play

## Prerequisites

Expand All @@ -33,16 +37,30 @@ chess-game/
├── gradlew / gradlew.bat # Gradle wrapper scripts
├── server/ # Backend module
│ ├── build.gradle.kts # Server build configuration
│ ├── main/x/ # XTC source code
│ │ ├── chess.x # Main server and API endpoints
│ │ ├── chessDB.x # Database schema and data models
│ │ └── chessLogic.x # Chess game logic and move validation
│ └── build/
│ └── chessDB.xtc # Compiled database file
│ └── chess/main/x/ # XTC source code
│ ├── chess.x # Main module definition
│ └── chess/
│ ├── ChessApi.x # REST API endpoints
│ ├── ChessGame.x # Core game state management
│ ├── ChessLogic.x # Move execution logic
│ ├── ChessAI.x # AI opponent with randomization
│ ├── PieceValidator.x # Move validation
│ ├── CheckDetection.x # Check/checkmate detection
│ ├── BoardUtils.x # Board utilities
│ ├── ValidMovesHelper.x # Valid move calculation
│ ├── OnlineChessApi.x # Multiplayer API
│ ├── OnlineChessLogic.x # Multiplayer logic
│ ├── ChatApi.x # Chat functionality
│ └── TimeControlService.x # Chess clock
├── chessDB/main/x/
│ └── chessDB.x # Database schema
└── webapp/ # Frontend module
├── build.gradle.kts # Webapp build configuration
└── public/
└── index.html # Single-page web client
├── index.html # Main HTML page
└── static/
├── app.js # JavaScript application
└── styles.css # Modern CSS styling
```

## Quick Start
Expand All @@ -61,6 +79,12 @@ cd chess-game

This will compile the XTC code and prepare all dependencies.

### 3. Run the Server

```bash
./gradlew run
```

### 4. Open the Game

Open your web browser and navigate to:
Expand All @@ -71,80 +95,121 @@ http://localhost:8080

You should see the chess board and be ready to play!

## Game Modes

### Single Player (vs AI)

Play against an intelligent AI opponent that uses:
- **Opening Book**: Recognizes common chess openings and responds with strong moves
- **Randomized Selection**: Chooses from top-scoring moves for unpredictable gameplay
- **Positional Evaluation**: Uses piece-square tables for strategic positioning
- **Tactical Awareness**: Evaluates captures, checks, and material balance

The AI adds variety by:
- Randomly selecting from multiple strong opening responses
- Choosing from top moves within a score threshold (not always the "best" move)
- Different play styles in opening, middle, and endgame phases

**Session Isolation**: Each browser tab gets its own independent game. You can play multiple games simultaneously in different tabs without interference.

### Online Multiplayer

1. Click the **Online** tab
2. Choose to **Create Game** (generates a unique code) or **Join Game** (enter a code)
3. Share the game code with your opponent
4. Play in real-time with automatic turn synchronization
5. Use the **Chat** feature to communicate during the game

## How to Play

### Game Rules

This implementation uses **simplified chess rules**:
This implementation includes **complete chess rules**:

- ✅ **Standard piece movement**: Pawns, Knights, Bishops, Rooks, Queens, and Kings move according to traditional rules
- ✅ **Pawn promotion**: Pawns automatically promote to Queens when reaching the opposite end
- ✅ **Capture pieces**: Capture opponent pieces to increase your score
- ❌ **No castling**: Special king-rook move is not implemented
- ❌ **No en passant**: Special pawn capture is not implemented
- ❌ **Simplified game ending**:
- **Checkmate**: When one player has no pieces left (all captured)
- **Stalemate**: When only kings remain on the board
- ✅ **Standard piece movement**: All pieces move according to official chess rules
- ✅ **Castling**: Both kingside (O-O) and queenside (O-O-O) castling
- ✅ **En passant**: Special pawn capture available for one move after double pawn push
- ✅ **Pawn promotion**: Pawns promote to Queen when reaching the opposite end
- ✅ **Check detection**: Illegal to move into check or leave king in check
- ✅ **Checkmate**: Game ends when king is in check with no escape
- ✅ **Stalemate**: Game ends in draw when no legal moves but not in check

### Making Moves

1. **Click a square** with your piece (White pieces)
1. **Click a square** with your piece (you play as White in single-player)
2. **Click the destination** square where you want to move
3. The move will be validated by the server
4. If legal, the opponent (Black) will automatically respond after a 3-second delay
4. If legal, the opponent responds (AI instantly picks from good moves, online opponent when they move)
5. Continue playing until the game ends

### Game Controls

- **Reset Game**: Start a new game with fresh board setup
- **Refresh State**: Manually sync with the server (useful if connection is lost)
- **Sync**: Manually refresh the game state from the server
- **Info**: View game status and rules
- **Chat**: Open chat panel (online mode)

## API Documentation

The server exposes a RESTful API at `/api`:

### Get Game State
### Single Player Endpoints

All single-player endpoints include a session ID for game isolation:

#### Get Game State
```http
GET /api/state
GET /api/state/{sessionId}
```

**Response:**
```json
{
"board": ["rnbqkbnr", "pppppppp", "........", ...],
"turn": "White",
"status": "Ongoing",
"message": "Your move.",
"lastMove": "e2e4",
"playerScore": 0,
"opponentScore": 0,
"opponentPending": false
}
#### Make a Move
```http
POST /api/move/{sessionId}/{from}/{to}
```

### Make a Move
#### Reset Game
```http
POST /api/reset/{sessionId}
```

#### Get Valid Moves
```http
POST /api/move/{from}/{to}
GET /api/validmoves/{sessionId}/{square}
```

**Parameters:**
- `from`: Source square in algebraic notation (e.g., `e2`)
- `to`: Destination square in algebraic notation (e.g., `e4`)
### Online Multiplayer Endpoints

**Example:**
#### Create Game
```http
POST /api/move/e2/e4
POST /api/online/create
```

### Reset Game
#### Join Game
```http
POST /api/online/join/{gameCode}?color={white|black}
```

#### Get Online Game State
```http
POST /api/reset
GET /api/online/state/{gameCode}?playerId={playerId}
```

Resets the game to the initial board position.
#### Make Online Move
```http
POST /api/online/move/{gameCode}/{from}/{to}?playerId={playerId}
```

### Chat Endpoints

#### Send Message
```http
POST /api/chat/{gameCode}/send?playerId={playerId}&message={message}
```

#### Get Messages
```http
GET /api/chat/{gameCode}/messages?since={timestamp}
```

## Technical Details

Expand All @@ -171,22 +236,26 @@ Index: 56-63 = Rank 1 (a1-h1) - White's back rank

### AI Strategy

The automated opponent uses a simple heuristic evaluation function:
The AI opponent uses sophisticated move selection:

1. **Piece Values**: Pawn=1, Knight/Bishop=3, Rook=5, Queen=9, King=100
2. **Position Bonus**: Pieces closer to center score higher
3. **Special Bonuses**:
- Pawn promotion: +8 points
- Checkmate: +1000 points
1. **Opening Book**: Collection of strong opening responses (Sicilian, French, Caro-Kann, etc.)
2. **Piece Values**: Pawn=100, Knight=320, Bishop=330, Rook=500, Queen=900
3. **Piece-Square Tables**: Positional bonuses for optimal piece placement
4. **Mobility**: Bonus for having more available moves
5. **Tactical Evaluation**: Check bonuses, development bonuses, center control
6. **Randomization**: Selects from top moves within 15% of best score for variety

The AI evaluates all legal moves and selects the one with the highest score.
### Session Management

- Single-player games use `sessionStorage` for browser tab isolation
- Each tab generates a unique session ID on first load
- Game state is persisted per-session in the database
- Refreshing the page restores your game; opening a new tab starts fresh

## Development

### Running in Development Mode

The XTC platform supports hot-reloading. After making changes to `.x` files:

```bash
./gradlew :server:run --continuous
```
Expand All @@ -199,35 +268,34 @@ This will automatically rebuild and restart the server when files change.
./gradlew build -Pproduction
```

### Testing
### Project Architecture

Currently, the project focuses on functional gameplay. To test manually:

1. Start the server
2. Open the web interface
3. Make moves and verify:
- Legal moves are accepted
- Illegal moves are rejected with appropriate messages
- Opponent responds after delay
- Game state persists across refreshes
- Scores update correctly
The server uses a modular architecture:
- **ChessApi**: Routes HTTP requests to appropriate handlers
- **ChessGame**: Manages game state and coordinates logic
- **ChessAI**: Intelligent move selection with randomization
- **ChessLogic**: Executes moves and updates state
- **PieceValidator**: Validates move legality per piece type
- **CheckDetection**: Determines check, checkmate, and stalemate
- **OnlineChessApi/Logic**: Handles multiplayer game sessions
- **ChatApi**: Real-time chat for online games

## Database

The game uses XTC's OODB (Object-Oriented Database) for state persistence:

- **Database file**: `server/build/chessDB.xtc`
- **Schema**: Defined in `server/main/x/chessDB.x`
- **Storage**: Games are stored in a map indexed by game ID (currently using ID=1 for single-game support)
- **Schema**: Defined in `chessDB/main/x/chessDB.x`
- **Storage**:
- Single-player games in `singlePlayerGames` map (keyed by session ID)
- Online games in `onlineGames` map (keyed by game code)

The database automatically persists game state, allowing you to close and restart the server without losing your game progress.
The database automatically persists game state, allowing you to close and restart the server without losing progress.

## Troubleshooting

### Port Already in Use

If port 8080 is already in use, you can change it by modifying the server configuration or killing the process using that port:

```bash
# Find the process
lsof -i :8080
Expand All @@ -239,38 +307,22 @@ kill -9 PID
### Build Failures

Ensure you have Java 11+ installed:

```bash
java -version
```

Clear the Gradle cache if needed:

```bash
./gradlew clean build
```

### Game State Issues

If the game gets into a bad state, you can:

If the game gets into a bad state:
1. Click the **Reset Game** button in the UI
2. Delete the database file: `rm server/build/chessDB.xtc`
3. Restart the server

## Contributing

This is an example project demonstrating XTC capabilities. Contributions are welcome!

Potential improvements:
- Add castling and en passant moves
- Implement proper check/checkmate detection
- Add move history and undo functionality
- Support multiple simultaneous games
- Add player authentication
- Implement time controls
- Add game replay feature

2. Open a new browser tab for a fresh game
3. Delete the database file: `rm server/build/chessDB.xtc`
4. Restart the server

## Learn More

Expand Down
Loading