如何在IF Else语句中判断函数返回结果?checktie函数逻辑优化求助
解决checktie函数跳过已判定胜负场景的问题
有两种简洁的方案可以实现你的需求,核心是明确记录「是否已经决出胜者」的状态,避免checktie在有胜者时执行:
方案一:给checkwin添加返回值,调用时传递状态
首先修改checkwin,让它返回布尔值表示是否存在胜者:
def checkwin(): has_winner = checkcolumn(board) or checkdiagonal(board) or checkrow(board) if has_winner: print(f"The winner is {winner}") return has_winner
然后在主逻辑中调用checkwin并保存结果,再把结果传给checktie:
# 示例主循环逻辑 gamerunning = True while gamerunning: # 玩家落子等操作代码... winner_found = checkwin() if winner_found: gamerunning = False continue # 有胜者则跳过平局检查 checktie(board, winner_found)
最后修改checktie函数,接收winner_found参数并判断:
def checktie(board, winner_found): global gamerunning if "-" not in board and not winner_found: printboard(board) print("It is a tie!") gamerunning = False
方案二:拆分胜负判断与打印逻辑
如果不想传递参数,可以把「判断是否有胜者」和「打印胜者信息」拆成两个函数,这样checktie可以只调用判断逻辑而不触发重复打印:
# 仅判断是否有胜者,不输出内容 def has_winner(board): return checkcolumn(board) or checkdiagonal(board) or checkrow(board) # 负责打印胜者信息的函数 def checkwin(): if has_winner(board): print(f"The winner is {winner}") # 修改后的checktie函数 def checktie(board): global gamerunning if "-" not in board and not has_winner(board): printboard(board) print("It is a tie!") gamerunning = False
这样无论哪种方案,都能确保当checkwin已经判定出胜者时,checktie会跳过平局判断逻辑。
内容的提问来源于stack exchange,提问作者Sharry
相关产品推荐
相关产品推荐

