我目前正在构建一个黑白棋游戏,其中棋盘是一个 8x8 整数系列(0 表示空白,1 表示白色,2 表示黑色)。我已经弄清楚如何获得垂直和水平以检查移动并进行移动,但无法弄清楚如何让对角线工作。
package OthelloTesting;
public class OthelloGameHandler {
private int[][] gameBoard = new int[8][8];
public OthelloGameHandler() {
}
public void setBoard(int[][] newBoard) {
gameBoard = newBoard;
}
public int[][] getBoard() {
return gameBoard;
}
private final boolean inBounds(int row, int col) {
return row >= 0 && col >= 0 && row < gameBoard.length && col < gameBoard.length;
}
/*
* Color is: 0 - Empty | 1 - White | 2 - Black Return Messages: 0 - Okay | 1
* - Piece in Spot | 2 - Not Valid Placement
*/
public int move(int color, int row, int col) {
// Check if spot is full
int oppColor = (color == 1) ? 2 : 1;
int returnCode = 2;
if (gameBoard[row][col] != 0) {
returnCode = 1;
}
if (!inBounds(row, col)) {
returnCode = 2;
}
// Check if move is Valid...
// Check Right Horizontal
if (col < 6 && gameBoard[row][col + 1] != 0 &&
gameBoard[row][col + 1] == oppColor) {
for (int pos = col + 2; pos < 8; pos++) {
if (gameBoard[row][pos] == 0) {
break;
}
if (gameBoard[row][pos] == color) {
fill(color, row, col, row, pos);
returnCode = 0;
}
}
}
// Check Left Horizontal
if (col > 1 && gameBoard[row][col - 1] != 0 &&
gameBoard[row][col - 1] == oppColor) {
for (int pos = col - 2; pos > -1; pos--) {
if (gameBoard[row][pos] == 0) {
break;
}
if (gameBoard[row][pos] == color) {
fill(color, row, pos, row, col);
returnCode = 0;
}
}
}
// Check Bottom Vertical
if (row < 6 && gameBoard[row + 1][col] != 0 && gameBoard[row + 1][col] == oppColor) {
for (int pos = row + 2; pos < 8; pos++) {
System.out.println("did");
if (gameBoard[pos][col] == 0) {
break;
}
if (gameBoard[pos][col] == color) {
fill(color, row, col, pos, col);
returnCode = 0;
}
}
}
// Check Top Vertical
if (row > 1 && gameBoard[row - 1][col] != 0 && gameBoard[row - 1][col] == oppColor) {
for (int pos = row - 2; pos > -1; pos++) {
System.out.println("did");
if (gameBoard[pos][col] == 0) {
break;
}
if (gameBoard[pos][col] == color) {
fill(color, pos, col, row, col);
returnCode = 0;
}
}
}
// Check Upper Right Diagonal
// Check Upper Left Diagonal
// Check Lower Left Diagonal
// Check Lower Right Diagonal
return returnCode;
}
private void fill(int color, int r1, int c1, int r2, int c2) {
// Horizontal Filling
if (r1 == r2) {
for (int pos = c1; pos <= c2; pos++) {
gameBoard[r1][pos] = color;
}
}
if (c1 == c2) {
for (int pos = r1; pos <= r2; pos++) {
gameBoard[pos][c1] = color;
}
}
}
}