Content
# Gomoku AI Battle Project
A Gomoku AI battle platform based on MCP (Model Context Protocol), allowing AI to compete in Gomoku through the MCP interface.
## ✨ Project Highlights
- 🤖 **Real AI Battles**: Supports AI like Claude to compete directly via the MCP protocol.
- 👁️ **Real-time Spectating**: A beautiful web interface displays the battle process in real-time.
- 🎯 **Complete Game Logic**: Standard 15x15 Gomoku rules with support for win/loss determination.
- 📊 **Data Statistics**: Player rankings, game history, and statistical analysis.
- 🔧 **Easy to Extend**: Modular design supports custom AI algorithms.
## 🎮 Demonstration Effect
**Successfully implemented Claude AI vs Claude AI battles!**
- ✅ Two AI instances connected simultaneously.
- ✅ Real-time moves and status updates.
- ✅ Web interface perfectly displays the board.
- ✅ Game logic is completely correct.
## Project Structure
```
gomoku-ai-battle/
├── README.md # Project description
├── requirements.txt # Python dependencies
├── GOMOKU_AI_BATTLE_PROJECT.md # Detailed project documentation
├──
├── game_server/ # Game server
│ ├── main.py # FastAPI application entry
│ ├── config.py # Configuration file
│ ├── models/ # Data models
│ ├── services/ # Business logic
│ └── api/ # API routes
│
├── mcp_server/ # MCP server
│ ├── gomoku_mcp.py # Main file for MCP server
│ ├── config.py # MCP configuration
│ └── tools/ # MCP tools
│
├── ai_client/ # AI client
│ ├── mcp_client.py # MCP client wrapper
│ └── simple_ai.py # Simple AI implementation
│
├── scripts/ # Script tools
│ ├── start_game_server.py # Start game server
│ ├── start_mcp_server.py # Start MCP server
│ └── run_ai_battle.py # Run AI battle
│
└── tests/ # Test code
├── test_game_logic.py # Game logic tests
└── test_mcp_server.py # MCP server tests
```
## 🚀 Quick Start
### 1. Install Dependencies
```bash
pip install -r requirements.txt
```
### 2. Start the Game Server
```bash
python scripts/start_game_server.py
```
The game server will start at `http://localhost:8000`:
- 🌐 **Web Interface**: http://localhost:8000
- 📚 **API Documentation**: http://localhost:8000/docs
- 🎮 **Spectator Platform**: http://localhost:8000/static/index.html
### 3. Configure Claude Desktop
Add the MCP server to the Claude Desktop configuration file:
**Configuration File Location:**
- Windows: `%APPDATA%\Claude\claude_desktop_config.json`
- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
**Configuration Content:**
```json
{
"mcpServers": {
"gomoku-mcp-server": {
"command": "python",
"args": ["D:\\your\\project\\path\\scripts\\start_mcp_server.py"],
"env": {
"PYTHONIOENCODING": "utf-8",
"MCP_GAME_SERVER_URL": "http://localhost:8000"
}
}
}
}
```
### 4. Start the MCP Server
```bash
python scripts/start_mcp_server.py
```
### 5. Restart Claude Desktop
Completely close and reopen Claude Desktop to apply the configuration.
### 6. Start AI Battles!
Now Claude AI can directly compete in Gomoku through the MCP tool:
```
I want to create a Gomoku room to start a battle.
```
Or run the example AI client:
```bash
# Run 2 AIs in battle
python scripts/run_ai_battle.py --mode battle --ai-count 2
# Let AI join a specified room
python scripts/run_ai_battle.py --mode join --room-id room_12345 --ai-id AI_Test
```
## Usage Instructions
### Game Server API
The game server provides a REST API interface:
- `POST /api/v1/rooms` - Create a room
- `GET /api/v1/rooms` - Get the list of rooms
- `POST /api/v1/rooms/{room_id}/join` - Join a room
- `POST /api/v1/rooms/{room_id}/move` - Make a move
- `GET /api/v1/rooms/{room_id}/game` - Get game status
### 🛠️ MCP Tools
The MCP server provides the following tools for AI calls:
**Game Operation Tools:**
- `create_room(creator_id, room_name)` - Create a room
- `join_room(room_id, player_id)` - Join a room
- `leave_room(room_id, player_id)` - Leave a room
- `start_game(room_id, player_id)` - Start the game
- `make_move(room_id, player_id, x, y)` - Make a move
- `get_move_suggestions(room_id, player_id, count)` - Get move suggestions
- `get_leaderboard(limit, sort_by)` - Get leaderboard
- `get_server_status()` - Get server status
**Information Query Resources:**
- `board_state://{room_id}` - Get board state
- `game_info://{room_id}` - Get game information
- `gomoku://room_list` - Get room list
- `player_info://{player_id}` - Get player information
### 🎯 AI Battle Example
**Create a room and start a battle:**
```
Claude: I want to create a Gomoku room.
AI: Successfully created room 'Claude's AI Battle Room', Room ID: room_3b93ac16.
Claude: Let another AI join the room.
AI: Successfully joined room room_3b93ac16.
Claude: Start the game and make the first move in the center position.
AI: Move successful.
Claude: Check the current board state.
AI: [Displays 15x15 board, center has black piece ●].
```
**Actual demonstration results:**
- ✅ Successfully created room: `room_3b93ac16`.
- ✅ Two AIs battling simultaneously: `Claude_AI_1 vs Claude_AI_2`.
- ✅ 7 moves have been made, the game is ongoing.
- ✅ Web interface displays the board state in real-time.
### AI Client Development
Using the `GomokuMCPClient` class, you can easily develop an AI client:
```python
from ai_client.mcp_client import GomokuMCPClient
async def my_ai():
async with GomokuMCPClient() as client:
# Create a room
result = await client.create_room("my_ai", "Test Room")
# Get board state
board = await client.get_board_state("room_id")
# Make a move
result = await client.make_move("room_id", "my_ai", 7, 7)
```
## Configuration
### Game Server Configuration
You can configure in `game_server/config.py`:
- Server address and port
- Board size and winning conditions
- Room and player limits
- Log level
### MCP Server Configuration
You can configure in `mcp_server/config.py`:
- Game server connection address
- Connection timeout and retry settings
- AI suggestion count limit
- Log level
## Development and Testing
### Run Tests
```bash
# Run all tests
pytest
# Run specific tests
pytest tests/test_game_logic.py
pytest tests/test_mcp_server.py
```
### Development Mode
```bash
# Start game server (development mode)
python scripts/start_game_server.py --debug --reload
# Start MCP server (debug mode)
python scripts/start_mcp_server.py --debug --log-level DEBUG
```
## 🏗️ Architecture Description
### System Architecture
```
┌─────────────┐ MCP ┌─────────────┐ HTTP ┌─────────────┐
│ Claude AI │ ←────────→ │ MCP Server │ ←────────→ │ Game Server │
│ (Black Player) │ │ │ │ │
└─────────────┘ └─────────────┘ └─────────────┘
↑ ↑
│ MCP │ HTTP
↓ ↓
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Claude AI │ ←────────→ │ MCP Server │ │ Web Spectator │
│ (White Player) │ │ (Same) │ │ │
└─────────────┘ └─────────────┘ └─────────────┘
```
### Data Flow
1. **AI Connection**: Claude AI connects to the MCP server via the MCP protocol.
2. **Command Conversion**: The MCP server converts AI commands into HTTP API calls.
3. **Game Processing**: The game server processes Gomoku logic and updates the state.
4. **Result Return**: The MCP server returns the game results to the AI.
5. **Real-time Spectating**: The web interface displays the board state in real-time.
### Tech Stack
- **Game Server**: Python + FastAPI + Pydantic + Uvicorn
- **MCP Server**: MCP Python SDK (FastMCP) + httpx
- **Web Interface**: HTML5 + CSS3 + JavaScript + Real-time refresh
- **AI Client**: Claude Desktop + MCP protocol
- **Communication Protocol**: HTTP REST API + MCP stdio + WebSocket (optional)
### Core Features
- 🔄 **Real-time Synchronization**: Game state is synchronized in real-time to all clients.
- 🎯 **Precise Control**: Coordinate system (0-14) supports precise moves.
- 🛡️ **Error Handling**: Comprehensive exception handling and retry mechanisms.
- 📊 **State Management**: Complete game state and room management.
- 🎮 **Multiple Modes**: Supports AI vs AI, spectating, statistics, and more.
## 🎉 Success Cases
### Actual Battle Records
**Room Information:**
- Room ID: `room_3b93ac16`
- Room Name: "Claude's AI Battle Room"
- Competing Parties: `Claude_AI_1` (Black) vs `Claude_AI_2` (White)
**Battle Progress:**
1. ✅ Claude_AI_1 created the room.
2. ✅ Claude_AI_2 successfully joined.
3. ✅ The game started automatically.
4. ✅ 7 moves have been made.
5. ✅ Web interface displays in real-time.
**Board State:**
```
Current board (after 7 moves):
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 · · · · · · · · · · · · · · ·
1 · · · · · · · · · · · · · · ·
...
7 · · · · ○ ● ● ● ○ ○ · · · · ·
8 · · · · · · · · ● · · · · · ·
...
```
**Technical Validation:**
- ✅ MCP protocol communication is normal.
- ✅ Game logic is completely correct.
- ✅ Web interface updates in real-time.
- ✅ Supports multiple AIs concurrently.
- ✅ Error handling mechanisms are effective.
## 🚀 Extended Features
The project supports the following extensions:
- 🧠 More complex AI algorithms (basic framework already in place).
- 👁️ Web interface spectating (✅ implemented).
- 📹 Game replay functionality.
- 🎲 Support for various board games (Chess, Go, etc.).
- 💾 Database persistence.
- 🔐 User authentication system.
- 📊 Advanced statistical analysis.
- 🏆 AI algorithm scoring system.
- 🌐 Multiplayer online battles.
- 📱 Mobile support.
## 🔧 Troubleshooting
### Common Issues and Solutions
1. **MCP Server Fails to Start**
```
Error: URL validation error
Solution: Check the resource URI format and ensure a valid URL scheme is used.
```
2. **HTTP 307 Redirect Error**
```
Error: Game server error: 307 Temporary Redirect
Solution: Add follow_redirects=True in the httpx request.
```
3. **Claude Desktop Cannot See MCP Tools**
```
Issue: Tools not displayed after modifying the configuration file.
Solution:
- Ensure the configuration file path is correct.
- Completely restart Claude Desktop.
- Check if the MCP server is running.
```
4. **Game Server Connection Failed**
```
Error: Failed to connect to the game server.
Solution:
- Ensure the game server is running at http://localhost:8000.
- Check if the port is occupied.
- Review firewall settings.
```
5. **Move Failed**
```
Error: Invalid move position.
Solution:
- Ensure coordinates are within the range of 0-14.
- Check if the position is already occupied.
- Confirm it's the current player's turn.
```
### Debugging Steps
1. **Verify Server Status**
```bash
curl http://localhost:8000/api/v1/health
# Should return: {"status":"healthy",...}
```
2. **Check MCP Connection**
```bash
python scripts/start_mcp_server.py --debug
# View detailed log output.
```
3. **Test API Calls**
```bash
curl http://localhost:8000/api/v1/rooms/
# Should return room list JSON.
```
### Log Viewing
```bash
# View game server logs
python scripts/start_game_server.py --log-level DEBUG
# View MCP server logs
python scripts/start_mcp_server.py --debug --log-level DEBUG
# View AI battle logs
tail -f ai_battle.log
```
### Success Verification Checklist
- ✅ Game server started: `http://localhost:8000`.
- ✅ MCP server started: Displays "Starting Gomoku MCP Server".
- ✅ Claude Desktop restarted: Configuration applied.
- ✅ MCP tools visible: Tools can be called in Claude.
- ✅ Room creation successful: Returns room ID.
- ✅ Move successful: Returns "Move successful".
- ✅ Web interface displays: Board updates in real-time.
## Contribution
Feel free to submit Issues and Pull Requests to improve the project!
## License
MIT License
Connection Info
You Might Also Like
cc-switch
All-in-One Assistant for Claude Code, Codex & Gemini CLI across platforms.
awesome-mcp-servers
A collection of MCP servers.
git
A Model Context Protocol server for Git automation and interaction.
Train-in-Silence
The first Task-Aware MCP server and automated VRAM calculator for LLM...
ai-orchestrator
Portable multi-agent AI developer setup for Claude Code + Ollama. Role-based...
houtini-lm
Local or Cloud LLM support via MCP for your AI assistant with Houtini-LM -...