问题
I'm building a game of Tic-Tac-Toe, and I have a vertical and horizontal check that look like this:
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
It looks through the board by incrementing the y axis; I use the same method for the x axis. How would I do this for a diagonal axis? Would I increment both?
回答1:
You would use the same variable for both on one diagonal, and "2 invert" it on the other:
for x in range(2):
if board[x][x] ...
for x in range(2):
if board[x][2-x] ...
Note that you have to watch out for boundary conditions. I strongly suspect that you haven't bothered to test your horizontal code yet, as it tries to check a space off the right edge of the board. Reduce the range to fix that.
回答2:
You need to make in the same loop check for diagonal case
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;
来源:https://stackoverflow.com/questions/47423891/tic-tac-toe-diagonal-check