A java snake game for A.U.TH. Data structures class
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

250 lignes
8.2 KiB

  1. package net.hoo2.auth.dsproject.snake;
  2. /**
  3. * @mainpage
  4. * @title Snake game project. -- Part 1 --
  5. *
  6. * This is the code documentation page of the Snake game project.
  7. * Listed are:
  8. * * All used classes
  9. * * All member functions
  10. * * All data members
  11. *
  12. * @author Christos Choutouridis AEM:8997
  13. * @email cchoutou@ece.auth.gr
  14. */
  15. import java.lang.Math;
  16. import java.util.ArrayList;
  17. /**
  18. * @class Game
  19. *
  20. * @brief This is the main control class of the game.
  21. *
  22. * This class includes the main function.Using this class's api
  23. * the user can create a board, register players and roll the game.
  24. *
  25. * @author Christos Choutouridis AEM:8997
  26. * @email cchoutou@ece.auth.gr
  27. */
  28. public class Game {
  29. /** @name Constants */
  30. /**@{ */
  31. static final int MAX_PLAYERS = 4; /**< The maximum number of allowed players in the game */
  32. static final int MAX_GAME_ROUNDS = 10000; /**< the maximum allowed round of the game */
  33. /**@} */
  34. /** @name Private data members */
  35. /** @{ */
  36. private int round; /**< The current round of the game */
  37. private Board board; /**< A reference to board */
  38. private ArrayList<Player> players; /**< A reference to players */
  39. /** @} */
  40. /** @name private api */
  41. /** @{ */
  42. /**
  43. * Dice functionality
  44. * @return An integer in the range [1 .. 6]
  45. */
  46. private int _dice () {
  47. return (int)(1 + Math.random()*5);
  48. }
  49. /**
  50. * Search the players already in the players vector and compare their turn to play
  51. * with the result of a dice. If there is another one with the same dice result return true.
  52. *
  53. * @param turn The dice result to check in order to find player's turn to play
  54. * @param players Reference to already register players
  55. * @return True if there is another player with the same dice result
  56. */
  57. private boolean _search (int die, ArrayList<Player> players) {
  58. for (int i =0; i<players.size() ; ++i)
  59. if (players.get(i).getTurn() == die)
  60. return true;
  61. return false;
  62. }
  63. /** @} */
  64. /** @name Constructors */
  65. /** @{ */
  66. /** Default doing nothing constructor */
  67. Game () {
  68. round = 0;
  69. board = new Board();
  70. players = new ArrayList<>();
  71. }
  72. /**
  73. * @brief The main constructor
  74. * This constructor create a board and prepares the board for the game.
  75. * After this call the user can call @ref registerPlayer()
  76. * @param N The row for the board
  77. * @param M The columns of the board
  78. * @param numOfSnakes Number of snakes to place
  79. * @param numOfLadders Number of ladders to place
  80. * @param numOfApples Number of Apples to place
  81. */
  82. Game (int N, int M, int numOfSnakes, int numOfLadders, int numOfApples) {
  83. round = 0;
  84. // delegate constructors
  85. board = new Board (N, M, numOfSnakes, numOfLadders, numOfApples);
  86. players = new ArrayList<>();
  87. }
  88. /** @} */
  89. /** @name Get/Set interface */
  90. /** @{ */
  91. int getRound () { return round; }
  92. void setRound (int round) { this.round = round; }
  93. /** Get reference to board */
  94. Board getBoard () { return board; }
  95. /** Set board
  96. * @param board Reference to board to use
  97. * @note This requires board must be allocated elsewhere.
  98. */
  99. void setBoard (Board board) {
  100. this.board = board;
  101. }
  102. /** Get reference to players */
  103. ArrayList<Player> getPlayers() { return players; }
  104. /**
  105. * Set players
  106. * @param players Reference to players to use
  107. * @note This requires players must be allocated elsewhere.
  108. */
  109. void setPlayers(ArrayList<Player> players) {
  110. this.players = players;
  111. }
  112. /** @} */
  113. /** @name Public functionality */
  114. /** @{ */
  115. /**
  116. * Register a player to the game
  117. * @param playerId The player ID to use
  118. * @param name The player name to use
  119. * @return The status of the operation
  120. */
  121. boolean registerPlayer (int playerId, String name) {
  122. if (players.size() >= MAX_PLAYERS)
  123. return false;
  124. players.add(new Player(playerId, name, board));
  125. return true;
  126. }
  127. /**
  128. * @brief Set the playing order of players
  129. * This function emulates the classic roll of dice to decide which player
  130. * plays first which second and so on.
  131. */
  132. void playOrder () {
  133. int d;
  134. for (int i =0 ; i<players.size() ; ++i) {
  135. do
  136. // Keep rolling the dice as the die belongs to another user
  137. d = _dice();
  138. while (_search (d, players));
  139. players.get(i).setTurn(d);
  140. }
  141. // Sort players vector
  142. players.sort((p1, p2) ->
  143. Integer.compare (p1.getTurn(), p2.getTurn())
  144. );
  145. }
  146. /**
  147. * Sort the players according to their score
  148. */
  149. void scoreSort () {
  150. players.sort((p1, p2) ->
  151. Integer.compare (p1.getScore(), p2.getScore())
  152. );
  153. }
  154. /**
  155. * A game round. In each round every player plays when is his turn
  156. *
  157. * @return The winner if we have one, or null
  158. */
  159. Player round () {
  160. int [] mret;
  161. ++round; // keep track of round
  162. // traverse the players vector and move each player on the board
  163. // using a dice throw
  164. for (int i =0 ; i<players.size() ; ++i) {
  165. mret = players.get(i).move (players.get(i).getTile(), _dice());
  166. if (mret[0]>= board.getN()*board.getM())
  167. // The first one here is the winner
  168. return players.get(i);
  169. }
  170. return null; // No one finished yet
  171. }
  172. /** @} */
  173. /**
  174. * @brief Main
  175. * As the requirements of the project suggested.
  176. * We:
  177. * * Create a game
  178. * * Manually create a board
  179. * * Register 2 players (John Doe for now)
  180. * * Place a predefined number of snakes, ladders and apples
  181. * * Deploy the game by calling @ref playOrder() and @ref round()
  182. * At the end we print the results and exit
  183. */
  184. public static void main(String[] args) {
  185. // Current project requirements
  186. int lines = 20;
  187. int columns = 10;
  188. int numOfSnakes = 3;
  189. int numOfLadders = 3;
  190. int numOfApples = 6;
  191. int numOfPlayers = 2;
  192. // Print caption
  193. System.out.println("================== Snake Game ==================");
  194. System.out.println("Board: " +lines +"x" +columns +" with " +numOfSnakes +" snakes, "
  195. +numOfLadders +" ladders and " +numOfApples +" apples.");
  196. System.out.println("Players: " + numOfPlayers);
  197. System.out.println("");
  198. // Board creation
  199. Game game = new Game (lines, columns, numOfSnakes, numOfLadders, numOfApples);
  200. // game.getBoard().createElementBoard(); // Not explicitly required
  201. // Player registration
  202. for (int i=0 ; i<numOfPlayers && i<MAX_PLAYERS; ++i)
  203. game.registerPlayer(i+1, String.format("Player %d", i+1));
  204. game.playOrder(); // Choose play order
  205. Player winner;
  206. do // Keep going until someone finishes
  207. winner = game.round ();
  208. while (winner == null
  209. && game.getRound() < MAX_GAME_ROUNDS);
  210. if (game.getRound() == MAX_GAME_ROUNDS) {
  211. // Check if we finished
  212. System.out.println("Game did not finished in " + MAX_GAME_ROUNDS + " rounds. Abort.");
  213. return;
  214. }
  215. // Print the results
  216. System.out.println("***** Game finished *****");
  217. System.out.println("");
  218. System.out.println("Rounds: " + game.getRound());
  219. System.out.println("Winner: " + winner.getName() + " [" + winner.getScore() +" points]");
  220. System.out.println("Score: ");
  221. game.scoreSort (); // sort players based on their score
  222. for (int i=game.getPlayers().size()-1 ; i>=0 ; --i) {
  223. // Loop all players
  224. Player p = game.getPlayers().get(i);
  225. if (p == winner)
  226. System.out.println(" * " +p.getName() + ": " + p.getScore() +" points");
  227. else
  228. System.out.println(" " +p.getName() + ": " + p.getScore() +" points");
  229. }
  230. }
  231. }