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.

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