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.

83 lines
2.0 KiB

  1. package de.tims.tictactoe;
  2. public class GameLogic {
  3. private char[][] board;
  4. private final char[] occupiedFields = { 'x', 'o' };
  5. public GameLogic(int size) {
  6. if (size < 3) {
  7. size = 3;
  8. }
  9. this.board = new char[size][size];
  10. for (int i = 0; i < this.board.length; i++) {
  11. for (int j = 0; j < this.board[0].length; j++) {
  12. this.setField(i, j, '-');
  13. }
  14. }
  15. }
  16. public GameLogic(char[][] board) {
  17. this.board = board;
  18. }
  19. public char[][] getBoard() {
  20. return this.board;
  21. }
  22. public int countFields() {
  23. return this.board[0].length * this.board.length;
  24. }
  25. public void setField(int column, int row, char player) {
  26. if(fieldIsEmpty(column, row)) this.board[column][row] = player;
  27. }
  28. public boolean fieldIsEmpty(int column, int row) {
  29. for (char field : this.occupiedFields) {
  30. if (this.board[column][row] == field) return false;
  31. }
  32. return true;
  33. }
  34. public boolean checkForWin(char player) {
  35. boolean finished = false;
  36. int countFields = 0;
  37. // check columns
  38. for (int i = 0; i < this.board.length; i++) {
  39. for (int j = 0; j < this.board[0].length; j++) {
  40. if(board[j][i] == player) countFields++;
  41. }
  42. if(countFields == this.board.length) return finished = true;
  43. countFields = 0;
  44. }
  45. countFields = 0;
  46. // check rows
  47. for (int i = 0; i < this.board[0].length; i++) {
  48. for (int j = 0; j < this.board.length; j++) {
  49. if(board[i][j] == player) countFields++;
  50. }
  51. if(countFields == this.board.length) return finished = true;
  52. countFields = 0;
  53. }
  54. // check diagonal left
  55. for (int i = this.board.length - 1, j = this.board.length - 1; i >= 0 ; i--, j--) {
  56. if (board[i][j] == player) countFields++;
  57. }
  58. if(countFields == this.board.length) return finished = true;
  59. countFields = 0;
  60. // check diagonal right
  61. for (int i = this.board.length - 1, j = 0; i >= 0 ; i--, j++) {
  62. if (board[i][j] == player) countFields++;
  63. }
  64. if(countFields == this.board.length) return finished = true;
  65. return finished;
  66. }
  67. }