o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)
1.写一个五子棋游戏,13*13,双人对弈,用python写,代码生产在一起,可以一次性运行bug free,用鼠标点击交互,黑白子UI,pygame里显示中文乱码全部改成英文…
- User
1.写一个五子棋游戏,13*13,双人对弈,用python写,代码生产在一起,可以一次性运行bug free,用鼠标点击交互,黑白子UI,pygame里显示中文乱码全部改成英文 2.有双人对弈模式,和人机对战,选择模式 不用键盘 弹出方框用鼠标选择 3.人机对战,玩家可选黑白,完成人机对战五子棋AI,AI实现使用了 Minimax 算法,结合简单的评估函数,搜索深度设置为3可调整, 思考最长时间5秒并显示倒计时
- Assistant
Here's a Python implementation of a 13x13 Gomoku game using Pygame. The game includes both two-player mode and human vs. AI mode with a Minimax algorithm for the AI. The AI search depth is adjustable, and it displays a 5-second countdown during its turn.
import pygame import sys import time import threading # Initialize Pygame pygame.init() screen_size = 560 margin = 20 grid_size = 13 cell_size = (screen_size - 2 * margin) // (grid_size - 1) screen = pygame.display.set_mode((screen_size, screen_size)) pygame.display.set_caption('Gomoku') font = pygame.font.SysFont(None, 24) # Colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) WOOD = (205, 133, 63) BLUE = (0, 0, 255) # Board representation EMPTY = 0 BLACK_STONE = 1 WHITE_STONE = 2 # Game state variables board = [[EMPTY for _ in range(grid_size)] for _ in range(grid_size)] current_player = BLACK_STONE game_over = False winner = None ai_enabled = False ai_player = WHITE_STONE max_depth = 3 thinking = False countdown = 5 # Draw the board def draw_board(): screen.fill(WOOD) # Draw grid lines for i in range(grid_size): pygame.draw.line(screen, BLACK, (margin, margin + i * cell_size), (screen_size - margin, margin + i * cell_size)) pygame.draw.line(screen, BLACK, (margin + i * cell_size, margin), (margin + i * cell_size, screen_size - margin)) # Draw stones for y in range(grid_size): for x in range(grid_size): if board[y][x] == BLACK_STONE: pygame.draw.circle(screen, BLACK, (margin + x * cell_size, margin + y * cell_size), cell_size // 2 - 2) elif board[y][x] == WHITE_STONE: pygame.draw.circle(screen, WHITE, (margin + x * cell_size, margin + y * cell_size), cell_size // 2 - 2) # Show countdown timer if AI is thinking if thinking: timer_text = font.render(f'AI Thinking... {countdown}', True, BLUE) screen.blit(timer_text, (10, screen_size - 30)) pygame.display.flip() # Check for a win def check_win(x, y): directions = [(1, 0), (0, 1), (1, 1), (1, -1)] player = board[y][x] for dx, dy in directions: count = 1 for dir in [1, -1]: nx, ny = x, y while True: nx += dir * dx ny += dir * dy if 0 <= nx < grid_size and 0 <= ny < grid_size and board[ny][nx] == player: count += 1 else: break if count >= 5: return True return False # Minimax Algorithm with Alpha-Beta Pruning def minimax(bd, depth, alpha, beta, maximizing): if depth == 0 or is_full(bd): return evaluate_board(bd) if maximizing: max_eval = float('-inf') for y in range(grid_size): for x in range(grid_size): if bd[y][x] == EMPTY: bd[y][x] = ai_player eval = minimax(bd, depth - 1, alpha, beta, False) bd[y][x] = EMPTY max_eval = max(max_eval, eval) alpha = max(alpha, eval) if beta <= alpha: break return max_eval else: min_eval = float('inf') opponent = BLACK_STONE if ai_player == WHITE_STONE else WHITE_STONE for y in range(grid_size): for x in range(grid_size): if bd[y][x] == EMPTY: bd[y][x] = opponent eval = minimax(bd, depth - 1, alpha, beta, True) bd[y][x] = EMPTY min_eval = min(min_eval, eval) beta = min(beta, eval) if beta <= alpha: break return min_eval # Evaluation Function def evaluate_board(bd): # Simple evaluation: count the number of stones for AI and opponent ai_count = sum(row.count(ai_player) for row in bd) opponent = BLACK_STONE if ai_player == WHITE_STONE else WHITE_STONE opponent_count = sum(row.count(opponent) for row in bd) return ai_count - opponent_count # Check if the board is full def is_full(bd): for row in bd: if EMPTY in row: return False return True # AI move using Minimax def ai_move(): global current_player, thinking, countdown best_score = float('-inf') move = None start_time = time.time() time_limit = 5 # seconds def countdown_timer(): global countdown, thinking while countdown > 0 and thinking: time.sleep(1) countdown -= 1 # Start countdown thread countdown_thread = threading.Thread(target=countdown_timer) countdown_thread.start() thinking = True for y in range(grid_size): for x in range(grid_size): if board[y][x] == EMPTY: board[y][x] = ai_player score = minimax(board, max_depth - 1, float('-inf'), float('inf'), False) board[y][x] = EMPTY if score > best_score: best_score = score move = (x, y) if time.time() - start_time > time_limit: break if time.time() - start_time > time_limit: break thinking = False countdown = 5 if move: x, y = move board[y][x] = ai_player if check_win(x, y): global game_over, winner game_over = True winner = ai_player current_player = BLACK_STONE if ai_player == WHITE_STONE else WHITE_STONE # Mode Selection def select_mode(): global ai_enabled, ai_player running = True mode = None player_color = None while running: screen.fill(WOOD) title_text = font.render('Select Game Mode', True, BLACK) two_player_text = font.render('1. Two Player', True, BLACK) ai_text = font.render('2. Play with AI', True, BLACK) screen.blit(title_text, (screen_size // 2 - 60, screen_size // 2 - 60)) screen.blit(two_player_text, (screen_size // 2 - 60, screen_size // 2 - 30)) screen.blit(ai_text, (screen_size // 2 - 60, screen_size // 2)) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if screen_size // 2 - 60 <= x <= screen_size // 2 + 60: if screen_size // 2 - 30 <= y <= screen_size // 2 - 10: mode = 'two_player' running = False elif screen_size // 2 <= y <= screen_size // 2 + 20: mode = 'ai' running = False if mode == 'ai': running = True while running: screen.fill(WOOD) color_text = font.render('Select Your Color', True, BLACK) black_text = font.render('1. Black', True, BLACK) white_text = font.render('2. White', True, BLACK) screen.blit(color_text, (screen_size // 2 - 60, screen_size // 2 - 60)) screen.blit(black_text, (screen_size // 2 - 60, screen_size // 2 - 30)) screen.blit(white_text, (screen_size // 2 - 60, screen_size // 2)) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if screen_size // 2 - 60 <= x <= screen_size // 2 + 60: if screen_size // 2 - 30 <= y <= screen_size // 2 - 10: player_color = BLACK_STONE running = False elif screen_size // 2 <= y <= screen_size // 2 + 20: player_color = WHITE_STONE running = False ai_enabled = True global current_player ai_player = BLACK_STONE if player_color == WHITE_STONE else WHITE_STONE current_player = BLACK_STONE if ai_player == BLACK_STONE: ai_move() # Main game loop def main(): select_mode() global current_player, game_over, winner while True: draw_board() if game_over: win_text = 'Black wins!' if winner == BLACK_STONE else 'White wins!' text = font.render(win_text, True, BLUE) screen.blit(text, (screen_size // 2 - 40, screen_size // 2 - 15)) pygame.display.flip() time.sleep(3) pygame.quit() sys.exit() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN and not thinking: x_mouse, y_mouse = event.pos x = round((x_mouse - margin) / cell_size) y = round((y_mouse - margin) / cell_size) if 0 <= x < grid_size and 0 <= y < grid_size: if board[y][x] == EMPTY and current_player != ai_player: board[y][x] = current_player if check_win(x, y): game_over = True winner = current_player current_player = BLACK_STONE if current_player == WHITE_STONE else WHITE_STONE if ai_enabled and not game_over: ai_move() pygame.display.flip() if __name__ == '__main__': main()Instructions:
- Ensure you have Pygame installed. If not, install it using
pip install pygame. - Run the script. A window will open with options to select the game mode and player color using the mouse.
- In two-player mode, two players take turns placing stones by clicking on the grid.
- In human vs. AI mode, select your color, and the AI will play as the opposite color.
- The AI uses the Minimax algorithm with a default search depth of 3. You can adjust
max_depthfor difficulty. - The AI has a maximum thinking time of 5 seconds, and a countdown timer is displayed during its turn.
- The game ends when a player forms an unbroken chain of five stones horizontally, vertically, or diagonally.
- The game will display the winner and exit after a brief pause.
Note:
- This implementation uses a simple evaluation function and may not represent a strong AI.
- The Minimax algorithm considers all possible moves up to the given depth, which can be slow for larger depths.
- For better performance and a stronger AI, consider implementing optimizations like a better heuristic or move ordering.
- Ensure you have Pygame installed. If not, install it using