簡體   English   中英

如何檢查連接四中的對角線

[英]How to Check Diagonals in Connect Four

我已經檢查了獲勝者的行和列,但我對如何求解對角線的線索為零。 以下是我的獲勝者判定 function:

def winner(board):
    """This function accepts the Connect Four board as a parameter.
    If there is no winner, the function will return the empty string "".
    If the user has won, it will return 'X', and if the computer has
    won it will return 'O'."""
    for row in range(7):
        count = 0
        last = ''
        for col in range(7):
            row_win = board[row][col]
            if row_win == " ":
                count = 0
                continue
            if row_win == last:
                count += 1
            else:
                count = 1
            if count >= 4:
                return row_win
            last = row_win

    for col in range(7):
        count = 0
        last = ''
        for row in range(7):
            col_win = board[row][col]
            if col_win == " ":
                count = 0
                continue
            if col_win == last:
                count += 1
            else:
                count = 1
            if count >= 4:
                return col_win
            last = col_win

我想不出一種方法來檢查對角線是否獲勝。 如果您需要任何參考,這里是代碼的 rest: https://paste.pythondiscord.com/epihuvujal.py任何提示將不勝感激!

這是一個簡單的示例,您可以嘗試並修改以適應您的需求:

def winner(board, length):
    """Returns the 'mark' of the winning player"""
    W = range(len(board))     # width
    H = range(len(board[0]))  # height
    directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
    
    for dx, dy in directions:
        edges = []  
        
        if dx > 0:
            edges += [(0, y) for y in H]
            
        if dy > 0:   # scanning down
            edges += [(x, 0) for x in W]
            
        if dy < 0:   # scanning up
            edges += [(x, H[-1]) for x in W]
            
        for ex, ey in edges: 
            row = 0; mark = None
            x, y = ex, ey
            
            while x in W and y in H:
                if board[x][y] == mark:
                    row += 1
                else:
                    mark = board[x][y]
                    row = 1
                if mark is not None and row >= length:
                    return mark
                x, y = x + dx, y + dy
    return None

print(winner([
    ['X', 'O', 'O', 'O'],
    ['O', 'X', 'O', 'X'],
    ['O', 'O', 'X', 'O'],
    ['O', 'X', 'X', 'X'] ], 4))  # X

要檢查對角線,您需要一個嵌套循環。

for 循環可以完成工作,但 while 循環也可以。

您需要的 for 循環不是代碼中的循環,而是帶有 i 和 j 用於迭代的循環。

請注意,從值 board[i][j] 開始,有 4 個對角線要檢查。

左上角、右上角、左下角和右下角的那個。

您可以通過每次從 i 和 j 中添加 1 或減去它來訪問它們。

像這個 board[i+1][j+1] 和 board[i][j] 和 board[i-1][j-1] 在同一個對角線上。

您可以訪問盡可能多的值(如果它是 connect 3 或 4 或 K )

但要小心不要超出棋盤邊界(也許你可以使用 try - catch)。

如果對角線被檢查兩次,不要害怕,因為您的代碼最終會檢查新的對角線。

您還可以添加您之前訪問過的診斷列表,這樣它就不會重復工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM