Python井字棋游戏check_winner函数为何不打印获胜提示?
井字棋check_winner函数获胜提示无法打印的问题解决
问题描述
我正在用Python开发一款井字棋游戏,目前功能可用但尚未完善。问题在于编写的check_winner函数在检测到获胜情况时,return True语句后的获胜提示信息无法打印。
原check_winner函数代码:
def check_winner(spots): if spots[1] == spots[2] == spots[3]: return True print("Winner found!") if spots[4] == spots[5] == spots[6]: return True print("Winner found!") if spots[7] == spots[8] == spots[9]: return True print("Winner found!") if spots[1] == spots[4] == spots[7]: return True print("Winner found!") if spots[3] == spots[6] == spots[9]: return True print("Winner found!") if spots[1] == spots[5] == spots[9]: return True print("Diagonal winner found!") if spots[3] == spots[5] == spots[7]: return True print("Diagonal winner found!")
游戏主循环代码:
while winner == False: if Turns % 2: Letter = 'X' else: Letter = 'O' print_board(spots) if check_winner(spots) == True: break
当棋盘检测到获胜者,函数返回True时,获胜提示完全不打印,请问这是为什么?
问题原因
return语句会立即终止函数的执行流程,一旦函数执行到return True,会直接跳出函数返回结果,后面的print语句根本没有机会被执行。这就是提示信息无法打印的核心原因。
修复方案
方案1:将print语句移到return之前
调整函数内代码顺序,先打印提示再返回结果:
def check_winner(spots): if spots[1] == spots[2] == spots[3]: print("Winner found!") return True if spots[4] == spots[5] == spots[6]: print("Winner found!") return True if spots[7] == spots[8] == spots[9]: print("Winner found!") return True if spots[1] == spots[4] == spots[7]: print("Winner found!") return True if spots[3] == spots[6] == spots[9]: print("Winner found!") return True if spots[1] == spots[5] == spots[9]: print("Diagonal winner found!") return True if spots[3] == spots[5] == spots[7]: print("Diagonal winner found!") return True return False # 没有获胜情况时返回False,避免函数无返回值
方案2:让函数返回获胜类型,在主循环中打印提示
这种方式更符合单一职责原则,函数只负责检测获胜并返回结果,打印逻辑放在主循环里:
def check_winner(spots): if spots[1] == spots[2] == spots[3]: return "horizontal" if spots[4] == spots[5] == spots[6]: return "horizontal" if spots[7] == spots[8] == spots[9]: return "horizontal" if spots[1] == spots[4] == spots[7]: return "vertical" if spots[3] == spots[6] == spots[9]: return "vertical" if spots[1] == spots[5] == spots[9]: return "diagonal" if spots[3] == spots[5] == spots[7]: return "diagonal" return None # 无获胜时返回None # 修改主循环 while winner == False: if Turns % 2: Letter = 'X' else: Letter = 'O' print_board(spots) result = check_winner(spots) if result: if result in ["horizontal", "vertical"]: print("Winner found!") else: print("Diagonal winner found!") break
内容的提问来源于stack exchange,提问作者rooknoobski
相关产品推荐
相关产品推荐

