首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对角线Wins的ConnectN检查

对角线Wins的ConnectN检查
EN

Stack Overflow用户
提问于 2020-05-17 01:21:49
回答 1查看 28关注 0票数 1

因此,我目前正在编写代码来检查connect3游戏中的对角获胜,但是由于某些原因,没有显示打印语句,有人可以检查错误的地方吗

代码语言:javascript
复制
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'
代码语言:javascript
复制
# 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')
EN

回答 1

Stack Overflow用户

发布于 2020-05-17 01:31:35

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

代码语言:javascript
复制
>>> 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:

代码语言:javascript
复制
>>> 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?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61840794

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档