簡體   English   中英

Java Connect 4算法檢查是否成功

[英]Java Connect 4 Algorithm Checking for a win

我試圖在Connect 4游戲中檢查勝利,我設法檢查對角線向右,但是我需要幫助檢查對角線向左,垂直和水平方向,這是改變我已經創建的算法並對其進行調整的問題。 您如何在垂直,水平和對角線左方向檢查?

public class Game {

    private static final int COLS = 7;
    private static final int ROWS = 6;
    public State[][] count = new State[COLS][ROWS];
    boolean player1Turn = true;
    public static final int LEN = 4;
    protected Context context;

    public enum State {
        RED, YELLOW, BLANK;
    }

    public State checkWinner() {
        for (int col = 0; col < count.length; ++col) {
            for (int row = 0; row < count[col].length; ++row) {
                State result = checkWinner(col, row);
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }

    //This method is called in a another class 
    public State checkWinner(int col, int row) {
        State cell = count[col][row];
        if (cell == null || cell == State.BLANK) {
            return null;
        }

        // Here I am checking for a win Diagonally  Right
        // The next step is to check vertically and horizontelly and Diagnollly left
        // There needs to be a pattern of four reds or yellow counters either horizontelly or vertically 
        // My guess to check horizentally or vertically and diagonally left would be to copy this algorithm and possibly change the coordinates 
        // Checking four up for horizontal and four across for vertical, four for diagnoally left
        if ((col + LEN <= COLS) && (row + LEN <= ROWS)) {
            boolean same = true;
            for (int i = 1; i < LEN; ++i) {
                if (count[col + i][row + i] != cell) {
                    same = false;
                    break;
                }
            }
            if (same) {
                return cell;
            }
        }
        // TODO Auto-generated method stub
        return null;
    }
}

假設它是一個4x4的正方形,要檢查對角線的右方,您正在比較從(左上角)位置(0,0)到右下角單元格(4,4)開始的單元格狀態。

要在對角線左方檢查,請進行相反的操作,即從右上角開始,到左下角結束-(0,4)至(4,0)

要垂直檢查,請遍歷每列(0,0)直到(4,0)-對要檢查的每一列都執行此操作。

水平檢查同樣適用,遍歷每行中最左邊的單元格到最右邊的單元格-(0,0)至(0,4),(1,0)至(1,4),依此類推。

希望能幫助到你!

這很簡單。

您的觀點是:(col,row)。

水平檢查:從左到右逐一檢查同一行中的每個單元格,並計數是否有四個以上連續填充的單元格。 如果是,則玩家以水平方法獲勝。

對於垂直而言相同:從上到下逐一檢查同一列中的每個單元格,並計數是否有超過4個連續的填充單元格。 如果是,則玩家以垂直方法獲勝。

暫無
暫無

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

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