use pygame to write a Gobang game, and adding an AI using MCTS
- User
use pygame to write a Gobang game, and adding an AI using MCTS
- Assistant
use pygame to write a Gobang game, and adding an AI using MCTS
Creating a Gobang (Five in a Row) game with Pygame and integrating an AI using Monte Carlo Tree Search (MCTS) is an exciting project. Below is a step-by-step guide along with the complete Python code to help you achieve this.
Before diving into the code, ensure you have the following installed:
You can install Pygame using pip:
pip install pygame
For simplicity, we'll keep everything in a single Python file. However, for larger projects, it's recommended to separate classes and functionalities into different modules.
Monte Carlo Tree Search is a heuristic search algorithm for decision processes, notably in game playing. It involves the following steps:
Implementing MCTS for Gobang requires handling the game state, possible moves, and efficiently performing simulations.
Below is the complete Python code integrating Pygame for the UI and implementing the MCTS-based AI.
GameState Classmake_move(row, col): Places a piece on the board.get_available_moves(): Returns a list of valid moves.is_near(row, col, distance=2): Optimizes move generation by considering positions near existing pieces.check_win(last_move): Checks if the last move resulted in a win.MCTSNode Classstate: Current game state.parent: Parent node.move: The move that led to this state.children: List of child nodes.visits & wins: Statistics for MCTS.untried_moves: Moves that can be tried from this state.select_child(): Selects the child with the highest UCB1 score.add_child(move, state): Adds a new child node.update(result): Updates the node's statistics based on simulation results.MCTS Functionroot: The root node from which MCTS starts.iter_limit: Maximum number of iterations/simulations.time_limit: Maximum time allowed for MCTS (in seconds).draw_grid(): Draws the game grid.draw_pieces(board): Draws the black and white pieces on the board.get_grid_pos(pos): Converts mouse click positions to grid coordinates.main FunctionSave the Code: Copy the complete code into a Python file, e.g., gobang_mcts.py.
Run the Script:
python gobang_mcts.py
Gameplay:
Exiting the Game: Close the game window or press Ctrl + C in the terminal.
While the above implementation provides a functional Gobang game with an MCTS-based AI, there are several ways to enhance and optimize it:
Performance Optimization:
Enhanced AI:
User Interface Improvements:
Advanced AI Techniques:
This implementation provides a solid foundation for a Gobang game with an AI opponent. By understanding the structure and functionality, you can further customize and enhance the game to suit your preferences. Happy coding!
Not yet included in a published release.
import pygame
import sys
import math
import random
import time
from copy import deepcopy
# Initialize Pygame
pygame.init()
# Screen settings
WIDTH, HEIGHT = 600, 600
ROWS, COLS = 15, 15
GAP = WIDTH // ROWS
BORDER = 20
# Colors
BG_COLOR = (222, 184, 135) # Wood-like background
LINE_COLOR = (0, 0, 0)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# Fonts
FONT = pygame.font.SysFont(None, 40)
# Screen setup
screen = pygame.display.set_mode((WIDTH + BORDER*2, HEIGHT + BORDER*2))
pygame.display.set_caption("Gobang with MCTS AI")
# Game Settings
EMPTY = 0
BLACK_PIECE = 1
WHITE_PIECE = 2
WIN_COUNT = 5
# Clock
clock = pygame.time.Clock()
class GameState:
def __init__(self, board=None, turn=BLACK_PIECE):
if board is None:
self.board = [[EMPTY for _ in range(COLS)] for _ in range(ROWS)]
else:
self.board = deepcopy(board)
self.turn = turn
def make_move(self, row, col):
if self.board[row][col] != EMPTY:
return False
self.board[row][col] = self.turn
self.turn = BLACK_PIECE if self.turn == WHITE_PIECE else WHITE_PIECE
return True
def get_available_moves(self):
moves = []
for r in range(ROWS):
for c in range(COLS):
if self.board[r][c] == EMPTY:
# To optimize, consider moves near existing pieces
if self.is_near(r, c):
moves.append((r, c))
return moves
def is_near(self, row, col, distance=2):
for r in range(max(0, row - distance), min(ROWS, row + distance + 1)):
for c in range(max(0, col - distance), min(COLS, col + distance + 1)):
if self.board[r][c] != EMPTY:
return True
return False
def check_win(self, last_move=(None, None)):
if last_move == (None, None):
return False
row, col = last_move
piece = self.board[row][col]
if piece == EMPTY:
return False
directions = [(1,0), (0,1), (1,1), (1,-1)]
for dr, dc in directions:
count = 1
# Check in the positive direction
r, c = row + dr, col + dc
while 0 <= r < ROWS and 0 <= c < COLS and self.board[r][c] == piece:
count += 1
r += dr
c += dc
# Check in the negative direction
r, c = row - dr, col - dc
while 0 <= r < ROWS and 0 <= c < COLS and self.board[r][c] == piece:
count += 1
r -= dr
c -= dc
if count >= WIN_COUNT:
return piece
return False
class MCTSNode:
def __init__(self, state, parent=None, move=None):
self.state = state # GameState
self.parent = parent # Parent MCTSNode
self.move = move # The move that led to this state
self.children = []
self.visits = 0
self.wins = 0
self.untried_moves = state.get_available_moves()
def select_child(self):
# Select child with highest UCB1 score
best_score = -float('inf')
best_child = None
for child in self.children:
if child.visits == 0:
ucb1 = float('inf')
else:
ucb1 = (child.wins / child.visits) + math.sqrt(2 * math.log(self.visits) / child.visits)
if ucb1 > best_score:
best_score = ucb1
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
if result:
self.wins += 1
def MCTS(root, iter_limit=1000, time_limit=None):
start_time = time.time()
for _ in range(iter_limit):
node = root
state = deepcopy(root.state)
# Selection
while node.untried_moves == [] and node.children:
node = node.select_child()
state.make_move(*node.move)
# Expansion
if node.untried_moves:
move = random.choice(node.untried_moves)
state.make_move(*move)
node = node.add_child(move, state)
# Simulation
winner = state.check_win(move)
while winner == False and state.get_available_moves():
m = random.choice(state.get_available_moves())
state.make_move(*m)
winner = state.check_win(m)
# Backpropagation
result = False
if winner == WHITE_PIECE:
result = True # AI is WHITE
while node:
node.update(result)
node = node.parent
if time_limit and (time.time() - start_time) >= time_limit:
break
# Return the move with the most visits
best_move = None
best_visits = -1
for child in root.children:
if child.visits > best_visits:
best_visits = child.visits
best_move = child.move
return best_move
def draw_grid():
for i in range(ROWS):
pygame.draw.line(screen, LINE_COLOR, (BORDER, BORDER + i * GAP),
(BORDER + (COLS-1)*GAP, BORDER + i * GAP))
pygame.draw.line(screen, LINE_COLOR, (BORDER + i * GAP, BORDER),
(BORDER + i * GAP, BORDER + (ROWS-1)*GAP))
def draw_pieces(board):
for r in range(ROWS):
for c in range(COLS):
if board[r][c] != EMPTY:
center = (BORDER + c * GAP, BORDER + r * GAP)
if board[r][c] == BLACK_PIECE:
pygame.draw.circle(screen, BLACK, center, GAP//2 - 2)
else:
pygame.draw.circle(screen, WHITE, center, GAP//2 -2)
pygame.draw.circle(screen, BLACK, center, GAP//2 -2, 1)
def get_grid_pos(pos):
x, y = pos
if x < BORDER - GAP//2 or y < BORDER - GAP//2:
return None
grid_x = int(round((x - BORDER) / GAP))
grid_y = int(round((y - BORDER) / GAP))
if 0 <= grid_x < COLS and 0 <= grid_y < ROWS:
return (grid_y, grid_x)
return None
def main():
game_state = GameState()
running = True
ai_thinking = False
winner = False
last_move = (None, None)
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN and not ai_thinking and not winner:
if game_state.turn == BLACK_PIECE:
pos = pygame.mouse.get_pos()
move = get_grid_pos(pos)
if move and game_state.board[move[0]][move[1]] == EMPTY:
game_state.make_move(*move)
last_move = move
result = game_state.check_win(move)
if result:
winner = result
elif game_state.turn == WHITE_PIECE:
# AI's turn
ai_thinking = True
pygame.display.set_caption("Gobang with MCTS AI - AI Thinking...")
pygame.display.flip()
# AI move
ai_move = None
root = MCTSNode(deepcopy(game_state))
ai_move = MCTS(root, iter_limit=1000, time_limit=1.0)
if ai_move:
game_state.make_move(*ai_move)
last_move = ai_move
result = game_state.check_win(ai_move)
if result:
winner = result
ai_thinking = False
pygame.display.set_caption("Gobang with MCTS AI")
# Drawing
screen.fill(BG_COLOR)
draw_grid()
draw_pieces(game_state.board)
# Highlight last move
if last_move != (None, None):
r, c = last_move
center = (BORDER + c * GAP, BORDER + r * GAP)
pygame.draw.circle(screen, RED, center, GAP//2 -2, 2)
# Display winner
if winner:
text = "White Wins!" if winner == WHITE_PIECE else "Black Wins!"
img = FONT.render(text, True, RED)
screen.blit(img, (WIDTH//2 - img.get_width()//2, BORDER//2))
# Optionally, you can reset the game after a win
# For simplicity, we keep it static
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()