PlayField.java 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. public class PlayField {
  2. private int width;
  3. private int height;
  4. private final char[][] fields;
  5. public PlayField(int width, int height) {
  6. this.width = width;
  7. this.height = height;
  8. fields = new char[width][height];
  9. reset();
  10. }
  11. public final void setPos(int x, int y, Player player) {
  12. fields[x][y] = player.getToken();
  13. }
  14. public int getWidth() {
  15. return width;
  16. }
  17. public int getHeight() {
  18. return height;
  19. }
  20. public void print() {
  21. for(int i = 1; i <= width; i++) {
  22. System.out.print("[" + i + "]");
  23. }
  24. System.out.println();
  25. for(int y = 0; y < height; y++) {
  26. for(int x = 0; x < width; x++) {
  27. System.out.print("[" + fields[x][y] + "]");
  28. }
  29. System.out.println();
  30. }
  31. }
  32. public void reset() {
  33. for(int x = 0; x < width; x++) {
  34. for(int y = 0; y < height; y++) {
  35. fields[x][y] = ' ';
  36. }
  37. }
  38. }
  39. public int getFreeY(int x) {
  40. for(int y = height - 1; y >= 0; y--) {
  41. if(fields[x][y] == ' ') {
  42. return y;
  43. }
  44. }
  45. return -1;
  46. }
  47. public boolean isDraw() {
  48. for(int x = 0; x < width; x++) {
  49. if(getFreeY(x) != 1) {
  50. return false;
  51. }
  52. }
  53. return true;
  54. }
  55. public boolean hasWon(Player player, int y, int x) {
  56. for(int dir_x = -1; dir_x <= 1; dir_x++) {
  57. for(int dir_y = -1; dir_y <= 1; dir_y++) {
  58. if(dir_x == 0 && dir_y == 0) {
  59. continue;
  60. }
  61. if(checkDirection(player, y, x, dir_y, dir_x)) {
  62. return true;
  63. }
  64. }
  65. }
  66. return false;
  67. }
  68. private boolean checkDirection(Player player, int x, int y, int dir_x, int dir_y) {
  69. char t = player.getToken();
  70. for(int i = 1; i < 4; i++) {
  71. int new_x = x + i * dir_y;
  72. int new_y = y + i * dir_x;
  73. if(new_x < 0 || new_x >= width || new_y < 0 || new_y >= height
  74. || fields[new_x][new_y] != t) {
  75. return false;
  76. }
  77. }
  78. return true;
  79. }
  80. }