Certainly! Below is a Python project that uses Monte Carlo Tree Search (MCTS) to play the described game. The project includes:
- Game Logic: Defines the game state, possible moves, and game rules.
- MCTS Implementation: Implements the MCTS algorithm to decide the best move.
- Player Interface: Allows a human to play against the AI or watch two AI players compete.
- Command-Line Interface: Enables interaction via the terminal.
Project Structure
mcts_game/
├── game.py
├── mcts.py
├── player.py
├── main.py
└── README.md
For simplicity, I'll provide all the code in a single script. You can separate them into different files as per the structure above if desired.
Complete Python Code
import math
import random
import copy
from collections import defaultdict
class GameState:
def __init__(self, n_rows, n_cols, board=None, current_player=1):
self.n_rows = n_rows
self.n_cols = n_cols
if board:
self.board = copy.deepcopy(board)
else:
self.board = [[0 for _ in range(n_cols)] for _ in range(n_rows)]
self.current_player = current_player # 1 or -1
def get_legal_moves(self):
moves = []
for r in range(self.n_rows):
for c in range(self.n_cols):
if self.board[r][c] == 0:
# Check adjacent cells
adjacent = False
for dr, dc in [(-1,0), (1,0), (0,-1), (0,1)]:
nr, nc = r + dr, c + dc
if 0 <= nr < self.n_rows and 0 <= nc < self.n_cols:
if self.board[nr][nc] != 0:
adjacent = True
break
if not adjacent:
moves.append((r, c))
return moves
def make_move(self, move):
r, c = move
new_board = copy.deepcopy(self.board)
new_board[r][c] = self.current_player
return GameState(self.n_rows, self.n_cols, new_board, -self.current_player)
def is_terminal(self):
return len(self.get_legal_moves()) == 0
def get_winner(self):
if not self.is_terminal():
return None
# The last player to make a move is the winner
return -self.current_player
def display(self):
symbols = {0: '.', 1: 'X', -1: 'O'}
print(" " + " ".join(str(c) for c in range(self.n_cols)))
for idx, row in enumerate(self.board):
print(str(idx) + " " + " ".join(symbols[cell] for cell in row))
print()
class MCTSNode:
def __init__(self, state, parent=None, move=None):
self.state = state # GameState
self.parent = parent # MCTSNode
self.children = []
self.move = move # Move that led to this state
self.visits = 0
self.wins = 0
self.untried_moves = self.state.get_legal_moves()
def select_child(self):
# Use UCB1 formula
# c = exploration parameter (commonly sqrt(2))
c = math.sqrt(2)
best_score = -float('inf')
best_child = None
for child in self.children:
if child.visits == 0:
score = float('inf')
else:
score = (child.wins / child.visits) + c * math.sqrt(math.log(self.visits) / child.visits)
if score > best_score:
best_score = score
best_child = child
return best_child
def add_child(self, move, state):
child = MCTSNode(state, parent=self, move=move)
self.untried_moves.remove(move)
self.children.append(child)
return child
def update(self, result):
self.visits += 1
self.wins += result
class MCTS:
def __init__(self, iterations=1000):
self.iterations = iterations
def search(self, initial_state):
root = MCTSNode(initial_state)
for _ in range(self.iterations):
node = root
state = copy.deepcopy(initial_state)
# Selection
while node.untried_moves == [] and node.children:
node = node.select_child()
state = state.make_move(node.move)
# Expansion
if node.untried_moves:
move = random.choice(node.untried_moves)
state = state.make_move(move)
node = node.add_child(move, state)
# Simulation
while not state.is_terminal():
moves = state.get_legal_moves()
if not moves:
break
move = random.choice(moves)
state = state.make_move(move)
# Backpropagation
winner = state.get_winner()
while node is not None:
node.update(1 if winner == node.state.current_player else 0)
node = node.parent
# Select the move with the most visits
best_move = None
max_visits = -1
for child in root.children:
if child.visits > max_visits:
max_visits = child.visits
best_move = child.move
return best_move
def human_move(game_state):
while True:
try:
move = input("Enter your move as 'row col': ")
r, c = map(int, move.strip().split())
if (r, c) in game_state.get_legal_moves():
return (r, c)
else:
print("Invalid move. Try again.")
except:
print("Invalid input format. Please enter two integers separated by space.")
def ai_move(game_state, mcts):
move = mcts.search(game_state)
print(f"AI selects move: {move}")
return move
def main():
n_rows = int(input("Enter number of rows: "))
n_cols = int(input("Enter number of columns: "))
game_state = GameState(n_rows, n_cols)
mcts = MCTS(iterations=1000)
mode = input("Choose game mode:\n1. Human vs AI\n2. AI vs AI\nEnter 1 or 2: ")
game_state.display()
while not game_state.is_terminal():
if mode == '1':
if game_state.current_player == 1:
print("Your turn:")
move = human_move(game_state)
else:
print("AI's turn:")
move = ai_move(game_state, mcts)
else:
print(f"Player {'AI1' if game_state.current_player == 1 else 'AI2'}'s turn:")
move = ai_move(game_state, mcts)
game_state = game_state.make_move(move)
game_state.display()
winner = game_state.get_winner()
if winner == 1:
print("Player 1 (X) wins!")
elif winner == -1:
print("Player 2 (O) wins!")
else:
print("It's a draw!")
if __name__ == "__main__":
main()
How to Use the Project
-
Prerequisites: Ensure you have Python 3 installed on your system.
-
Save the Code: Save the above script to a file named mcts_game.py.
-
Run the Game:
python mcts_game.py
-
Gameplay:
-
Choose Board Size: When prompted, enter the number of rows and columns for the board.
-
Choose Game Mode:
- Enter
1 for Human vs AI.
- Enter
2 for AI vs AI.
-
Making Moves (Human vs AI):
- If you selected Human vs AI and it's your turn, input your move by specifying the row and column numbers separated by a space (e.g.,
2 3).
-
AI Moves:
- The AI will automatically select and display its moves.
-
Game Rules:
- Players alternate turns placing their pieces (
X for Player 1 and O for Player 2).
- A piece cannot be placed adjacent (up, down, left, right) to any existing pieces.
- The last player to successfully place a piece wins the game.
Explanation of the Components
-
GameState Class:
- Represents the current state of the game, including the board, current player, and methods to get legal moves, make moves, check for terminal states, determine the winner, and display the board.
-
MCTSNode Class:
- Represents a node in the MCTS tree.
- Contains methods for selecting child nodes based on the UCB1 formula, adding child nodes, and updating node statistics during backpropagation.
-
MCTS Class:
- Implements the Monte Carlo Tree Search algorithm.
- The
search method performs the MCTS iterations to find the best move from the current game state.
-
Player Functions:
human_move: Handles input from the human player.
ai_move: Uses the MCTS class to determine and execute the AI's move.
-
main Function:
- Facilitates the game flow, handling user input for game setup, alternating turns between players (human or AI), and declaring the winner at the end.
Potential Enhancements
- Performance Optimization: Increase the number of MCTS iterations for stronger AI (at the cost of computation time).
- Heuristics in Simulation: Improve the simulation phase by adding heuristics to make more informed random playouts.
- GUI Interface: Implement a graphical user interface for a better user experience.
- Multithreading: Utilize multithreading or multiprocessing to speed up the MCTS computations.
Conclusion
This project provides a foundational implementation of a two-player grid-based game using MCTS for AI decision-making. It's a solid starting point for further enhancements and can be extended to more complex games or improved with additional features as needed.