问题描述
我有一个连接四板",这是一个6 * 7 2D字符数组,其中填充有X或O两个空格.当垂直,水平或垂直连续四个X或四个O时,满足获胜条件.对角地.我设法成功检查了垂直和水平方向的获胜条件,其中通过以下方法返回了获胜的字符:
I have a Connect Four "board" which is a 6*7 2D char array populated with either spaces, X or O. The win condition is met when there are either four Xs or four Os in a row vertically, horizontally or diagonally. I've managed to get the win conditions checked successfully for vertical and horizontal, where the winning char is returned by some methods as below:
private char CheckVerticalWinner(char[][] currentBoard) {
// check vertical (move down one row, same column)
char vWinner = ' ';
for (int col=0; col<7; col++) {
int vCount = 0;
for (int row=0; row<5; row++) {
if (currentBoard[row][col]!=' ' &&
currentBoard[row][col] == currentBoard[row+1][col]) {
vCount++;
System.out.println("VERT "+vCount); //test
} else {
vCount = 1;
}
if (vCount>=4) {
vWinner = currentBoard[row][col];
}
}
}
return vWinner;
}
private char CheckHorizontalWinner(char[][] currentBoard) {
// check horizontal (move across one column, same row)
char hWinner = ' ';
for (int row=0; row<6; row++) {
int hCount = 0;
for (int col=0; col<6; col++) {
if (currentBoard[row][col]!=' ' &&
currentBoard[row][col] == currentBoard[row][col+1]) {
hCount++;
System.out.println("HORIZ "+hCount); //test
} else {
hCount = 1;
}
if (hCount>= 4) {
hWinner = currentBoard[row][col];
}
}
}
return hWinner;
}
我只是停留在如何检查对角线胜利的问题上,而不会抛出ArrayIndexOutOfBoundsException.我知道我需要遍历2D数组两次,一次是对前对角线,一次是对后对角线 4平方或更多,如下图所示:
I'm just stuck on how to check for diagonal wins, without throwing an ArrayIndexOutOfBoundsException. I know I need to iterate through the 2D array twice, once for forward diagonals and once for backward diagonals that are 4 squares long or more, like in the below diagram:
基本上,我该如何填写此方法以返回获胜的字符?
Basically, how would I fill in this method to return a winning char?
private char CheckDiagonalWinner(char[][] currentBoard) {
// some iteration here
return dWinner;
}
任何帮助将不胜感激!
推荐答案
最简单的算法可能是:
for every direction
for every coordinate
check whether the next 3 elements in this direction exist and are the same
使用代码:
final int maxx = 7;
final int maxy = 6;
char winner(char[][] board) {
int[][] directions = {{1,0}, {1,-1}, {1,1}, {0,1}};
for (int[] d : directions) {
int dx = d[0];
int dy = d[1];
for (int x = 0; x < maxx; x++) {
for (int y = 0; y < maxy; y++) {
int lastx = x + 3*dx;
int lasty = y + 3*dy;
if (0 <= lastx && lastx < maxx && 0 <= lasty && lasty < maxy) {
char w = board[x][y];
if (w != ' ' && w == board[x+dx][y+dy]
&& w == board[x+2*dx][y+2*dy]
&& w == board[lastx][lasty]) {
return w;
}
}
}
}
}
return ' '; // no winner
}
这篇关于Java:如何检查对角线连接二维阵列中的四连胜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!