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.

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