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.

96 lines
2.1 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))
  27. this.board[column][row] = player;
  28. }
  29. public boolean fieldIsEmpty(int column, int row) {
  30. for (char field : this.occupiedFields) {
  31. if (this.board[column][row] == field)
  32. return false;
  33. }
  34. return true;
  35. }
  36. public boolean checkForWin(char player) {
  37. boolean finished = false;
  38. int countFields = 0;
  39. // check columns
  40. for (int i = 0; i < this.board.length; i++) {
  41. for (int j = 0; j < this.board[0].length; j++) {
  42. if (this.board[j][i] == player)
  43. countFields++;
  44. }
  45. if (countFields == this.board.length)
  46. return finished = true;
  47. countFields = 0;
  48. }
  49. // check rows
  50. for (int i = 0; i < this.board[0].length; i++) {
  51. for (int j = 0; j < this.board.length; j++) {
  52. if (this.board[i][j] == player)
  53. countFields++;
  54. }
  55. if (countFields == this.board.length)
  56. return finished = true;
  57. countFields = 0;
  58. }
  59. // check diagonal left
  60. for (int i = this.board.length - 1, j = this.board.length - 1; i >= 0; i--, j--) {
  61. if (this.board[i][j] == player)
  62. countFields++;
  63. }
  64. if (countFields == this.board.length)
  65. return finished = true;
  66. countFields = 0;
  67. // check diagonal right
  68. for (int i = this.board.length - 1, j = 0; i >= 0; i--, j++) {
  69. if (this.board[i][j] == player)
  70. countFields++;
  71. }
  72. if (countFields == this.board.length)
  73. return finished = true;
  74. return finished;
  75. }
  76. public boolean checkEndOfGame() {
  77. // TODO Auto-generated method stub
  78. return false;
  79. }
  80. }