Certainly! Below is a Python project structured to implement an AI using Monte Carlo Tree Search (MCTS) to play the described game. The project is organized into multiple files and interfaces, allowing for future extensions such as different AI implementations and various game interfaces.
Project Structure
ai_mcts_game/
├── ai/
│ ├── __init__.py
│ ├── mcts_ai.py
│ └── random_ai.py
├── game/
│ ├── __init__.py
│ ├── game.py
│ └── player.py
├── main.py
└── README.md
1. game/game.py - Game Logic
This module defines the Game class, which encapsulates the game state, rules, and logic for making moves.
# game/game.py
from typing import List, Tuple, Optional
import copy
Position = Tuple[int, int]
class Game:
def __init__(self, rows: int, columns: int):
self.rows = rows
self.columns = columns
self.board = [['.' for _ in range(columns)] for _ in range(rows)]
self.current_player = 'X' # Players can be 'X' and 'O'
def get_available_moves(self) -> List[Position]:
available = []
for r in range(self.rows):
for c in range(self.columns):
if self.board[r][c] == '.' and not self.is_adjacent(r, c):
available.append((r, c))
return available
def is_adjacent(self, r: int, c: int) -> bool:
directions = [(-1,0), (1,0), (0,-1), (0,1)]
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < self.rows and 0 <= nc < self.columns:
if self.board[nr][nc] != '.':
return True
return False
def make_move(self, move: Position) -> bool:
r, c = move
if self.board[r][c] != '.' or self.is_adjacent(r, c):
return False
self.board[r][c] = self.current_player
self.current_player = 'O' if self.current_player == 'X' else 'X'
return True
def is_game_over(self) -> bool:
return len(self.get_available_moves()) == 0
def get_winner(self) -> Optional[str]:
if not self.is_game_over():
return None
# The last player to make a move is the winner
return 'O' if self.current_player == 'X' else 'X'
def clone(self) -> 'Game':
cloned_game = Game(self.rows, self.columns)
cloned_game.board = copy.deepcopy(self.board)
cloned_game.current_player = self.current_player
return cloned_game
def display(self):
for row in self.board:
print(' '.join(row))
print()
2. game/player.py - Player Interface
This module defines the abstract Player class, which serves as an interface for different player types (e.g., AI, human).
# game/player.py
from abc import ABC, abstractmethod
from game.game import Game, Position
class Player(ABC):
def __init__(self, name: str):
self.name = name
@abstractmethod
def select_move(self, game: Game) -> Position:
pass
3. ai/mcts_ai.py - MCTS AI Implementation
This module implements the MCTSPlayer class using the Monte Carlo Tree Search algorithm.
# ai/mcts_ai.py
import math
import random
import time
from typing import List, Optional
from game.game import Game, Position
from game.player import Player
class MCTSNode:
def __init__(self, game: Game, parent: Optional['MCTSNode'] = None, move: Optional[Position] = None):
self.game = game
self.parent = parent
self.move = move
self.children: List[MCTSNode] = []
self.wins = 0
self.visits = 0
self.untried_moves = game.get_available_moves()
def is_fully_expanded(self) -> bool:
return len(self.untried_moves) == 0
def best_child(self, c_param: float = math.sqrt(2)) -> 'MCTSNode':
choices_weights = [
(child.wins / child.visits) + c_param * math.sqrt((2 * math.log(self.visits) ) / child.visits)
for child in self.children
]
return self.children[choices_weights.index(max(choices_weights))]
def expand(self) -> 'MCTSNode':
move = self.untried_moves.pop()
next_game = self.game.clone()
next_game.make_move(move)
child_node = MCTSNode(next_game, parent=self, move=move)
self.children.append(child_node)
return child_node
def most_visited_child(self) -> 'MCTSNode':
return max(self.children, key=lambda c: c.visits)
class MCTSPlayer(Player):
def __init__(self, name: str, time_limit: float = 1.0):
super().__init__(name)
self.time_limit = time_limit # Time limit per move in seconds
def select_move(self, game: Game) -> Position:
root = MCTSNode(game.clone())
end_time = time.time() + self.time_limit
while time.time() < end_time:
node = root
simulated_game = game.clone()
# Selection
while node.is_fully_expanded() and node.children:
node = node.best_child()
simulated_game.make_move(node.move)
# Expansion
if node.untried_moves:
node = node.expand()
simulated_game.make_move(node.move)
# Simulation
winner = self.simulate(simulated_game)
# Backpropagation
while node is not None:
node.visits += 1
if node.game.current_player != winner:
node.wins += 1
node = node.parent
# Choose the move with the most visits
if root.children:
best_child = max(root.children, key=lambda c: c.visits)
return best_child.move
else:
# No possible moves
return (-1, -1)
def simulate(self, game: Game) -> Optional[str]:
while not game.is_game_over():
moves = game.get_available_moves()
if not moves:
break
move = random.choice(moves)
game.make_move(move)
return game.get_winner()
4. ai/random_ai.py - Random AI Implementation
This module implements a RandomPlayer class that selects moves randomly. It serves as an example of an alternative AI implementation.
# ai/random_ai.py
import random
from game.game import Game, Position
from game.player import Player
class RandomPlayer(Player):
def __init__(self, name: str):
super().__init__(name)
def select_move(self, game: Game) -> Position:
available_moves = game.get_available_moves()
if not available_moves:
return (-1, -1)
return random.choice(available_moves)
5. ai/__init__.py - AI Package Initialization
This file makes the ai directory a Python package.
# ai/__init__.py
from .mcts_ai import MCTSPlayer
from .random_ai import RandomPlayer
6. game/__init__.py - Game Package Initialization
This file makes the game directory a Python package.
# game/__init__.py
from .game import Game
from .player import Player
7. main.py - Entry Point
This script allows you to run a game between two players (AI or human). Currently, it sets up a game between two AI players: one using MCTS and the other using random moves.
# main.py
from game import Game
from ai import MCTSPlayer, RandomPlayer
def main():
rows, columns = 5, 5 # You can modify the board size here
game = Game(rows, columns)
# Initialize players
player1 = MCTSPlayer(name="MCTS_AI", time_limit=2.0) # 2 seconds per move
player2 = RandomPlayer(name="Random_AI")
players = {
'X': player1,
'O': player2
}
game.display()
while not game.is_game_over():
current_player = players[game.current_player]
move = current_player.select_move(game)
if move == (-1, -1):
break
success = game.make_move(move)
if not success:
print(f"Invalid move by {current_player.name}: {move}")
break
print(f"{current_player.name} ({game.current_player}) placed at {move}")
game.display()
winner = game.get_winner()
if winner:
print(f"Winner: {players[winner].name}")
else:
print("It's a draw!")
if __name__ == "__main__":
main()
8. README.md - Project Documentation
# AI MCTS Game
## Description
This project implements an AI using Monte Carlo Tree Search (MCTS) to play a two-player game on a board. Players take turns placing pieces on the board without placing them adjacent to existing pieces. The last player to successfully place a piece wins.
## Project Structure
ai_mcts_game/
├── ai/
│ ├── init.py
│ ├── mcts_ai.py
│ └── random_ai.py
├── game/
│ ├── init.py
│ ├── game.py
│ └── player.py
├── main.py
└── README.md
## Requirements
- Python 3.7 or higher
## How to Run
1. **Clone the Repository**
```bash
git clone https://github.com/yourusername/ai_mcts_game.git
cd ai_mcts_game
```
2. **Run the Game**
```bash
python main.py
```
The game will start with a 5x5 board between an MCTS AI and a Random AI. You can modify the board size and player types in `main.py`.
## Extending the Project
- **Adding New AI Players**
Implement a new class in the `ai/` directory inheriting from the `Player` abstract class and implement the `select_move` method.
- **Changing Game Interfaces**
Modify or add new modules in the `game/` directory to support different interfaces like command-line, GUI, or training environments.
## License
MIT License
Running the Project
-
Ensure You Have Python Installed
Make sure you have Python 3.7 or higher installed on your system. You can check your Python version with:
python --version
-
Navigate to the Project Directory
cd ai_mcts_game
-
Run the Game
python main.py
You should see the game board displayed in the console, with players taking turns to place their pieces. The MCTS AI will think for a specified time limit (e.g., 2 seconds) per move, while the Random AI selects moves randomly.
Example Output
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
MCTS_AI (X) placed at (2, 2)
. . . . .
. . . . .
. . X . .
. . . . .
. . . . .
Random_AI (O) placed at (0, 0)
O . . . .
. . . . .
. . X . .
. . . . .
. . . . .
MCTS_AI (X) placed at (4, 4)
O . . . .
. . . . .
. . X . .
. . . . .
. . . . X
Random_AI (O) placed at (0, 4)
O . . . O
. . . . .
. . X . .
. . . . .
. . . . X
...
Winner: MCTS_AI
Notes
-
Time Limit for MCTS: The MCTSPlayer is configured with a time_limit parameter (e.g., 2.0 seconds) which determines how long it thinks per move. You can adjust this in main.py when initializing the MCTSPlayer.
-
Extensibility: The project is designed with extensibility in mind. You can easily add new AI algorithms by creating new classes that inherit from the Player abstract class. Similarly, the game logic can be extended or modified without affecting the AI implementations.
-
Error Handling: The current implementation includes basic error handling for invalid moves. You can enhance this further based on specific requirements.
Feel free to customize and extend this project to fit your needs!