o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
写一个五子棋游戏,13*13,双人对弈,用python写,代码生产在一起,可以一次性运行bug free,用鼠标点击交互,黑白子UI。 有双人对弈模式,和人机对战。…
- User
写一个五子棋游戏,13*13,双人对弈,用python写,代码生产在一起,可以一次性运行bug free,用鼠标点击交互,黑白子UI。 有双人对弈模式,和人机对战。 人机对战,玩家可选黑白。、 完成人机对战五子棋AI 选择模式 不用键盘 弹出方框用鼠标选择
- Assistant
下面是一个使用
pygame库编写的五子棋游戏,满足您的要求。此游戏支持双人对战和人机对战模式,玩家可以通过鼠标点击来进行交互选择。确保您的环境中已经安装了pygame库。如果尚未安装,可以使用以下命令安装:pip install pygame以下是完整的 Python 代码:
import pygame import sys import math import random # 初始化pygame pygame.init() # 定义颜色 WHITE = (255, 255, 255) BLACK = (0, 0, 0) GRAY = (185, 185, 185) RED = (255, 0, 0) BLUE = (0, 0, 255) # 设置屏幕大小 BOARD_SIZE = 13 CELL_SIZE = 40 MARGIN = 20 WIDTH = CELL_SIZE * (BOARD_SIZE - 1) + 2 * MARGIN HEIGHT = WIDTH + 100 # 预留下方区域用于显示信息 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('五子棋') FONT = pygame.font.SysFont(None, 36) # 棋盘数据结构 board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)] # 游戏状态 mode = None # None, 'PVP', 'PVC' player_color = None # 1: 黑, 2: 白 current_player = 1 # 1: 黑, 2: 白 game_over = False winner = None def draw_board(): screen.fill(GRAY) # 画网格 for i in range(BOARD_SIZE): # 画横线 pygame.draw.line(screen, BLACK, (MARGIN, MARGIN + i * CELL_SIZE), (WIDTH - MARGIN, MARGIN + i * CELL_SIZE), 1) # 画竖线 pygame.draw.line(screen, BLACK, (MARGIN + i * CELL_SIZE, MARGIN), (MARGIN + i * CELL_SIZE, WIDTH - MARGIN), 1) # 画星位 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) # 画棋子 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 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 # 向一个方向数 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 # 向另一个方向数 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): pygame.draw.rect(screen, GRAY, (0, WIDTH, WIDTH, HEIGHT - WIDTH)) img = FONT.render(text, True, RED) screen.blit(img, (MARGIN, WIDTH + 30)) def reset_game(): global board, current_player, game_over, winner board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)] current_player = 1 game_over = False winner = None # 简单的AI:随机选择一个空位置 def ai_move(): empty = [(r, c) for r in range(BOARD_SIZE) for c in range(BOARD_SIZE) if board[r][c] == 0] if empty: return random.choice(empty) return None def minimax(board_state, depth, maximizing, alpha, beta): # 终止条件 if depth == 0 or check_terminal(board_state): return evaluate(board_state), None if maximizing: max_eval = -math.inf best_move = None for move in get_possible_moves(board_state): new_board = [row[:] for row in board_state] new_board[move[0]][move[1]] = 2 eval, _ = minimax(new_board, depth -1, False, alpha, beta) 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 best_move = None for move in get_possible_moves(board_state): new_board = [row[:] for row in board_state] new_board[move[0]][move[1]] = 1 eval, _ = minimax(new_board, depth -1, True, alpha, beta) if eval < min_eval: min_eval = eval best_move = move beta = min(beta, eval) if beta <= alpha: break return min_eval, best_move 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 # 平局 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 evaluate(board_state): # 很简单的评分函数 score = 0 for r in range(BOARD_SIZE): for c in range(BOARD_SIZE): if board_state[r][c] == 2: score +=1 elif board_state[r][c] ==1: score -=1 return score def get_possible_moves(board_state): # 返回所有空位 return [(r, c) for r in range(BOARD_SIZE) for c in range(BOARD_SIZE) if board_state[r][c]==0] def ai_move_minimax(): _, move = minimax(board, 2, True, -math.inf, math.inf) return move def main_menu(): menu = True while menu: screen.fill(GRAY) title = FONT.render('五子棋游戏', True, BLUE) screen.blit(title, (WIDTH//2 - title.get_width()//2, HEIGHT//2 - 150)) pvp_text = FONT.render('双人对战', True, BLACK) pvc_text = FONT.render('人机对战', 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('请选择颜色', True, BLUE) screen.blit(prompt, (WIDTH//2 - prompt.get_width()//2, HEIGHT//2 - 100)) black_text = FONT.render('黑色', True, BLACK) white_text = FONT.render('白色', 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 # 黑色 elif WIDTH//2 +20 <= mx <= WIDTH//2 +100 and HEIGHT//2 -40 <= my <= HEIGHT//2: return 2 # 白色 def main(): global mode, player_color, current_player, game_over, winner clock = pygame.time.Clock() mode = main_menu() if mode == 'PVC': player_color = choose_color() if player_color ==1: ai_player =2 else: ai_player =1 draw_board() if mode == 'PVC' and player_color ==2: # AI先手 move = ai_move_minimax() if move: r, c = move board[r][c] = ai_player winner = is_winner(r, c) if winner: game_over = True current_player = player_color while True: draw_board() if game_over: if winner ==1: msg = "黑棋胜利!" elif winner ==2: msg = "白棋胜利!" else: msg = "平局!" draw_info(msg + " 点击任意键重新开始") else: if mode == 'PVP': turn = '黑棋' if current_player ==1 else '白棋' draw_info(f"{turn} 回合") else: if current_player == player_color: turn = '你的回合' else: turn = 'AI 回合' draw_info(turn) 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.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN: reset_game() mode = main_menu() if mode == 'PVC': player_color = choose_color() if player_color ==1: ai_player =2 else: ai_player =1 reset_game() draw_board() if mode == 'PVC' and player_color ==2: # AI先手 move = ai_move_minimax() if move: r, c = move board[r][c] = ai_player winner = is_winner(r, c) if winner: game_over = True current_player = player_color 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 走棋 pygame.display.flip() pygame.time.delay(500) # 短暂延迟 ai_move_func = ai_move_minimax move = ai_move_func() if move: r, c = move board[r][c] = ai_player winner = is_winner(r, c) if winner: game_over = True current_player = player_color clock.tick(30) if __name__ == "__main__": main()代码说明
-
初始化和设置:
- 使用
pygame初始化游戏窗口,并定义了一些基本颜色和尺寸参数。 - 棋盘大小为 13x13,每个格子的大小为 40 像素,周边留有边距。
- 使用
-
棋盘绘制:
draw_board()函数负责绘制棋盘,包括网格、星位和棋子。- 星位位于第 4、第 7 和第 10 条线上。
-
事件处理:
main_menu()函数显示主菜单,让玩家选择双人对战(PVP)或人机对战(PVC)。- 如果选择人机对战,
choose_color()函数会弹出选择黑色或白色棋子的界面。
-
游戏逻辑:
- 棋盘用二维列表
board表示,0 表示空位,1 表示黑子,2 表示白子。 get_cell()函数将鼠标点击的位置转换为棋盘上的格子坐标。is_winner()函数用于检查是否有玩家获胜。draw_info()函数在棋盘下方显示当前游戏状态或胜利信息。reset_game()函数用于重置游戏数据。
- 棋盘用二维列表
-
AI 实现:
- 这里实现了一个基本的 Minimax 算法来作为 AI。为了效率,深度限制为 2,可以根据需要调整。
minimax()函数递归计算最佳走法,并返回评分和最佳移动位置。- 评分函数
evaluate()非常简单,仅基于当前棋盘状态进行评分,实际应用中可以进一步优化。
-
主循环:
main()函数处理游戏的主循环,包括绘制棋盘、处理玩家和 AI 的回合、检测胜利条件等。- 如果游戏结束,会提示胜利信息,并允许玩家点击重新开始游戏。
如何运行
-
安装 Pygame: 确保已安装
pygame库。如果未安装,可以使用以下命令进行安装:pip install pygame -
运行脚本: 将上述代码保存为
gobang.py,然后在终端或命令提示符中运行:python gobang.py -
游戏操作:
- 主菜单: 使用鼠标点击选择“双人对战”或“人机对战”。
- 人机对战:
- 选择颜色后,轮流点击棋盘位置下子。
- 如果选择让 AI 先手(选择白色),AI 会先下子。
- 游戏结束: 当有一方获胜或平局时,会在下方显示信息,点击任意键或鼠标重新开始游戏。
注意事项
- AI 简单性: 目前的 AI 实现较为基础,可能不会进行复杂的策略思考。可以根据需要优化 AI,例如增加启发式评估函数或使用更高级的搜索策略。
- 性能优化: 对于较大的棋盘和更深的 Minimax 搜索,可能会影响性能。可以优化算法或限制搜索深度以提高响应速度。
- 界面改进: 可以进一步美化界面,例如添加按钮、动画效果等。
希望这个代码能满足您的需求,祝您游戏愉快!
-