【问题标题】:ConnectN Checking for Diagonal WinsConnectN 检查对角线获胜
【发布时间】:2020-09-02 13:14:17
【问题描述】:

所以我目前正在编写代码来检查 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')

【问题讨论】:

    标签: python list


    【解决方案1】:

    您的代码只测试第一个对角线(从右上角开始):

    >>> 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?

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多