import pygame import sys import math import random import time import threading…
- User
import pygame import sys import math import random import time import threading
Initialize pygame
pygame.init()
Define colors
WHITE = (255, 255, 255) BLACK = (0, 0, 0) GRAY = (185, 185, 185) RED = (255, 0, 0) BLUE = (0, 0, 255) GREEN = (0, 255, 0)
Set screen size
BOARD_SIZE = 13 CELL_SIZE = 40 MARGIN = 20 WIDTH = CELL_SIZE * (BOARD_SIZE - 1) + 2 * MARGIN HEIGHT = WIDTH + 100 # Reserved area below for display
screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Gomoku')
FONT = pygame.font.SysFont(None, 36) SMALL_FONT = pygame.font.SysFont(None, 24)
Board data structure
board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
Game state
mode = None # None, 'PVP', 'PVC' player_color = None # 1: Black, 2: White current_player = 1 # 1: Black, 2: White game_over = False winner = None
AI variables
ai_thinking = False ai_move_result = None ai_start_time = None ai_time_limit = 5 # seconds ai_countdown = ai_time_limit ai_lock = threading.Lock()
def draw_board(): screen.fill(GRAY) # Draw grid for i in range(BOARD_SIZE): # Draw horizontal lines pygame.draw.line(screen, BLACK, (MARGIN, MARGIN + i * CELL_SIZE), (WIDTH - MARGIN, MARGIN + i * CELL_SIZE), 1) # Draw vertical lines pygame.draw.line(screen, BLACK, (MARGIN + i * CELL_SIZE, MARGIN), (MARGIN + i * CELL_SIZE, WIDTH - MARGIN), 1) # Draw star points star_points = [3, 6, 9] for i in star_points: for j in star_points: pygame.draw.circle(screen, BLACK, (MARGIN + i * CELL_SIZE, MARGIN + j * CELL_SIZE), 5)
# Draw pieces for row in range(BOARD_SIZE): for col in range(BOARD_SIZE): if board[row][col] != 0: center = (MARGIN + col * CELL_SIZE, MARGIN + row * CELL_SIZE) if board[row][col] == 1: pygame.draw.circle(screen, BLACK, center, CELL_SIZE//2 - 2) else: pygame.draw.circle(screen, WHITE, center, CELL_SIZE//2 - 2) pygame.draw.circle(screen, BLACK, center, CELL_SIZE//2 - 2, 1)def get_cell(pos): x, y = pos if x < MARGIN - CELL_SIZE//2 or x > WIDTH - MARGIN + CELL_SIZE//2 or
y < MARGIN - CELL_SIZE//2 or y > WIDTH - MARGIN + CELL_SIZE//2: return None col = int(round((x - MARGIN) / CELL_SIZE)) row = int(round((y - MARGIN) / CELL_SIZE)) if 0 <= row < BOARD_SIZE and 0 <= col < BOARD_SIZE: return row, col return Nonedef is_winner(r, c): color = board[r][c] directions = [(1,0), (0,1), (1,1), (1,-1)] for dr, dc in directions: count = 1 # Count in the positive direction i = 1 while True: nr = r + dr * i nc = c + dc * i if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE and board[nr][nc] == color: count += 1 i += 1 else: break # Count in the negative direction i = 1 while True: nr = r - dr * i nc = c - dc * i if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE and board[nr][nc] == color: count += 1 i += 1 else: break if count >= 5: return color return None
def draw_info(text, countdown=None): pygame.draw.rect(screen, GRAY, (0, WIDTH, WIDTH, HEIGHT - WIDTH)) img = FONT.render(text, True, RED) screen.blit(img, (MARGIN, WIDTH + 30)) if countdown is not None: countdown_img = SMALL_FONT.render(f"AI thinking time left: {countdown} sec", True, BLUE) screen.blit(countdown_img, (WIDTH - 300, WIDTH + 60))
def reset_game(): global board, current_player, game_over, winner, ai_move_result, ai_thinking, ai_countdown board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)] current_player = 1 game_over = False winner = None ai_move_result = None ai_thinking = False ai_countdown = ai_time_limit
Enhanced Evaluation Function
def evaluate(board_state): # Simple heuristic: number of open sequences patterns = { 'five': 100000, 'open_four': 10000, 'four': 1000, 'open_three': 1000, 'three': 100, 'open_two': 100, 'two': 10 } score = 0 for r in range(BOARD_SIZE): for c in range(BOARD_SIZE): if board_state[r][c] != 0: color = board_state[r][c] for dr, dc in [(1,0), (0,1), (1,1), (1,-1)]: cnt, open_cnt = count_sequence(board_state, r, c, dr, dc, color) if cnt >=5: score += patterns['five'] elif cnt ==4 and open_cnt ==2: score += patterns['open_four'] elif cnt ==4 and open_cnt ==1: score += patterns['four'] elif cnt ==3 and open_cnt ==2: score += patterns['open_three'] elif cnt ==3 and open_cnt ==1: score += patterns['three'] elif cnt ==2 and open_cnt ==2: score += patterns['open_two'] elif cnt ==2 and open_cnt ==1: score += patterns['two'] return score
def count_sequence(board_state, r, c, dr, dc, color): count = 1 open_ends = 0
# Forward direction i = 1 while True: nr = r + dr * i nc = c + dc * i if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE and board_state[nr][nc] == color: count += 1 i += 1 else: if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE and board_state[nr][nc] == 0: open_ends += 1 break # Backward direction i = 1 while True: nr = r - dr * i nc = c - dc * i if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE and board_state[nr][nc] == color: count += 1 i += 1 else: if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE and board_state[nr][nc] == 0: open_ends += 1 break return count, open_endsdef minimax(board_state, depth, maximizing, alpha, beta, start_time, time_limit): if depth == 0 or check_terminal(board_state): return evaluate(board_state), None
if time.time() - start_time > time_limit: return evaluate(board_state), None best_move = None possible_moves = get_possible_moves(board_state) # Move ordering: prioritize center and recent moves possible_moves = sorted(possible_moves, key=lambda move: -distance_from_center(move)) if maximizing: max_eval = -math.inf for move in possible_moves: new_board = [row[:] for row in board_state] new_board[move[0]][move[1]] = 2 eval, _ = minimax(new_board, depth -1, False, alpha, beta, start_time, time_limit) if eval > max_eval: max_eval = eval best_move = move alpha = max(alpha, eval) if beta <= alpha: break return max_eval, best_move else: min_eval = math.inf for move in possible_moves: new_board = [row[:] for row in board_state] new_board[move[0]][move[1]] = 1 eval, _ = minimax(new_board, depth -1, True, alpha, beta, start_time, time_limit) if eval < min_eval: min_eval = eval best_move = move beta = min(beta, eval) if beta <= alpha: break return min_eval, best_movedef distance_from_center(move): center = BOARD_SIZE // 2 return math.hypot(move[0] - center, move[1] - center)
def check_terminal(board_state): for r in range(BOARD_SIZE): for c in range(BOARD_SIZE): if board_state[r][c] != 0: if evaluate_win(board_state, r, c): return True # Draw for row in board_state: if 0 in row: return False return True
def evaluate_win(board_state, r, c): color = board_state[r][c] directions = [(1,0), (0,1), (1,1), (1,-1)] for dr, dc in directions: count = 1 i = 1 while True: nr = r + dr * i nc = c + dc * i if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE and board_state[nr][nc] == color: count +=1 i +=1 else: break i =1 while True: nr = r - dr * i nc = c - dc * i if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE and board_state[nr][nc] == color: count +=1 i +=1 else: break if count >=5: return True return False
def get_possible_moves(board_state): # To optimize, consider only moves near existing pieces moves = set() for r in range(BOARD_SIZE): for c in range(BOARD_SIZE): if board_state[r][c] !=0: for dr in range(-2,3): for dc in range(-2,3): nr = r + dr nc = c + dc if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE and board_state[nr][nc] ==0: moves.add((nr, nc)) if not moves: # If board is empty, choose center return [(BOARD_SIZE//2, BOARD_SIZE//2)] return list(moves)
def ai_move_minimax(): global ai_move_result, ai_thinking, ai_countdown start_time = time.time() best_move = None depth = 1 best_score = -math.inf while True: if time.time() - start_time >= ai_time_limit: break score, move = minimax(board, depth, True, -math.inf, math.inf, start_time, ai_time_limit) if move is not None: best_move = move best_score = score else: break depth +=1 with ai_lock: ai_move_result = best_move ai_thinking = False
def start_ai_thread(): global ai_thinking, ai_move_result, ai_start_time, ai_countdown ai_thinking = True ai_move_result = None ai_start_time = time.time() ai_countdown = ai_time_limit threading.Thread(target=ai_move_minimax, daemon=True).start()
def main_menu(): menu = True while menu: screen.fill(GRAY) title = FONT.render('Gomoku Game', True, BLUE) screen.blit(title, (WIDTH//2 - title.get_width()//2, HEIGHT//2 - 150))
pvp_text = FONT.render('Player vs Player', True, BLACK) pvc_text = FONT.render('Player vs AI', True, BLACK) screen.blit(pvp_text, (WIDTH//2 - pvp_text.get_width()//2, HEIGHT//2 - 50)) screen.blit(pvc_text, (WIDTH//2 - pvc_text.get_width()//2, HEIGHT//2 + 10)) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: mx, my = pygame.mouse.get_pos() if HEIGHT//2 -50 <= my <= HEIGHT//2 -50 + pvp_text.get_height(): return 'PVP' elif HEIGHT//2 +10 <= my <= HEIGHT//2 +10 + pvc_text.get_height(): return 'PVC'def choose_color(): choosing = True while choosing: screen.fill(GRAY) prompt = FONT.render('Choose Your Color', True, BLUE) screen.blit(prompt, (WIDTH//2 - prompt.get_width()//2, HEIGHT//2 - 100))
black_text = FONT.render('Black', True, BLACK) white_text = FONT.render('White', True, WHITE) pygame.draw.rect(screen, BLACK, (WIDTH//2 - 100, HEIGHT//2 - 40, 80, 40)) pygame.draw.rect(screen, WHITE, (WIDTH//2 +20, HEIGHT//2 -40, 80, 40)) screen.blit(black_text, (WIDTH//2 - 90, HEIGHT//2 -35)) screen.blit(white_text, (WIDTH//2 +30, HEIGHT//2 -35)) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: mx, my = pygame.mouse.get_pos() if WIDTH//2 -100 <= mx <= WIDTH//2 -20 and HEIGHT//2 -40 <= my <= HEIGHT//2: return 1 # Black elif WIDTH//2 +20 <= mx <= WIDTH//2 +100 and HEIGHT//2 -40 <= my <= HEIGHT//2: return 2 # Whitedef main(): global mode, player_color, current_player, game_over, winner, ai_thinking, ai_move_result, ai_countdown clock = pygame.time.Clock()
mode = main_menu() if mode == 'PVC': player_color = choose_color() ai_player = 2 if player_color ==1 else 1 draw_board() if mode == 'PVC' and player_color ==2: # AI starts first start_ai_thread() while True: draw_board() countdown_display = None if game_over: if winner ==1: msg = "Black Wins!" elif winner ==2: msg = "White Wins!" else: msg = "Draw!" draw_info(msg + " Click to Restart") else: if mode == 'PVP': turn = 'Black' if current_player ==1 else 'White' draw_info(f"{turn}'s Turn") else: if current_player == player_color: turn = 'Your Turn' else: if ai_thinking: elapsed = time.time() - ai_start_time remaining = max(0, ai_time_limit - int(elapsed)) countdown_display = remaining # Check if time exceeded if elapsed >= ai_time_limit and ai_thinking: # Time out, make best available move if ai_move_result is None: # If AI hasn't returned any move, make random move empty = [(r, c) for r in range(BOARD_SIZE) for c in range(BOARD_SIZE) if board[r][c] == 0] if empty: move = random.choice(empty) board[move[0]][move[1]] = ai_player winner = is_winner(move[0], move[1]) if winner: game_over = True current_player = player_color else: # Apply AI move move = ai_move_result if move: board[move[0]][move[1]] = ai_player winner = is_winner(move[0], move[1]) if winner: game_over = True current_player = player_color ai_thinking = False elif not ai_thinking and ai_move_result is not None: # Apply AI move move = ai_move_result if move: board[move[0]][move[1]] = ai_player winner = is_winner(move[0], move[1]) if winner: game_over = True current_player = player_color ai_move_result = None turn = 'AI is Thinking...' draw_info(turn, countdown_display) pygame.display.flip() if game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: reset_game() mode = main_menu() if mode == 'PVC': player_color = choose_color() ai_player = 2 if player_color ==1 else 1 draw_board() if mode == 'PVC' and player_color ==2: # AI starts first start_ai_thread() continue else: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() cell = get_cell(pos) if cell and board[cell[0]][cell[1]] ==0: if mode == 'PVP': board[cell[0]][cell[1]] = current_player winner = is_winner(cell[0], cell[1]) if winner: game_over = True current_player = 2 if current_player ==1 else 1 else: if current_player == player_color: board[cell[0]][cell[1]] = current_player winner = is_winner(cell[0], cell[1]) if winner: game_over = True else: current_player = ai_player # AI's turn start_ai_thread() # Update AI countdown and handle AI move if mode == 'PVC' and current_player == ai_player and not game_over: if not ai_thinking and ai_move_result is None: # Start AI thinking start_ai_thread() clock.tick(30)if name == "main": main()
1.写一个五子棋游戏,13*13,双人对弈,用python写,代码生产在一起,可以一次性运行bug free,用鼠标点击交互,黑白子UI,pygame里显示中文乱码全部改成英文 2.有双人对弈模式,和人机对战,选择模式 不用键盘 弹出方框用鼠标选择 3.人机对战,玩家可选黑白,完成人机对战五子棋AI,人机对战AI要厉害,最大化胜率赢过玩家,思考最长时间5秒并显示倒计时
- Assistant
Here is a complete Python script using Pygame to implement a 13x13 Gomoku game with the features you requested:
import pygame import sys import math import threading import time import random # Initialize pygame pygame.init() # Set up display BOARD_SIZE = 13 CELL_SIZE = 40 MARGIN = 40 SCREEN_SIZE = CELL_SIZE * (BOARD_SIZE - 1) + MARGIN * 2 INFO_HEIGHT = 100 SCREEN_HEIGHT = SCREEN_SIZE + INFO_HEIGHT screen = pygame.display.set_mode((SCREEN_SIZE, SCREEN_HEIGHT)) pygame.display.set_caption("Gomoku") # Load fonts FONT = pygame.font.SysFont(None, 36) SMALL_FONT = pygame.font.SysFont(None, 24) # Define colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) BOARD_COLOR = (185, 122, 87) LINE_COLOR = (0, 0, 0) TEXT_COLOR = (0, 0, 0) HIGHLIGHT_COLOR = (255, 0, 0) INFO_BG_COLOR = (192, 192, 192) # Game variables board = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)] current_player = 1 # 1 for Black, 2 for White game_over = False winner = None mode = None # 'PVP' or 'PVC' player_color = None # 1 for Black, 2 for White ai_thinking = False ai_move_result = None ai_start_time = None ai_time_limit = 5 # in seconds clock = pygame.time.Clock() ai_thread_lock = threading.Lock() def draw_board(): screen.fill(BOARD_COLOR) # Draw grid lines for i in range(BOARD_SIZE): x = MARGIN + i * CELL_SIZE pygame.draw.line(screen, LINE_COLOR, (MARGIN, x - MARGIN + CELL_SIZE), (SCREEN_SIZE - MARGIN, x - MARGIN + CELL_SIZE), 1) pygame.draw.line(screen, LINE_COLOR, (x, MARGIN), (x, SCREEN_SIZE - MARGIN), 1) # Draw star points star_points = [3, 6, 9] for i in star_points: for j in star_points: x = MARGIN + i * CELL_SIZE y = MARGIN + j * CELL_SIZE pygame.draw.circle(screen, LINE_COLOR, (x, y), 4) # Draw pieces for row in range(BOARD_SIZE): for col in range(BOARD_SIZE): piece = board[row][col] if piece != 0: x = MARGIN + col * CELL_SIZE y = MARGIN + row * CELL_SIZE center = (x, y) if piece == 1: pygame.draw.circle(screen, BLACK, center, CELL_SIZE // 2 - 2) else: pygame.draw.circle(screen, WHITE, center, CELL_SIZE // 2 - 2) pygame.draw.circle(screen, BLACK, center, CELL_SIZE // 2 - 2, 1) def get_cell(pos): x, y = pos if x < MARGIN - CELL_SIZE // 2 or x > SCREEN_SIZE - MARGIN + CELL_SIZE // 2 or \ y < MARGIN - CELL_SIZE // 2 or y > SCREEN_SIZE - MARGIN + CELL_SIZE // 2: return None col = int(round((x - MARGIN) / CELL_SIZE)) row = int(round((y - MARGIN) / CELL_SIZE)) if 0 <= row < BOARD_SIZE and 0 <= col < BOARD_SIZE: return row, col return None def is_winner(r, c): color = board[r][c] directions = [(1, 0), (0, 1), (1, 1), (1, -1)] for dr, dc in directions: count = 1 # Positive direction i = 1 while True: nr = r + dr * i nc = c + dc * i if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE and board[nr][nc] == color: count += 1 i += 1 else: break # Negative direction i = 1 while True: nr = r - dr * i nc = c - dc * i if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE and board[nr][nc] == color: count += 1 i += 1 else: break if count >= 5: return color return None def draw_info(text, countdown=None): pygame.draw.rect(screen, INFO_BG_COLOR, (0, SCREEN_SIZE, SCREEN_SIZE, INFO_HEIGHT)) img = FONT.render(text, True, TEXT_COLOR) screen.blit(img, (MARGIN, SCREEN_SIZE + 20)) if countdown is not None: time_text = SMALL_FONT.render(f"AI Thinking Time Left: {countdown} sec", True, HIGHLIGHT_COLOR) screen.blit(time_text, (SCREEN_SIZE - 300, SCREEN_SIZE + 50)) def reset_game(): global board, current_player, game_over, winner, ai_thinking, ai_move_result board = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)] current_player = 1 # Black starts game_over = False winner = None ai_thinking = False ai_move_result = None # AI Functions def evaluate(board_state, player): # Simple heuristic evaluation function opponent = 2 if player == 1 else 1 player_score = get_score(board_state, player) opponent_score = get_score(board_state, opponent) return player_score - opponent_score def get_score(board_state, player): patterns = { 'five': 100000, 'open_four': 10000, 'four': 1000, 'open_three': 1000, 'three': 100, 'open_two': 100, 'two': 10, } score = 0 for row in range(BOARD_SIZE): for col in range(BOARD_SIZE): if board_state[row][col] == player: for dr, dc in [(1, 0), (0, 1), (1, 1), (1, -1)]: cnt, open_ends = count_sequence(board_state, row, col, dr, dc, player) if cnt >= 5: score += patterns['five'] elif cnt == 4 and open_ends == 2: score += patterns['open_four'] elif cnt == 4 and open_ends == 1: score += patterns['four'] elif cnt == 3 and open_ends == 2: score += patterns['open_three'] elif cnt == 3 and open_ends == 1: score += patterns['three'] elif cnt == 2 and open_ends == 2: score += patterns['open_two'] elif cnt == 2 and open_ends == 1: score += patterns['two'] return score def count_sequence(board_state, r, c, dr, dc, player): count = 1 open_ends = 0 # Positive direction i = 1 while True: nr = r + dr * i nc = c + dc * i if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE: if board_state[nr][nc] == player: count += 1 i += 1 elif board_state[nr][nc] == 0: open_ends += 1 break else: break else: break # Negative direction i = 1 while True: nr = r - dr * i nc = c - dc * i if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE: if board_state[nr][nc] == player: count += 1 i += 1 elif board_state[nr][nc] == 0: open_ends += 1 break else: break else: break return count, open_ends def get_possible_moves(board_state): moves = set() for row in range(BOARD_SIZE): for col in range(BOARD_SIZE): if board_state[row][col] != 0: for dr in range(-2, 3): for dc in range(-2, 3): nr = row + dr nc = col + dc if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE: if board_state[nr][nc] == 0: moves.add((nr, nc)) if not moves: return [(BOARD_SIZE // 2, BOARD_SIZE // 2)] return list(moves) def minimax(board_state, depth, alpha, beta, maximizing_player, start_time, time_limit, player): if depth == 0 or game_end(board_state) or (time.time() - start_time) >= time_limit: return evaluate(board_state, ai_player), None possible_moves = get_possible_moves(board_state) best_move = None if maximizing_player: max_eval = -math.inf for move in possible_moves: row, col = move new_board = [row.copy() for row in board_state] new_board[row][col] = player eval_score, _ = minimax(new_board, depth - 1, alpha, beta, False, start_time, time_limit, opponent(player)) if eval_score > max_eval: max_eval = eval_score best_move = move alpha = max(alpha, eval_score) if beta <= alpha: break return max_eval, best_move else: min_eval = math.inf for move in possible_moves: row, col = move new_board = [row.copy() for row in board_state] new_board[row][col] = player eval_score, _ = minimax(new_board, depth - 1, alpha, beta, True, start_time, time_limit, opponent(player)) if eval_score < min_eval: min_eval = eval_score best_move = move beta = min(beta, eval_score) if beta <= alpha: break return min_eval, best_move def game_end(board_state): for r in range(BOARD_SIZE): for c in range(BOARD_SIZE): if board_state[r][c] != 0 and is_winner_state(board_state, r, c): return True return False def is_winner_state(board_state, r, c): color = board_state[r][c] directions = [(1, 0), (0, 1), (1, 1), (1, -1)] for dr, dc in directions: count = 1 # Positive direction i = 1 while True: nr = r + dr * i nc = c + dc * i if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE and board_state[nr][nc] == color: count += 1 i += 1 else: break # Negative direction i = 1 while True: nr = r - dr * i nc = c - dc * i if 0 <= nr < BOARD_SIZE and 0 <= nc < BOARD_SIZE and board_state[nr][nc] == color: count += 1 i += 1 else: break if count >= 5: return True return False def opponent(player): return 2 if player == 1 else 1 def ai_move(): global ai_move_result, ai_thinking start_time = time.time() depth = 1 best_move = None while True: if time.time() - start_time >= ai_time_limit: break eval_score, move = minimax(board, depth, -math.inf, math.inf, True, start_time, ai_time_limit, ai_player) if move: best_move = move depth += 1 with ai_thread_lock: ai_move_result = best_move ai_thinking = False def start_ai_thread(): global ai_thinking, ai_move_result, ai_start_time ai_thinking = True ai_move_result = None ai_start_time = time.time() threading.Thread(target=ai_move, daemon=True).start() def main_menu(): global mode selecting = True while selecting: screen.fill(INFO_BG_COLOR) title = FONT.render("Gomoku", True, TEXT_COLOR) pvp_text = FONT.render("Player vs Player", True, TEXT_COLOR) pvc_text = FONT.render("Player vs AI", True, TEXT_COLOR) screen.blit(title, ((SCREEN_SIZE - title.get_width()) // 2, SCREEN_HEIGHT // 2 - 150)) screen.blit(pvp_text, ((SCREEN_SIZE - pvp_text.get_width()) // 2, SCREEN_HEIGHT // 2 - 50)) screen.blit(pvc_text, ((SCREEN_SIZE - pvc_text.get_width()) // 2, SCREEN_HEIGHT // 2 + 10)) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: mx, my = pygame.mouse.get_pos() if SCREEN_HEIGHT // 2 - 50 <= my <= SCREEN_HEIGHT // 2 - 50 + pvp_text.get_height(): mode = 'PVP' selecting = False elif SCREEN_HEIGHT // 2 + 10 <= my <= SCREEN_HEIGHT // 2 + 10 + pvc_text.get_height(): mode = 'PVC' selecting = False def choose_color(): global player_color, ai_player choosing = True while choosing: screen.fill(INFO_BG_COLOR) prompt = FONT.render("Choose Your Color", True, TEXT_COLOR) black_text = FONT.render("Black", True, WHITE) white_text = FONT.render("White", True, BLACK) black_rect = pygame.Rect((SCREEN_SIZE // 2 - 100, SCREEN_HEIGHT // 2 - 40, 80, 40)) white_rect = pygame.Rect((SCREEN_SIZE // 2 + 20, SCREEN_HEIGHT // 2 - 40, 80, 40)) pygame.draw.rect(screen, BLACK, black_rect) pygame.draw.rect(screen, WHITE, white_rect) screen.blit(black_text, (SCREEN_SIZE // 2 - 90, SCREEN_HEIGHT // 2 - 35)) screen.blit(white_text, (SCREEN_SIZE // 2 + 30, SCREEN_HEIGHT // 2 - 35)) screen.blit(prompt, ((SCREEN_SIZE - prompt.get_width()) // 2, SCREEN_HEIGHT // 2 - 100)) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: mx, my = pygame.mouse.get_pos() if black_rect.collidepoint(mx, my): player_color = 1 ai_player = 2 choosing = False elif white_rect.collidepoint(mx, my): player_color = 2 ai_player = 1 choosing = False def main(): global current_player, game_over, winner, ai_thinking, ai_move_result reset_game() main_menu() if mode == 'PVC': choose_color() draw_board() if mode == 'PVC' and current_player == ai_player: start_ai_thread() while True: draw_board() if game_over: if winner == 1: msg = "Black Wins! Click to Restart." elif winner == 2: msg = "White Wins! Click to Restart." else: msg = "Draw! Click to Restart." draw_info(msg) else: if mode == 'PVP': player_text = "Black's Turn" if current_player == 1 else "White's Turn" draw_info(player_text) else: if current_player == player_color: draw_info("Your Turn") else: elapsed_time = int(time.time() - ai_start_time) remaining_time = max(ai_time_limit - elapsed_time, 0) draw_info("AI is Thinking...", remaining_time) if not ai_thinking and ai_move_result is not None: row, col = ai_move_result board[row][col] = ai_player if is_winner(row, col): winner = ai_player game_over = True else: current_player = player_color ai_move_result = None pygame.display.flip() if game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: reset_game() main() else: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN and mode == 'PVP': pos = pygame.mouse.get_pos() cell = get_cell(pos) if cell and board[cell[0]][cell[1]] == 0: board[cell[0]][cell[1]] = current_player if is_winner(cell[0], cell[1]): winner = current_player game_over = True else: current_player = opponent(current_player) elif event.type == pygame.MOUSEBUTTONDOWN and mode == 'PVC' and current_player == player_color: pos = pygame.mouse.get_pos() cell = get_cell(pos) if cell and board[cell[0]][cell[1]] == 0: board[cell[0]][cell[1]] = player_color if is_winner(cell[0], cell[1]): winner = player_color game_over = True else: current_player = ai_player start_ai_thread() clock.tick(30) if __name__ == "__main__": main()Instructions:
- Save the code to a file named
gomoku.py. - Ensure you have Pygame installed (
pip install pygame). - Run the script using
python gomoku.py.
Features:
-
Gomoku Game (13x13): The game board is initialized to a 13x13 grid, as per your request.
-
Two Game Modes:
- Player vs Player (PVP): Allows two players to play against each other on the same machine.
- Player vs Computer (PVC): Allows a single player to play against an AI opponent.
-
Mode Selection: A main menu is displayed at the start, allowing players to choose the game mode using the mouse.
-
Color Selection: In PVC mode, the player can choose to play as Black or White using the mouse.
-
Strong AI Opponent:
- The AI uses the Minimax algorithm with alpha-beta pruning for efficient decision-making.
- The AI evaluates moves up to a certain depth within the 5-second time limit.
- The AI aims to maximize its chances of winning against the player.
-
AI Time Limit and Countdown:
- The AI has a maximum of 5 seconds to make a move.
- A countdown timer is displayed while the AI is thinking.
- If the AI exceeds the time limit, it makes the best move calculated so far.
-
Mouse Interaction:
- All interactions are handled via mouse clicks.
- Players place stones by clicking on the desired intersection.
- Menus and options are selected using the mouse.
-
User Interface:
- The game board is displayed with clear grid lines and star points.
- Black and White stones are displayed as filled circles.
- Information regarding turns, wins, and prompts are displayed on the screen.
-
No Chinese Characters: All text and messages are in English to avoid character encoding issues with Pygame.
Note:
- The AI's strength depends on the depth it can search within the time limit.
- The script is designed to be run directly, and all functions are self-contained.
- Ensure threading is supported in your Python environment, as the AI runs in a separate thread.
Gameplay Controls:
- Starting the Game: Run the script and use the mouse to select the game mode and color (if applicable).
- Placing Stones: Click on the board to place your stone during your turn.
- Restarting the Game: After a game ends, click anywhere to restart.
Enjoy your game of Gomoku!
- Save the code to a file named