如何简化带多难度AI的Tic Tac Toe(井字棋)主函数命令匹配代码
井字棋命令分支冗余问题简化方案
核心思路
你现有代码的问题在于硬编码了所有命令组合、且为每个玩家组合单独编写了启动方法,后续加难度自然会导致代码线性膨胀。我们可以通过「命令结构化解析 + 映射表路由 + 统一游戏启动入口」的方式彻底干掉冗余分支。
具体实现步骤
1. 调整游戏类设计,统一启动入口
废弃easy_pvc/medium_cvp这类针对特定组合的方法,将玩家类型作为游戏类的初始化参数,所有模式统一通过run()方法启动:
- 玩家类型标记为
user(真人玩家)或者easy/medium/hard(对应难度的AI) - 难度AI类统一继承同一个AI基类,实现相同的
get_move()决策方法,游戏逻辑层不需要区分AI难度
# 示例AI基类和难度实现 class BaseAI: def get_move(self, grid): raise NotImplementedError class EasyAI(BaseAI): def get_move(self, grid): # 简单难度逻辑 pass class MediumAI(BaseAI): def get_move(self, grid): # 中等难度逻辑 pass # 统一的游戏类 class Game: def __init__(self, player1, player2): self.player1 = player1 self.player2 = player2 self.grid = Grid() def run(self): # 统一游戏流程:轮流走子,判断胜负,不需要关心玩家是真人还是AI、是哪个难度的AI current_player = self.player1 while not self.grid.is_game_over(): if current_player == 'user': move = self.grid.get_user_input() else: move = current_player.get_move(self.grid) self.grid.make_move(move) current_player = self.player2 if current_player == self.player1 else self.player1 self.grid.show_result()
2. 用映射表替代硬编码分支
提前定义难度类的映射字典,解析命令后直接从字典中取对应实例,不需要写任何分支判断:
# 难度类映射,后续加hard只需要加一行即可 DIFFICULTY_MAP = { "easy": EasyAI(), "medium": MediumAI(), "hard": HardAI() # 后续加难度仅需新增这一项 } def main(): while True: command = input('Input command: ').strip().split() # 先做参数合法性校验 if not command: print('Bad parameters!') continue # 处理exit命令 if command[0] == 'exit': exit() # 处理start命令 if command[0] == 'start' and len(command) == 3: p1_type, p2_type = command[1], command[2] # 校验玩家参数合法性 valid_types = {'user', 'easy', 'medium', 'hard'} if p1_type not in valid_types or p2_type not in valid_types: print('Bad parameters!') continue # 生成玩家实例 player1 = 'user' if p1_type == 'user' else DIFFICULTY_MAP[p1_type] player2 = 'user' if p2_type == 'user' else DIFFICULTY_MAP[p2_type] # 启动游戏 Game(player1, player2).run() else: print('Bad parameters!')
方案优势
- 后续新增
hard难度仅需要2步:实现HardAI类,在DIFFICULTY_MAP中加一行映射,不需要修改任何分支逻辑 - 所有玩家组合自动支持,不需要单独为
start user hard/start hard medium这类新组合加代码 - 游戏逻辑和AI实现完全解耦,调整难度逻辑不需要修改主程序代码
内容的提问来源于stack exchange,提问作者grl
相关产品推荐
相关产品推荐

