( ) , 8.
, . , 2D-
static final class WinCombos {
int[][][] positions = {
{ {0, 0}, {0, 1}, {0, 2} },
{ {0, 0}, {1, 1}, {2, 2} },
{ {0, 0}, {1, 0}, {2, 0} },
{ {....}, {....}, {....} }
};
}
, , . , .
, , , :
boolean xWon = false;
boolean oWon = false;
for (int[][] combo : WinCombos.positions) {
xWon = oWon = true;
for (int[] coord : combo) {
if (!"X".equals(board[coord[0]][coord[1]])) {
xWon = false;
}
if (!"O".equals(board[coord[0]][coord[1]])) {
oWon = false;
}
}
if (oWon || xWon) break;
}
if (xWon) {
System.out.println("X won!");
} else if (oWon) {
System.out.println("O won!");
}
Now, if you want the board to resize, you need to reset the winning coordinates every time the board size changes. Tic-tac-toe will be relatively simple, because winning combinations should always be the length of the board.
So you need some loops:
public final class WinCombos {
public int[][][] positions;
static {
findCombos(3);
}
public static final void findCombos(int blen) {
int combos = blen * 2 + 2;
positions = new int[combos][blen][];
for (int i = 0; i < blen; i++) {
for (int k = 0; k < blen; k++) {
positions[i][k] = new int[] { i, k };
positions[i + blen][k] = new int[] { k, i };
}
}
for (int i = blen - 2; i < blen; i++) {
for (int k = 0; k < blen; k++) {
positions[i][k] = new int[] { k, k };
}
}
}
}
And you go there. I have not tested this.
source
share