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.

563 lines
21 KiB

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