use pygame to write a Gobang game, including against AI mode and AI vs AI mode
- User
use pygame to write a Gobang game, including against AI mode and AI vs AI mode
- Assistant
use pygame to write a Gobang game, including against AI mode and AI vs AI mode
Creating a Gobang (Gomoku) game with both Human vs. AI and AI vs. AI modes using Pygame involves several steps:
Below is a comprehensive implementation of Gobang using Pygame. The code is well-commented to help you understand each part.
First, ensure that Pygame is installed. You can install it using pip:
pip install pygame
import pygame
import sys
import math
import random
import time
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 800, 800
ROWS, COLS = 15, 15
SQUARE_SIZE = WIDTH // COLS
# Colors
BG_COLOR = (245, 222, 179)
LINE_COLOR = (0, 0, 0)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
# Initialize screen
screen = pygame.display.set_mode((WIDTH, HEIGHT + 100))
pygame.display.set_caption('Gobang (Gomoku)')
# Fonts
font = pygame.font.SysFont(None, 40)
small_font = pygame.font.SysFont(None, 30)
class Gobang:
def __init__(self):
self.board = [['' for _ in range(COLS)] for _ in range(ROWS)]
self.current_player = 'B' # 'B' for Black, 'W' for White
self.game_over = False
self.winner = None
self.ai_enabled = True
self.ai_mode = None # 'HvAI' or 'AIvAI'
def reset(self):
self.__init__()
def make_move(self, row, col):
if self.board[row][col] == '' and not self.game_over:
self.board[row][col] = self.current_player
if self.check_win(row, col):
self.game_over = True
self.winner = self.current_player
else:
self.current_player = 'W' if self.current_player == 'B' else 'B'
def check_win(self, row, col):
def count(direction):
dr, dc = direction
r, c = row + dr, col + dc
cnt = 0
while 0 <= r < ROWS and 0 <= c < COLS and self.board[r][c] == self.current_player:
cnt += 1
r += dr
c += dc
return cnt
directions = [ (1,0), (0,1), (1,1), (1,-1) ]
for direction in directions:
cnt = 1
cnt += count(direction)
cnt += count((-direction[0], -direction[1]))
if cnt >= 5:
return True
return False
def is_full(self):
for row in self.board:
for cell in row:
if cell == '':
return False
return True
def get_valid_moves(self):
moves = []
for r in range(ROWS):
for c in range(COLS):
if self.board[r][c] == '':
# To optimize, consider only cells near existing stones
for dr in range(-2, 3):
for dc in range(-2, 3):
nr, nc = r + dr, c + dc
if 0 <= nr < ROWS and 0 <= nc < COLS:
if self.board[nr][nc] != '':
moves.append((r, c))
break
else:
continue
break
if not moves:
# If board is empty
moves = [(ROWS//2, COLS//2)]
return moves
def ai_move(self, player):
# Simple AI: Choose the best move based on a basic heuristic
best_score = -math.inf
best_move = None
for move in self.get_valid_moves():
r, c = move
self.board[r][c] = player
score = self.evaluate(player)
self.board[r][c] = ''
if score > best_score:
best_score = score
best_move = move
if best_move:
self.make_move(*best_move)
def evaluate(self, player):
# Very basic evaluation function
opponent = 'W' if player == 'B' else 'B'
score = 0
for row in range(ROWS):
for col in range(COLS):
if self.board[row][col] == player:
score += self.score_position(row, col, player)
elif self.board[row][col] == opponent:
score -= self.score_position(row, col, opponent)
return score
def score_position(self, row, col, player):
# Assign scores based on potential lines
directions = [ (1,0), (0,1), (1,1), (1,-1) ]
score = 0
for dr, dc in directions:
count = 1
# Check in positive direction
r, c = row + dr, col + dc
while 0 <= r < ROWS and 0 <= c < COLS and self.board[r][c] == player:
count += 1
r += dr
c += dc
# Check in negative direction
r, c = row - dr, col - dc
while 0 <= r < ROWS and 0 <= c < COLS and self.board[r][c] == player:
count += 1
r -= dr
c -= dc
if count >= 5:
score += 1000
elif count == 4:
score += 100
elif count == 3:
score += 10
elif count == 2:
score += 1
return score
def draw_grid():
for i in range(ROWS):
pygame.draw.line(screen, LINE_COLOR, (SQUARE_SIZE, SQUARE_SIZE + i * SQUARE_SIZE),
(WIDTH - SQUARE_SIZE, SQUARE_SIZE + i * SQUARE_SIZE), 2)
pygame.draw.line(screen, LINE_COLOR, (SQUARE_SIZE + i * SQUARE_SIZE, SQUARE_SIZE),
(SQUARE_SIZE + i * SQUARE_SIZE, HEIGHT - SQUARE_SIZE), 2)
def draw_stones(game):
for r in range(ROWS):
for c in range(COLS):
if game.board[r][c] != '':
center = (SQUARE_SIZE + c * SQUARE_SIZE, SQUARE_SIZE + r * SQUARE_SIZE)
if game.board[r][c] == 'B':
pygame.draw.circle(screen, BLACK, center, SQUARE_SIZE//2 - 4)
else:
pygame.draw.circle(screen, WHITE, center, SQUARE_SIZE//2 - 4)
pygame.draw.circle(screen, BLACK, center, SQUARE_SIZE//2 - 4, 1)
def draw_status(game):
if game.game_over:
if game.winner == 'B':
text = font.render("Black Wins!", True, GREEN)
else:
text = font.render("White Wins!", True, GREEN)
elif game.is_full():
text = font.render("Draw!", True, GREEN)
else:
turn = "Black" if game.current_player == 'B' else "White"
text = font.render(f"{turn}'s Turn", True, GREEN)
screen.blit(text, (50, HEIGHT + 10))
def draw_buttons(selected_mode):
# Buttons for selecting mode and reset
pygame.draw.rect(screen, (200, 200, 200), (600, HEIGHT + 10, 150, 40))
pygame.draw.rect(screen, (200, 200, 200), (600, HEIGHT + 60, 150, 40))
reset_button = font.render("Reset", True, BLACK)
screen.blit(reset_button, (650, HEIGHT + 15))
# Mode buttons
pygame.draw.rect(screen, (200, 200, 200), (300, HEIGHT + 10, 250, 40))
pygame.draw.rect(screen, (200, 200, 200), (300, HEIGHT + 60, 250, 40))
hvai_text = small_font.render("Human vs AI", True, BLACK)
aiva_text = small_font.render("AI vs AI", True, BLACK)
screen.blit(hvai_text, (320, HEIGHT + 15))
screen.blit(aiva_text, (320, HEIGHT + 65))
# Highlight selected mode
if selected_mode == 'HvAI':
pygame.draw.rect(screen, GREEN, (300, HEIGHT + 10, 250, 40), 3)
elif selected_mode == 'AIvAI':
pygame.draw.rect(screen, GREEN, (300, HEIGHT + 60, 250, 40), 3)
# Reset button highlight
pygame.draw.rect(screen, GREEN, (600, HEIGHT + 10, 150, 40), 3)
def get_clicked_button(pos):
x, y = pos
if 300 <= x <= 550 and HEIGHT +10 <= y <= HEIGHT + 50:
return 'HvAI'
if 300 <= x <= 550 and HEIGHT +60 <= y <= HEIGHT + 100:
return 'AIvAI'
if 600 <= x <= 750 and HEIGHT +10 <= y <= HEIGHT + 50:
return 'Reset'
return None
def main():
clock = pygame.time.Clock()
game = Gobang()
running = True
while running:
screen.fill(BG_COLOR)
draw_grid()
draw_stones(game)
draw_status(game)
draw_buttons(game.ai_mode)
pygame.display.flip()
if game.ai_mode == 'HvAI' and game.current_player == 'W' and game.ai_enabled and not game.game_over:
# AI's turn
game.ai_move('W')
elif game.ai_mode == 'AIvAI' and game.ai_enabled and not game.game_over:
# AI vs AI Mode: Alternate between AIs
game.ai_move(game.current_player)
# Add delay for visibility
pygame.display.flip()
time.sleep(0.5)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN and not game.game_over:
pos = pygame.mouse.get_pos()
if pos[1] < HEIGHT:
col = pos[0] // SQUARE_SIZE
row = pos[1] // SQUARE_SIZE
if game.ai_mode == 'HvAI' and game.current_player == 'B':
game.make_move(row, col)
else:
# Clicked in the button area
button = get_clicked_button(pos)
if button == 'HvAI':
game.ai_mode = 'HvAI'
game.reset()
elif button == 'AIvAI':
game.ai_mode = 'AIvAI'
game.reset()
elif button == 'Reset':
game.reset()
clock.tick(60)
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Game Initialization:
current_player is set to 'B' (Black) to start the game.ai_mode determines the game mode: 'HvAI' for Human vs. AI and 'AIvAI' for AI vs. AI.Drawing Functions:
draw_grid(): Draws the Gobang grid.draw_stones(game): Draws the stones (black or white) based on the current game state.draw_status(game): Displays the current status (whose turn it is, win, or draw).draw_buttons(selected_mode): Draws buttons for selecting game modes and resetting the game.Game Logic:
make_move(row, col): Places a stone on the board if the cell is empty and checks for a win.check_win(row, col): Checks if placing a stone at (row, col) results in a win by checking all four directions.get_valid_moves(): Returns all valid moves. For optimization, it considers only cells near existing stones.ai_move(player): The AI evaluates all valid moves and selects the best one based on a simple heuristic.evaluate(player): A basic heuristic that scores the board based on potential lines.score_position(row, col, player): Assigns scores to positions to help the AI decide the best move.Event Handling:
Game Loop:
The provided AI is relatively basic and uses a simple heuristic to evaluate moves. For a more competitive AI, consider implementing more advanced algorithms such as Minimax with Alpha-Beta Pruning, Monte Carlo Tree Search (MCTS), or using machine learning techniques.
Additionally, you can enhance the user interface by adding features like:
gobang.py.pip install pygame).python gobang.py
Selecting Game Mode:
Placing Stones (Human vs. AI Mode):
Enjoy playing Gobang!
Not yet included in a published release.