python - 在 Python 中查找井字游戏的结果
问题描述
我正在尝试编写一个函数来显示谁是井字游戏中的赢家。如果 X 是它返回的获胜者X
,如果 O 是它返回的获胜者,O
并且对于平局,它返回布尔值None
我尝试的内容适用于某些情况,但对于下面给出的测试用例失败请帮助。
def check_winner(tuples):
for row in range(0, len(tuples)):
print(tuples[row])
for col in range(0,3):
#check for row win
if tuples[row][0] == tuples[row][1] == tuples[row][2]:
print("1 ")
# return tuples[row][0];
#check for col win
if tuples[0][col] == tuples[1][col] == tuples[2][col]:
print("2")
return tuples[row][0];
# For diagonal
if tuples[0][0] == tuples[1][1] == tuples[2][2]:
return tuples[0][0]
if tuples[0][2] == tuples[1][1] == tuples[2][0]:
return tuples[2][0]
对于下面的测试用例
# O wins
test1 = (('X', 'O', 'O'),
(None, 'O', 'X'),
('X', 'O', 'X'))
# X Wins
test2 = (('X', 'X', 'O'),
(("O", 'X', 'O'),
('O', 'X', 'X'))
调用函数
print(check_winner(test1))
print(check_winner(test2))
应该分别返回 O 和 X
解决方案
您return tuples[row][0];
在第二个 if 语句中返回。tuples[0][col]
如果你想返回获胜者的价值,它应该是这样的。
您不需要嵌套 for 循环来检查行和列。您应该检查的每个只有 3 个。
试试这个:
def check_winner(tuples):
for line in range(3):
#check for row win
if tuples[line][0] == tuples[line][1] == tuples[line][2]:
print("1 ")
return tuples[line][0];
#check for col win
if tuples[0][line] == tuples[1][line] == tuples[2][line]:
print("2")
return tuples[0][line];
# For diagonal
if tuples[0][0] == tuples[1][1] == tuples[2][2]:
return tuples[0][0]
if tuples[0][2] == tuples[1][1] == tuples[2][0]:
return tuples[2][0]
推荐阅读
- php - 如何在内容类型下的字段中显示图像 - 使用 Drupal 7
- php - 家庭控制器内的转储和死亡(dd)
- google-query-language - 是否可以选择前 10 个项目并将其余项目放在其他项目中?就像我们可以在 SQL 中做的那样
- c# - 为什么我的 ImageButton 没有动态更新?
- azure - 通过 Visual Studio 2019 将逻辑应用部署到 Azure
- javascript - 模态图片库 - 多张图片不会显示
- excel-formula - 从单元格中的值引用数组
- python - 如何从“jetson.inference.detectNet.Detection”类型中获取单独的值?
- java - 使用 ProcessBuilder 运行 Java 主类
- scala - 如何减少 Spark 中的 List[Key, List[Name, Value]]?