我正在构建一个Tic-Tac-Toe游戏,我有一个纵向和横向检查,如下所示:
def check_win_left_vert (board):
win = True
x = 0
for y in range (2):
if board[y][x] != board[y+1][x]:
win = False
return win
通过增加y轴来查看电路板;我对x轴使用相同的方法。我如何为对角线轴做这个?我会增加两个吗?
答案 0 :(得分:0)
你会在一个对角线上使用相同的变量,而#34; 2反转"它在另一方面:
for x in range(2):
if board[x][x] ...
for x in range(2):
if board[x][2-x] ...
请注意,您必须注意边界条件。我强烈怀疑你还没有打算测试你的水平代码,因为它试图检查电路板右边缘的空间。缩小范围以解决问题。
答案 1 :(得分:0)
您需要在相同的循环中检查对角线情况
if board[y][y] != board[y+1][y+1] or board[2-y][y] != board[1-y][1+y]:
win = False
if win == False:
break;
答案 2 :(得分:0)
game_board = [ [1, 0, 1],
[0, 1, 0],
[0, 1, 0] ]
# Horizontals
h = [str(i+1) + ' Row' for i, v in enumerate(game_board) if sum(v) == 3]
# Verticals
v = [str(i+1) + ' Col' for i in range(3) if sum([j[i] for j in game_board]) == 3]
# Diagonals
d = [['Left Diag', '','Right Diag'][i+1] for i in [-1, 1] if sum([game_board[0][1+i], game_board[1][1]], game_board[2][1-i]) == 3]
if any([h,v,d]):
print('You won on:', h, v, d)
else:
print('No win yet')