Python Connect four检查win功能仅在某些情况下有效
我的用于检查connect four win的函数仅在第一行有效,而在其他任何行无效。在我代码的某个地方,x和y也混在一起了,是我的循环吗Python Connect four检查win功能仅在某些情况下有效,python,python-3.x,Python,Python 3.x,我的用于检查connect four win的函数仅在第一行有效,而在其他任何行无效。在我代码的某个地方,x和y也混在一起了,是我的循环吗 def check_win(it): #right diag - works for x in range (0, 6): for y in range (0, 5): if board[x][y] == it and board[x-1][y+1] == it and board[x-2][y+2]
def check_win(it):
#right diag - works
for x in range (0, 6):
for y in range (0, 5):
if board[x][y] == it and board[x-1][y+1] == it and board[x-2][y+2] == it and board[x-3][y+3] == it:
return True
#left diag- works
for x in range (0, 6):
for y in range (0, 5):
if board[x][y] == it and board[x-1][y-1] == it and board[x-2][y-2] == it and board[x-3][y-3] == it:
return True
#right- works
for y in range(0, 6):
if board[x][y] == it and board[x][y+1] == it and board[x][y+2] == it and board[x][y+3] == it:
return True
#down - works
for y in range(0, 6):
if board[x][y] == it and board[x-1][y] == it and board[x-2][y] == it and board[x-3][y] == it:
return True
return False
例如,这里的代码可以工作,但只在第一行
如下图所示,当第一行上方的任何一行上有一个connect 4时,它将不起作用
两个
for y
循环没有嵌套的for x
循环。因此,他们只是使用上一个对角循环中的最后一个x
。另外,在左对角代码中,您可以访问board[x-1][y-1]
。当x=0
和y=0
时,会得到负索引。在右边的诊断代码中也有board[x-1]
。哇,我完全错过了,谢谢
. . . . . . .
. . . . . . .
R . . . . . .
R . . . . . .
R . . . . . .
B B B B . . .
1 2 3 4 5 6 7
Game Over!
player 1 wins!
. . . . . . .
B . . . . . .
B . . . . . .
B . . . . . .
R R R R . . .
B R B R B . .
1 2 3 4 5 6 7