簡體   English   中英

連接4檢查獲勝算法

[英]Connect 4 Checking for a win algorithm

我正在制作一個Connect 4游戲,並且我正在嘗試檢查獲勝,到目前為止,我已經能夠在游戲板上的任何地方對角線進行檢查,現在如何在水平和垂直方向上對角向左進行檢查,我嘗試反轉方向檢查對角線左,但沒有用? 我可以更改哪些以向左檢查? 水平和垂直

//Column Size
private static final int COLS = 7; 
//Row Size
private static final int ROWS = 6; 
//Dynamic Array
private State [][]count = new State[COLS][ROWS];
//Length of Pattern to check FOUR counters in a row
public static final int LEN=4;


//trajectory
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;
}

public State checkWinner(int col, int row) {
    State cell = count[col][row];
    if (cell==null ||cell==State.BLANK) { return null; }

    // check Diagonally Right 
    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;
        }   
    }
    return null;
}

我可以推薦一種更簡單的方法。 僅有少量的可能的獲勝方式:水平24個,垂直21個和對角線12個,總共有69種可能性。

如果將紅色和黑色表示為兩個單獨的位字段,則每個字段總共有42位(存在或不存在),可以存儲在int 創建69個位掩碼,每個獲勝圖案一個,然后將每個掩碼與紅色(或黑色)的棋盤位置相抵並設為整數。

您在checkWinner(int col,int row)中的循環僅檢查三個位置。 它應從i = 0而不是i = 1開始。要垂直檢查,請使用count [col] [row + i],要水平檢查,請使用count [col + i] [row]。 反向檢查時,請務必在循環之前修改if語句。

暫無
暫無

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

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