Browse Source

tictactoe: refactoring: formatted code and removed unused lines

tictactoe
Malte Schellhardt 3 years ago
committed by Lorenz Hohmann
parent
commit
864906fb98
  1. 56
      src/main/java/de/tims/tictactoe/GameLogic.java

56
src/main/java/de/tims/tictactoe/GameLogic.java

@ -1,7 +1,7 @@
package de.tims.tictactoe;
public class GameLogic {
private char[][] board;
private final char[] occupiedFields = { 'x', 'o' };
@ -10,7 +10,7 @@ public class GameLogic {
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, '-');
@ -31,16 +31,18 @@ public class GameLogic {
}
public void setField(int column, int row, char player) {
if(fieldIsEmpty(column, row)) this.board[column][row] = 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;
if (this.board[column][row] == field)
return false;
}
return true;
}
public boolean checkForWin(char player) {
boolean finished = false;
int countFields = 0;
@ -48,34 +50,40 @@ public class GameLogic {
// check columns
for (int i = 0; i < this.board.length; i++) {
for (int j = 0; j < this.board[0].length; j++) {
if(board[j][i] == player) countFields++;
if (this.board[j][i] == player)
countFields++;
}
if(countFields == this.board.length) return finished = true;
countFields = 0;
if (countFields == this.board.length)
return finished = true;
countFields = 0;
}
countFields = 0;
// check rows
for (int i = 0; i < this.board[0].length; i++) {
for (int j = 0; j < this.board.length; j++) {
if(board[i][j] == player) countFields++;
if (this.board[i][j] == player)
countFields++;
}
if(countFields == this.board.length) return finished = true;
if (countFields == this.board.length)
return finished = true;
countFields = 0;
}
// check diagonal left
for (int i = this.board.length - 1, j = this.board.length - 1; i >= 0 ; i--, j--) {
if (board[i][j] == player) countFields++;
}
if(countFields == this.board.length) return finished = true;
countFields = 0;
// check diagonal right
for (int i = this.board.length - 1, j = 0; i >= 0 ; i--, j++) {
if (board[i][j] == player) countFields++;
}
if(countFields == this.board.length) return finished = true;
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 finished = 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 finished = true;
return finished;
}

Loading…
Cancel
Save