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.

619 lines
23 KiB

  1. /**
  2. * @file Board.java
  3. *
  4. * @author
  5. * Anastasia Foti AEM:8959
  6. * <anastaskf@ece.auth.gr>
  7. *
  8. * @author
  9. * Christos Choutouridis AEM:8997
  10. * <cchoutou@ece.auth.gr>
  11. */
  12. package host.labyrinth;
  13. import java.util.ArrayList;
  14. import java.util.Arrays;
  15. import java.util.function.IntFunction;
  16. /**
  17. * @brief
  18. * This class is the representation of the games's board
  19. *
  20. * The board is the square arrangement of the tiles. This class is also
  21. * the owner of the tile and supply objects.
  22. */
  23. class Board {
  24. /** @name Constructors */
  25. /** @{ */
  26. /**
  27. * The empty constructor for default initialization
  28. */
  29. Board() {
  30. this.N = 0;
  31. this.S = 0;
  32. this.W = 0;
  33. tiles = null;
  34. supplies =null;
  35. walls = new ArrayList<Edge>();
  36. moves = new ArrayList<Integer[]>();
  37. }
  38. /**
  39. * The main constructor for the application
  40. * @param N The size of each edge of the board
  41. * @param S The number of supplies on the board
  42. */
  43. Board(int N, int S) {
  44. assert (N%2 != 0) : "Board's size has to be an odd number.";
  45. assert (S <= (N*N-2)) : "At least 2 tiles has to be without supplies.";
  46. this.N = Session.boardSize = N;
  47. this.S = S;
  48. this.W = 0;
  49. tiles = new Tile[N*N];
  50. supplies = new Supply[S];
  51. walls = new ArrayList<Edge>();
  52. moves = new ArrayList<Integer[]>();
  53. }
  54. /**
  55. * Deep copy constructor
  56. * @param b The board to copy
  57. *
  58. * @note
  59. * The lack of value semantics in java is (in author's opinion) one of the greatest
  60. * weakness of the language and one of the reasons why it will never be a language
  61. * to care about. To quote Alexander Stepanof's words in "elements of programming" section 1.5:
  62. * "Assignment is a procedure that takes two objects of the same type and makes the first
  63. * object equal to the second without modifying the second".
  64. * In this class we try to cope with this situation knowing that we can not do anything about
  65. * assignment operator. We just add value semantics to the copy constructor and go on with our lifes...
  66. */
  67. Board(Board b) {
  68. // Copy primitives
  69. this.N = b.N;
  70. this.S = b.S;
  71. this.W = b.W;
  72. // Clone arrays
  73. this.tiles = b.tiles.clone();
  74. this.supplies = b.supplies.clone();
  75. for (Edge it: b.walls)
  76. this.walls.add(new Edge(it));
  77. for (Integer[] m : b.moves) {
  78. this.moves.add(m);
  79. }
  80. }
  81. /** @} */
  82. /** @name Board's main application interface */
  83. /** @{ */
  84. /**
  85. * Creates the board with all the requested walls and supplies.
  86. *
  87. * @param theseusTile
  88. * @param minotaurTile
  89. */
  90. void createBoard(int theseusTile, int minotaurTile) {
  91. createTiles();
  92. createSupplies(theseusTile, minotaurTile);
  93. }
  94. /**
  95. * Returns a 2-D array with the string representation of the board.
  96. *
  97. * The rows of the array represent the Y-coordinate and the columns the X-coordinate.
  98. * The only difference is that between each row there is an extra row with the possible
  99. * walls. This way the number of rows of the returning array are 2N+1 and the number of
  100. * columns N+1.\n
  101. * So each tile of the board is represented by 3 strings. One for the north wall, one for
  102. * the body and one for the south wall.
  103. *
  104. * @param theseusTile The current Theseus tile
  105. * @param minotaurTile The current Minotaur tile
  106. * @return The string representation of the board
  107. */
  108. String[][] getStringRepresentation(int theseusTile, int minotaurTile) {
  109. String[][] frame = new String[2*N+1][N];
  110. for (int row=0 ; row<N ; ++row) {
  111. int col;
  112. for (col =0 ; col<N-1 ; ++col)
  113. renderTile(frame, row, col, theseusTile, minotaurTile);
  114. renderSentinelTile(frame, row, col, theseusTile, minotaurTile);
  115. }
  116. return frame;
  117. }
  118. /**
  119. * Print board utility.
  120. * @param sBoard Reference to string representation of the board to print.
  121. *
  122. * @note
  123. * As the lower row addresses of the string representation of the board contain
  124. * the south rows, in order to view the board correctly we have to print the rows
  125. * in the opposite order.
  126. */
  127. void printBoard (String[][] sBoard) {
  128. for (int i=sBoard.length-1 ; i>=0 ; --i) {
  129. for (String it : sBoard[i])
  130. System.out.print(it);
  131. System.out.println();
  132. }
  133. }
  134. /**
  135. * Predicate to check if a direction is Walkable.
  136. *
  137. * A `walkable` direction is a tile direction where:
  138. * <ul>
  139. * <li>The wall is not the DOWN wall from tile (0, 0).
  140. * <li>There is not already a wall in the desired direction. (Implies no sentinel tile).
  141. * </ul>
  142. *
  143. * @param tileId The starting tileId.
  144. * @param direction The desired direction.
  145. * @return True if it is walkable.
  146. */
  147. boolean isWalkable(int tileId, int direction) {
  148. return !tiles[tileId].hasWall(direction)
  149. && !(tileId == 0 && direction == Direction.DOWN);
  150. }
  151. /**
  152. * Predicate to check if a direction is Walkable.
  153. *
  154. * A `walkable` direction is a tile direction where:
  155. * <ul>
  156. * <li>The wall is not the DOWN wall from tile (0, 0).
  157. * <li>There is not already a wall in the desired direction. (Implies no sentinel tile).
  158. * </ul>
  159. *
  160. * @param row Row position of the starting tile.
  161. * @param col Column position of the starting tile.
  162. * @param direction The desired direction.
  163. * @return True if it is walkable.
  164. */
  165. boolean isWalkable(int row, int col, int direction) {
  166. return !tiles[Position.toID(row, col)].hasWall(direction)
  167. && !(Position.toID(row, col) == 0 && direction == Direction.DOWN);
  168. }
  169. /**
  170. * Utility function to check if there is a supply on the tile or not
  171. * @param tileId The tile to check
  172. * @return Yes/no
  173. */
  174. boolean hasSupply (int tileId) {
  175. return (Const.noSupply != tiles[tileId].hasSupply(supplies)) ? true : false;
  176. }
  177. /**
  178. * Try to pick supply from a tile. If succeed it also erases the
  179. * supply from the board.
  180. *
  181. * @param tileId The tile to check
  182. * @return The id of supply.
  183. * @arg Const.noSupply if there is none
  184. * @arg The ID of supply if there is one.
  185. */
  186. int tryPickSupply(int tileId) {
  187. int supplyId = tiles[tileId].hasSupply(supplies);
  188. if (supplyId != Const.noSupply) {
  189. tiles[tileId].pickSupply(supplies, supplyId);
  190. }
  191. return supplyId;
  192. }
  193. /**
  194. * A plain fair dice functionality provided by the board.
  195. * @return A random direction;
  196. */
  197. int dice () {
  198. ShuffledRange d = new ShuffledRange(DirRange.Begin, DirRange.End, DirRange.Step);
  199. return d.get();
  200. }
  201. /** @return the size of each site of the board. */
  202. int size () { return N; }
  203. int[][] getOpponentMoves (int playerId) {
  204. int[][] ret = new int[moves.size()-1][Const.moveItems];
  205. int ii= 0, ri =0;
  206. for (Integer[] m : moves) {
  207. if (ii != playerId)
  208. ret[ri++] = Arrays.stream(m).mapToInt(i->i).toArray();
  209. ++ii;
  210. }
  211. return ret;
  212. }
  213. int generatePlayerId () {
  214. moves.add(null);
  215. return moves.size() -1;
  216. }
  217. void updateMove(int[] m, int playerId) {
  218. moves.set(playerId, Arrays.stream(m).boxed().toArray(Integer[]::new));
  219. }
  220. /** @} */
  221. /**
  222. * @name Accessor/Mutator interface
  223. * @note
  224. * Please consider not to use mutator interface. Its the abstraction killer :(
  225. */
  226. /** @{ */
  227. int getN() { return N; }
  228. int getS() { return S; }
  229. int getW() { return W; }
  230. /**
  231. * @note Use it with care. Any use of this function results to what Sean Parent calls "incidental data-structure".
  232. * <a href="https://github.com/sean-parent/sean-parent.github.io/blob/master/better-code/03-data-structures.md"> see also here</a>
  233. * @return Reference to inner tiles array.
  234. */
  235. Tile[] getTiles() { return tiles; }
  236. /**
  237. * @note Use it with care. Any use of this function results to what Sean Parent calls "incidental data-structure".
  238. * <a href="https://github.com/sean-parent/sean-parent.github.io/blob/master/better-code/03-data-structures.md"> see also here</a>
  239. * @return Reference to inner supplies array.
  240. */
  241. Supply[] getSupplies() { return supplies; }
  242. /**
  243. * @note Use it with care. Any use of this function results to what Sean Parent calls "incidental data-structure".
  244. * <a href="https://github.com/sean-parent/sean-parent.github.io/blob/master/better-code/03-data-structures.md"> see also here</a>
  245. * @return Reference to inner walls array.
  246. */
  247. ArrayList<Edge> getWalls() { return walls; }
  248. /**
  249. * @note Use it with care. Any use of this function results to what Sean Parent calls "incidental data-structure".
  250. * <a href="https://github.com/sean-parent/sean-parent.github.io/blob/master/better-code/03-data-structures.md"> see also here</a>
  251. * @return Reference to inner walls array.
  252. */
  253. ArrayList<Integer[]> getMoves() { return moves; }
  254. void setN(int N) { this.N = N; }
  255. void setS(int S) { this.S = S; }
  256. void setW(int W) { this.W = W; }
  257. /**
  258. * @param tiles Reference to tiles that we want to act as replacement for the inner tiles array.
  259. * @note Use with care.
  260. * Any call to this function will probably add memory for the garbage collector.
  261. */
  262. void setTiles(Tile[] tiles) { this.tiles = tiles; }
  263. /**
  264. * @param supplies Reference to supplies that we want to act as replacement for the inner supplies array.
  265. * @note Use with care.
  266. * Any call to this function will probably add memory for the garbage collector.
  267. */
  268. void setSupplies(Supply[] supplies) { this.supplies= supplies; }
  269. /**
  270. * @param walls Reference to walls that we want to act as replacement for the inner walls vector.
  271. * @note Use with care.
  272. * Any call to this function will probably add memory for the garbage collector.
  273. */
  274. void setWalls (ArrayList<Edge> walls) { this.walls= walls; }
  275. /**
  276. * @param moves Reference to moves that we want to act as replacement for the inner moves vector.
  277. * @note Use with care.
  278. * Any call to this function will probably add memory for the garbage collector.
  279. */
  280. void setMoves(ArrayList<Integer[]> moves) { this.moves =moves; }
  281. /** @} */
  282. /** @name Sentinel predicates */
  283. /** @{ */
  284. private boolean isLeftSentinel (int tileId) { return (Position.toCol(tileId) == 0); }
  285. private boolean isRightSentinel (int tileId) { return (Position.toCol(tileId) == N-1); }
  286. private boolean isUpSentinel (int tileId) { return (Position.toRow(tileId) == N-1); }
  287. private boolean isDownSentinel (int tileId) { return (Position.toRow(tileId) == 0); }
  288. /** @} */
  289. /**
  290. * @name private functionality of the object
  291. */
  292. /** @{ */
  293. /**
  294. * This function creates randomly all the tiles of the board
  295. */
  296. private void createTiles() {
  297. int wallCount;
  298. wallCount = createBasicTileWalls (); // First create tiles with outer walls
  299. wallCount += createInnerWalls(); // Greedy create as many inner walls we can
  300. W = wallCount;
  301. }
  302. /**
  303. * This function create randomly the board's supplies.
  304. *
  305. * The supplies has to be in separate tiles and in tiles with no player
  306. *
  307. * @param theseusTile The tile of the Theseus
  308. * @param minotaurTile The tile of the Minotaur
  309. */
  310. private void createSupplies(int theseusTile, int minotaurTile) {
  311. ShuffledRange rand = new ShuffledRange(0, N*N); // Make a shuffled range of all tiles
  312. for (int tileId, i=0 ; i<supplies.length ; ++i) {
  313. // Pick a tile as long as there is no player in it
  314. do
  315. tileId = rand.get();
  316. while (tileId == theseusTile || tileId == minotaurTile);
  317. supplies[i] = new Supply(i, tileId);
  318. }
  319. }
  320. /**
  321. * Predicate to check if a wall creates a closed room.
  322. *
  323. * This algorithm has a complexity of @f$ O(N^2logN) @f$ where N represents the total
  324. * number of tiles.
  325. * It should be used with care.
  326. *
  327. * @param tileId The tileId of the wall.
  328. * @param direction The wall's relative direction.
  329. * @return True if the wall creates a closed room, false otherwise.
  330. */
  331. private boolean isRoomCreator (int tileId, int direction) {
  332. // Clone the list of all the walls locally.
  333. ArrayList<Edge> w = new ArrayList<Edge>();
  334. for (Edge it : walls)
  335. w.add(new Edge(it));
  336. // Create the largest possible coherent graph from the list of walls(edges)
  337. Graph g = new Graph(new Edge(tileId, direction));
  338. int size;
  339. do {
  340. size = w.size(); // mark the size (before the pass)
  341. for (int i =0, S=w.size() ; i<S ; ++i) // for each edge(wall) on the local wall list
  342. if (g.attach(w.get(i))) { // can we attach the edge(wall) to the graph ?
  343. w.remove(i); // if yes remove it from the local wall list
  344. --i; --S; // decrease iterator and size to match ArrayList's new values
  345. }
  346. } while (size != w.size()); // If the size hasn't change(no new graph leafs) exit
  347. // Search if a vertex is attached to the graph more than once.
  348. // This means that there is at least 2 links to the same node
  349. // so the graph has a closed loop
  350. for (Edge it : walls) {
  351. if (g.count(it.getV1()) > 1) return true;
  352. if (g.count(it.getV2()) > 1) return true;
  353. }
  354. return false;
  355. }
  356. /**
  357. * Predicate to check if a tile direction is `Wallable`.
  358. *
  359. * A `wallable` direction is a tile direction where:
  360. * <ul>
  361. * <li>The wall is not the DOWN wall from tile (0, 0).
  362. * <li>There is not already a wall in the desired direction. (Implies no sentinel tile).
  363. * <li>The neighbor in this direction has at most `Const.maxTileWalls -1` walls.
  364. * <li>The wall does not create a closed room (Optional requirement).
  365. * </ul>
  366. *
  367. * @note
  368. * A wallable direction automatically implies that the direction in not an outer wall.
  369. *
  370. * @param tileId The tile to check.
  371. * @param direction The direction to check
  372. * @return True if the direction is wallable.
  373. */
  374. private boolean isWallableDir (int tileId, int direction) {
  375. // Check list
  376. if (!isWalkable(tileId, direction))
  377. return false;
  378. switch (direction) {
  379. case Direction.UP:
  380. if (tiles[upTileId.apply(tileId)].hasWalls() >= Const.maxTileWalls) return false;
  381. break;
  382. case Direction.DOWN:
  383. if (tiles[downTileId.apply(tileId)].hasWalls() >= Const.maxTileWalls) return false;
  384. break;
  385. case Direction.LEFT:
  386. if (tiles[leftTileId.apply(tileId)].hasWalls() >= Const.maxTileWalls) return false;
  387. break;
  388. case Direction.RIGHT:
  389. if (tiles[rightTileId.apply(tileId)].hasWalls() >= Const.maxTileWalls) return false;
  390. break;
  391. }
  392. if (Session.loopGuard && isRoomCreator(tileId, direction))
  393. return false;
  394. return true;
  395. }
  396. /**
  397. * Predicate to check if a tile is `Wallable`.
  398. *
  399. * A `wallable` tile is a tile where:
  400. * <ul>
  401. * <li>The tile has at most `Const.maxTileWalls -1` walls.
  402. * <li>There is at least one wallable direction on the tile.
  403. * </ul>
  404. * @param tileId The tile to check
  405. * @return True if the tile is wallable.
  406. */
  407. private boolean isWallable (int tileId) {
  408. // Check list
  409. if (tileId == Const.noTileId)
  410. return false;
  411. if (tiles[tileId].hasWalls() >= Const.maxTileWalls)
  412. return false;
  413. Range dirs = new Range(DirRange.Begin, DirRange.End, DirRange.Step);
  414. for (int dir = dirs.get() ; dir != Const.EOR ; dir = dirs.get())
  415. if (isWallableDir(tileId, dir))
  416. return true;
  417. return false;
  418. }
  419. /**
  420. * This utility function create/allocate the tiles of the board and create
  421. * the outer walls at the same time.
  422. *
  423. * @return The number of walls created from the utility.
  424. */
  425. private int createBasicTileWalls () {
  426. int wallCount =0;
  427. for (int i =0 ; i< tiles.length ; ++i) {
  428. boolean up = isUpSentinel(i);
  429. boolean down = isDownSentinel(i) && (i != 0);
  430. boolean left = isLeftSentinel(i);
  431. boolean right = isRightSentinel(i);
  432. wallCount += ((up?1:0) + (down?1:0) + (left?1:0) + (right?1:0));
  433. tiles[i] = new Tile (i, up, down, left, right);
  434. // If we have loopGuard enable we populate walls also.
  435. if (Session.loopGuard) {
  436. if (up) walls.add(new Edge(i, Direction.UP));
  437. if (down) walls.add(new Edge(i, Direction.DOWN));
  438. if (left) walls.add(new Edge(i, Direction.LEFT));
  439. if (right) walls.add(new Edge(i, Direction.RIGHT));
  440. }
  441. }
  442. return wallCount;
  443. }
  444. /**
  445. * Create randomly a wall in the wallable selected tile.
  446. * @param tileId The wallable tile to create the wall
  447. */
  448. private void createInnerWall(int tileId) {
  449. // Randomly pick a wallable direction in that tile.
  450. ShuffledRange randDirections = new ShuffledRange(DirRange.Begin, DirRange.End, DirRange.Step);
  451. int dir;
  452. do
  453. dir = randDirections.get();
  454. while (!isWallableDir(tileId, dir));
  455. // Add wall to tileId and the adjacent tileId
  456. Position neighbor = new Position(Position.toRow(tileId), Position.toCol(tileId), dir);
  457. tiles[tileId].setWall(dir);
  458. tiles[neighbor.getId()].setWall(Direction.opposite(dir));
  459. // If we have loopGuard enable we populate walls also.
  460. if (Session.loopGuard)
  461. walls.add(new Edge(tileId, dir));
  462. }
  463. /**
  464. * This utility creates the inner walls of the board.
  465. *
  466. * @return The number of walls failed to create.
  467. */
  468. private int createInnerWalls () {
  469. ShuffledRange randTiles = new ShuffledRange(0, N*N);
  470. for (int tileId, walls =0, shuffleMark =0 ; true ; ) {
  471. // randomly pick a wallable tile.
  472. do {
  473. if ((tileId = randTiles.get())== Const.EOR) {
  474. if (walls == shuffleMark) // Wallable tiles exhausted.
  475. return walls;
  476. else { // Re-shuffle and continue.
  477. randTiles = new ShuffledRange(0, N*N);
  478. shuffleMark =walls;
  479. }
  480. }
  481. } while (!isWallable(tileId));
  482. ++walls;
  483. createInnerWall(tileId);
  484. }
  485. }
  486. /**
  487. * Utility to get the body (center line) of the string representation of the tile.
  488. *
  489. * @param row What board's row to get.
  490. * @param col What board's column to get.
  491. * @param theseusTile The current tile of the Theseus.
  492. * @param minotaurTile The current tile of the Minotaur.
  493. * @return The body string
  494. */
  495. private String getTileBody (int row, int col, int theseusTile, int minotaurTile) {
  496. int tileId = Position.toID(row, col);
  497. boolean T = (tileId == theseusTile) ? true : false;
  498. boolean M = (tileId == minotaurTile) ? true : false;
  499. int S = tiles[tileId].hasSupply(supplies);
  500. if (T && !M) return " T ";
  501. else if (T && M) return "T+M";
  502. else if (M) {
  503. if (S == Const.noSupply) return " M ";
  504. else return "M+s";
  505. }
  506. else if (S != Const.noSupply)
  507. return String.format("s%02d", S+1);
  508. else return " ";
  509. }
  510. /**
  511. * Utility to render the 3 strings of the tile in the representation frame.
  512. *
  513. * @param frame Reference to the frame to print into.
  514. * @param row The board's row to print.
  515. * @param col The board's column to print.
  516. * @param theseusTile The current tile of the Theseus.
  517. * @param minotaurTile The current tile of the Minotaur.
  518. */
  519. private void renderTile(String[][] frame, int row, int col, int theseusTile, int minotaurTile) {
  520. IntFunction<Integer> toframe = (r)->{ return 2*r+1; };
  521. int tileId = Position.toID(row, col);
  522. frame[toframe.apply(row)+1][col] = tiles[tileId].hasWall(Direction.UP) ? "+---" : "+ ";
  523. frame[toframe.apply(row) ][col] = (tiles[tileId].hasWall(Direction.LEFT)? "|" : " ")
  524. + getTileBody(row, col, theseusTile, minotaurTile);
  525. frame[toframe.apply(row)-1][col] = tiles[tileId].hasWall(Direction.DOWN) ? "+---" : "+ ";
  526. }
  527. /**
  528. * Utility to render the 3 strings of the tile in the representation frame in
  529. * the case the tile lies in the east wall. We call these tiles `sentinel tiles`
  530. *
  531. * @param frame Reference to the frame to print into.
  532. * @param row The board's row to print.
  533. * @param col The board's column to print.
  534. * @param theseusTile The current tile of the Theseus.
  535. * @param minotaurTile The current tile of the Minotaur.
  536. */
  537. private void renderSentinelTile(String[][] frame, int row, int col, int theseusTile, int minotaurTile ) {
  538. IntFunction<Integer> toframe = (r)->{ return 2*r+1; };
  539. int tileId = Position.toID(row, col);
  540. frame[toframe.apply(row)+1][col] = tiles[tileId].hasWall(Direction.UP) ? "+---+" : "+ +";
  541. frame[toframe.apply(row) ][col] = (tiles[tileId].hasWall(Direction.LEFT)? "|" : " ")
  542. + getTileBody(row, col, theseusTile, minotaurTile)
  543. + (tiles[tileId].hasWall(Direction.RIGHT)? "|" : " ");
  544. frame[toframe.apply(row)-1][col] = tiles[tileId].hasWall(Direction.DOWN) ? "+---+" : "+ +";
  545. }
  546. /** @} */
  547. /** @name Neighbor access lambdas */
  548. /** @{ */
  549. private IntFunction<Integer> leftTileId = (id) -> { return Position.toID(Position.toRow(id), Position.toCol(id)-1); };
  550. private IntFunction<Integer> rightTileId = (id) -> { return Position.toID(Position.toRow(id), Position.toCol(id)+1); };
  551. private IntFunction<Integer> upTileId = (id) -> { return Position.toID(Position.toRow(id)+1, Position.toCol(id) ); };
  552. private IntFunction<Integer> downTileId = (id) -> { return Position.toID(Position.toRow(id)-1, Position.toCol(id) ); };
  553. /** @} */
  554. /** @name Class data */
  555. /** @{ */
  556. private int N; /**< The size of each edge of the board */
  557. private int S; /**< The number of the supplies on the board */
  558. private int W; /**< The number of walls on the board */
  559. private Tile[] tiles; /**< Array to hold all the tiles for the board */
  560. private Supply[] supplies; /**< Array to hold all the supplies on the board */
  561. private ArrayList<Edge> walls; /**<
  562. * Array to hold all the walls using the edge representation
  563. * required by the closed room preventing algorithm.
  564. */
  565. private ArrayList<Integer[]> moves;
  566. /** @} */
  567. }