我應該使用一維或二維數組?
我認爲你可以是1維或2維數組,並且每個(i,j)都可以訪問你的單元格。在1D中,您必須編碼才能找到陣列的正確索引,而在2D中,只需訪問您的單元格即可。 所以在這個示例代碼中,我使用了一個2D數組。
什麼是資源有效的方式來檢查獲勝條件?
你必須經常檢查固定值(例如布爾值或數字)的單元格值,同等語句的最低組裝結構是檢查零標誌。所以我認爲最有效的isEqual是布爾值。
所以在此示例代碼中,我使用布爾值。由於Gomoku有2名玩家,每個單元格可以有3個值(黑色,懷特,空白),但是我們可以爲每個玩家使用2個布爾數組,每個單元格對於該玩家有2個值(石頭,空)。
public class Main {
final static int row = 15;
final static int column = 15;
final static int win_count = 5;
public static void main(String[] args) {
boolean[][] board1 = new boolean[row][column];
boolean[][] board2 = new boolean[row][column];
/*
* for each change by player1 in (i,j) in the board. (index start from 0
* to 14)
*/
int i = 2;
int j = 3;
Boolean win = checkWin(board1, i, j);
System.out.println("player1 win=" + win);
}
private static Boolean checkWin(boolean[][] board1, int i, int j) {
/**
* 1) check horizontal
*/
int leftBound = 0;
if (j - win_count >= 0)
leftBound = j - win_count;
else
leftBound = 0;
int rightBound = 0;
if (j + win_count < column)
rightBound = j + win_count;
else
rightBound = column - 1;
int hitCount = 0;
int jk = j;
// go left
while (jk >= leftBound && hitCount < win_count) {
if (board1[i][jk]) {
hitCount++;
jk--;
} else {
jk = j;
break;
}
}
// go right
while (jk <= rightBound && hitCount < win_count) {
if (board1[i][jk]) {
hitCount++;
jk++;
} else {
break;
}
}
if (hitCount >= win_count)
return true;
/**
* 2) check vertical
*/
/**
* 3) check principal diagonal
*/
/**
* 4) check minor diagonal
*/
// otherwise:
return false;
}
}
我寫了這段代碼的結構,你應該完成其他標記爲註釋的部分。
我希望這個示例代碼可以幫助你。
您應該使用二維數組。如果您使用15 * 15陣列,我認爲您不應該對資源進行大量的思考。編寫簡單易讀的代碼更好。 – coolguy