如何检查在自定义尺寸的双赢井字棋对角线(How to check for win in custom

2019-10-29 23:57发布

我正在做一个简单的井字游戏,其中用户可以指定网格的(列和行的量)的大小。
我需要创建一个功能,能够在网格中的所有对角线检查的胜利。

对于网格,我使用的是2维列表,看起来像这样(3×3为例):

grid = [['x', '-', 'o'], 
        ['o', 'x', '-'], 
        ['-', '-', 'x']]
grid[row][col]

这应该是一个胜势

我已经创建了纵横赢的支票,但我不能完全弄清楚,如何检查对角线。

这里是我为您在我的代码行胜利:

min_win_streak是最小连胜(例如,在3×3古典井字棋,这将是3)

def check_rows(grid, min_win_streak):
    winner = '-'
    for row in grid:
        win_streak = 0
        for element in row:
            if element != '-':
                if element == winner:
                    win_streak += 1
                    winner = element
                    if win_streak >= min_win_streak:
                        return True, winner
                else:
                    win_streak = 1
                    winner = element
            else:
                win_streak = 0
                winner = '-'
    return False, None



我需要check_diags()函数,收益应该是:

  • 赢得x,则函数应该返回true,“X”
  • 赢得O,函数应该返回true,“X”
  • 不成功 ,函数应该返回False,无

Answer 1:

您可以检查使用以下嵌套的for循环中的一个2x2的对角线:

for i in range(len(grid)-2):
    for j in range(len(grid)-2):
        if grid[i][j] == grid[i+1][j+1] == grid[i+2][j+2] and grid[i][j] != '-':
            print('Winner')
        elif grid[i][j+2] == grid[i+1][j+1] == grid[i+2][j] and grid[i][j+2] != '-':
            print('Winner')

如果你希望插入这个与期望回报率的函数来代替打印报表。 这应该是扩展到3×3×4等具有相当容易改变。



Answer 2:

感谢张贴你的代码。 我换成你win_streak检查循环与all功能。 下面的代码做更多的工作比你想使用一个巨大的网格,但它很容易(容易)理解和适应,它的速度不够快,使用的游戏五子棋(5连续上19×19板)。

我留在一个跟踪print语句来说明它的检查对角线。 你应该能够将此适应东北-西南对角线( check_slash_diag )。

grid = [['x', '-', 'o', 'o'],
        ['o', 'x', 'o', '-'],
        ['-', 'o', 'x', 'x'],
        ['-', 'x', 'o', '-']]

def check_backslash_diag(grid, min_win_streak):

    grid_size = len(grid)
    grid_extra = grid_size - min_win_streak   # This is the "extra" space in a long line

    # This pair of loops will iterate through the upper-left square of side 
    #   grid_extra+1, starting points of any diagonals long enough to contain a win.
    for start_row in range(grid_extra+1):
        for start_col in range(grid_extra+1):
            # Extract a diagonal "row" of length min_win_streak
            diag = [grid[start_row+i][start_col+i] for i in range(min_win_streak)]
            print(start_row, start_col, diag)  # DEBUG: Display checked diagonals
            if all(diag[i] == diag[0] for i in range(min_win_streak)):
                print(diag[0], "wins on NW-SE diagonal at", start_row, start_col)

check_backslash_diag(grid, 3)

输出:

0 0 ['x', 'x', 'x']
x wins on NW-SE diagonal at 0 0
0 1 ['-', 'o', 'x']
1 0 ['o', 'o', 'o']
o wins on NW-SE diagonal at 1 0
1 1 ['x', 'x', '-']


文章来源: How to check for win in custom sized tic-tac-toe diagonals