我目前正在阅读 pythonprogramming.net 上提供的一些教育 Material ,我们尝试在其中构建 TicTacToe 游戏。
在下面的代码中,您可以看到一个定义获胜者规则的方法,但是每当我尝试在游戏列表中对角线“硬编码”获胜位置,然后运行代码时,我总是在终端中收到以下内容输出:
Player 2 is the winner diagonally РР
Player 2 is the winner diagonally РР
Player 2 is the winner diagonally РР
Player 1 is the winner diagonally ЯЯ
Player 2 is the winner diagonally ЯЯ
Player 1 is the winner diagonally ЯЯ
如果您查看我的游戏列表中的硬编码测试用例 - 它必须只有 1 个获胜者(玩家 2),并且只有最后一个循环必须触发并打印到控制台...
有什么建议可能是问题所在以及如何解决吗?
game = [[2, 0, 1],
[0, 2, 0],
[1, 0, 2]]
def win(current_game):
col_dig = list(reversed(range(len(game))))
row_dig = range(len(game))
for row in current_game:
print(row)
if row.count(row[0]) == len(row) and row[0] != 0:
print(f"Player {row[0]} is the winner!")
for col in range(len(game[0])):
check = []
for row in game:
check.append(row[col])
if check.count(check[0]) == len(check) and check[0] != 0:
print(f"Player {check[0]} is the winner vertically!")
for ix in range(len(game)):
diag = []
diag.append(game[ix][ix])
if diag.count(diag[0]) == len(diag) and diag[0] != 0:
print(f"Player {diag[0]} is the winner diagonally РР")
for x, y in zip(col_dig, row_dig):
diag2 = []
diag2.append(game[x][y])
if diag2.count(diag2[0]) == len(diag2) and diag2[0] != 0:
print(f"Player {diag2[0]} is the winner diagonally ЯЯ")
win(game)
最佳答案
for ix in range(len(game)):
diag = []
diag.append(game[ix][ix])
if diag.count(diag[0]) == len(diag) and diag[0] != 0:
print(f"Player {diag[0]} is the winner diagonally РР")
在这里,在每次迭代期间,您的 diag=[]
语句将被执行,并且任何先前附加的值都将被删除。因此,您需要在 for 循环之前声明 diag=[]
的初始化。
此外,您的 if 条件在循环的每次迭代中执行。因为您在循环中使用 if 条件。这就是为什么你会得到三行循环。因此,您需要将 if 条件移到循环之外。
更新后的代码如下:
diag = []
for ix in range(len(game)):
diag.append(game[ix][ix])
if diag.count(diag[0]) == len(diag) and diag[0] != 0:
print(f"Player {diag[0]} is the winner diagonally РР")
代码最后部分的情况相同。
关于python - 为什么我的 FOR 循环返回 6 个结果而不是 1 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57614730/