因此,我目前正在编写代码来检查connect3游戏中的对角获胜,但是由于某些原因,没有显示打印语句,有人可以检查错误的地方吗
board = [['_','X','X','O'],
['_','X','X','O'],
['X','X','O','O']]
num_row = 3
num_col = 4
num_piece = 3 #game pieces needed to win
game_piece = 'X'# check / diagonal win
for rows in range(num_row - num_piece + 1):
for cols in range(num_piece, num_col):
index = 0
for counts in range(num_piece):
if board[rows + index][cols - index] == game_piece:
index += 1
else:
break
if index == num_piece:
print('game end')发布于 2020-05-17 01:31:35
您的代码只测试第一条对角线(从右上角开始):
>>> for rows in range(num_row - num_piece + 1):
... for cols in range(num_piece, num_col):
... index = 0
... print(f"testing {rows, cols}")
... for counts in range(num_piece):
... if board[rows + index][cols - index] == game_piece:
... index += 1
... else:
... break
... if index == num_piece:
... print('game end')
...
testing (0, 3)由于要测试从第2列(第3列)开始的每条对角线,因此需要从该范围的起始处减去1:
>>> for rows in range(num_row - num_piece + 1):
... for cols in range(num_piece - 1, num_col):
... index = 0
... print(f"testing {rows, cols}")
... for counts in range(num_piece):
... if board[rows + index][cols - index] == game_piece:
... index += 1
... else:
... break
... if index == num_piece:
... print('game end')
...
testing (0, 2)
game end
testing (0, 3)另请参阅:Finding neighbor cells in a grid with the same value. Ideas how to improve this function?
https://stackoverflow.com/questions/61840794
复制相似问题