You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
2.1 KiB
97 lines
2.1 KiB
package de.tims.tictactoe;
|
|
|
|
public class GameLogic {
|
|
|
|
private static final char PLAYER_1 = 'x';
|
|
private static final char PLAYER_2 = 'o';
|
|
private char[][] board;
|
|
private final char[] occupiedFields = { PLAYER_1, PLAYER_2 };
|
|
|
|
public GameLogic(int size) {
|
|
if (size < 3) {
|
|
size = 3;
|
|
}
|
|
this.board = new char[size][size];
|
|
|
|
for (int i = 0; i < this.board.length; i++) {
|
|
for (int j = 0; j < this.board[0].length; j++) {
|
|
this.setField(i, j, '-');
|
|
}
|
|
}
|
|
}
|
|
|
|
public GameLogic(char[][] board) {
|
|
this.board = board;
|
|
}
|
|
|
|
public char[][] getBoard() {
|
|
return this.board;
|
|
}
|
|
|
|
public int countFields() {
|
|
return this.board[0].length * this.board.length;
|
|
}
|
|
|
|
public void setField(int column, int row, char player) {
|
|
if (fieldIsEmpty(column, row))
|
|
this.board[column][row] = player;
|
|
}
|
|
|
|
public boolean fieldIsEmpty(int column, int row) {
|
|
for (char field : this.occupiedFields) {
|
|
if (this.board[column][row] == field)
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public boolean checkForWin(char player) {
|
|
boolean won = false;
|
|
int countFields = 0;
|
|
|
|
// check columns
|
|
for (int i = 0; i < this.board.length; i++) {
|
|
for (int j = 0; j < this.board[0].length; j++) {
|
|
if (this.board[j][i] == player)
|
|
countFields++;
|
|
}
|
|
if (countFields == this.board.length)
|
|
return won = true;
|
|
countFields = 0;
|
|
}
|
|
// check rows
|
|
for (int i = 0; i < this.board[0].length; i++) {
|
|
for (int j = 0; j < this.board.length; j++) {
|
|
if (this.board[i][j] == player)
|
|
countFields++;
|
|
}
|
|
if (countFields == this.board.length)
|
|
return won = true;
|
|
countFields = 0;
|
|
}
|
|
|
|
// check diagonal left
|
|
for (int i = this.board.length - 1, j = this.board.length - 1; i >= 0; i--, j--) {
|
|
if (this.board[i][j] == player)
|
|
countFields++;
|
|
}
|
|
if (countFields == this.board.length)
|
|
return won = true;
|
|
countFields = 0;
|
|
|
|
// check diagonal right
|
|
for (int i = this.board.length - 1, j = 0; i >= 0; i--, j++) {
|
|
if (this.board[i][j] == player)
|
|
countFields++;
|
|
}
|
|
if (countFields == this.board.length)
|
|
return won = true;
|
|
|
|
return won;
|
|
}
|
|
|
|
public boolean checkEndOfGame() {
|
|
return checkForWin(PLAYER_1) || checkForWin(PLAYER_2);
|
|
}
|
|
|
|
}
|