井字棋程序check_if_win函数判断结果异常,求原因分析
问题原因及解决方法
你的check_if_win函数逻辑存在错误,导致它错误返回True。
错误根源
你写的判断条件:
current_board_state[0][0] and current_board_state[1][0] and current_board_state[2][0] == current_mark
在Python中会被这样解析:
- 先判断
current_board_state[0][0]是否为布尔真:这里值是'.',非空字符串在Python中会被视为True; - 再判断
current_board_state[1][0]是否为布尔真:同样是'.',结果也是True; - 最后判断
current_board_state[2][0] == current_mark:这里是'o' == 'o',结果为True; - 三个True做逻辑与运算,最终结果为True,所以函数返回True。
但你实际想要的是第一列的三个元素都等于current_mark,而不是前两个元素非空、最后一个等于标记。
修正方法
需要给每个元素都加上和current_mark的比较:
current_board_state = [['.', '.', 'o'], ['.', 'o', '.'], ['o', '.', '.']] def check_if_win(current_board_state, current_mark): # 修正第一列的判断逻辑:每个元素都要等于current_mark if (current_board_state[0][0] == current_mark and current_board_state[1][0] == current_mark and current_board_state[2][0] == current_mark): print("Yes") return True else: print("No") return False print(check_if_win(current_board_state, "o")) # 现在会输出No,返回False
额外优化建议
如果要判断所有获胜条件(行、列、两条对角线),可以用更简洁的方式:
def check_if_win(current_board_state, current_mark): # 检查所有行 for row in current_board_state: if all(cell == current_mark for cell in row): return True # 检查所有列 for col in range(3): if all(current_board_state[row][col] == current_mark for row in range(3)): return True # 检查两条对角线 if (current_board_state[0][0] == current_mark and current_board_state[1][1] == current_mark and current_board_state[2][2] == current_mark): return True if (current_board_state[0][2] == current_mark and current_board_state[1][1] == current_mark and current_board_state[2][0] == current_mark): return True return False
内容的提问来源于stack exchange,提问作者mnms
相关产品推荐
相关产品推荐

