Game.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package game;
  2. import card.*;
  3. import game.Player;
  4. import java.util.Stack;
  5. import java.util.ArrayList;
  6. import java.util.Collections;
  7. public class Game {
  8. Stack<Card> cards;
  9. public Game () {
  10. this.cards = new Stack<Card>();
  11. // assign all unique cards
  12. for (Color color: Color.values()) {
  13. for (Value value: Value.values()) {
  14. cards.push(new Card(color, value));
  15. }
  16. }
  17. System.out.println("deck created");
  18. // shuffle deck
  19. Collections.shuffle(cards);
  20. System.out.println("deck shuffled");
  21. System.out.println(String.format("%d cards in deck", cards.size()));
  22. }
  23. // play a round, return winner
  24. public Player play_round(ArrayList<Player> players) {
  25. // assign each player a card
  26. for (Player player: players) {
  27. player.set_card(cards.peek());
  28. // if a player got a card from our deck, the card is gone from our deck
  29. cards.pop();
  30. }
  31. // if there is no player, there is no winner
  32. if (players.size() == 0) {
  33. return null;
  34. }
  35. // if there is only 1 player, we have a winner
  36. if (players.size() == 1) {
  37. return players.get(0);
  38. }
  39. Player current = players.get(1);
  40. for (Player player: players) {
  41. // if player holds a greater card than current
  42. if (player.get_card().compareTo(current.get_card()) > 0)
  43. // set new current
  44. current = player;
  45. }
  46. // return highest
  47. return current;
  48. }
  49. public void play(ArrayList<Player> players, int rounds) {
  50. Player winner;
  51. // play for <rounds> amount of rounds
  52. for (int i = 0; i < rounds; i++) {
  53. // print current round
  54. System.out.println(String.format("round number %d", i + 1));
  55. // if there are no cards left in deck
  56. if (this.cards.size() == 0) {
  57. System.out.println("no cards left in deck");
  58. }
  59. // play a round, assign winner and announce the lucky bastard's name
  60. winner = play_round(players);
  61. winner.win();
  62. System.out.println(String.format("and the winner is %s", winner.get_name()));
  63. System.out.println(String.format("using a %s", winner.get_card().to_string()));
  64. }
  65. // print final results
  66. System.out.println(" -- FINAL RESULTS --");
  67. for (Player player: players) {
  68. System.out.println(String.format("%s: %d wins", player.get_name(), player.won()));
  69. }
  70. }
  71. }