Tic Tac Toe diagonal check

天大地大妈咪最大 提交于 2020-05-15 22:44:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!