Game.java (2559B)
1 package lucky_card; 2 3 import java.util.ArrayList; 4 import java.util.Scanner; 5 6 public class Game { 7 private Deck deck; 8 private boolean playing; 9 private Scanner inputHandler; 10 11 12 //constructor 13 public Game() { 14 deck = new Deck(); 15 playing = true; 16 inputHandler = new Scanner(System.in); 17 } 18 19 //start the game 20 public void play() { 21 //greet user 22 System.out.println("Welcome to Lucky Card game by William Lindholm\n"); 23 24 //main game loop 25 while (playing) { 26 27 //display starting round information 28 System.out.println("\n------- Playing a game round"); 29 30 //draw three cards from top of deck 31 ArrayList<Card> drawnCards = new ArrayList<Card>(); 32 for (int i = 0; i < 3; i++) { 33 drawnCards.add(deck.pop()); 34 } 35 36 //re-add the drawn cards 37 for (Card card : drawnCards) { 38 deck.addToBottom(card); 39 } 40 41 //display cards and determine if user won. 42 displayCards(drawnCards); 43 44 //check if user has won and display result 45 displayResult(isWin(drawnCards)); 46 47 //ask if user wants to play again 48 System.out.print("\n=========> Press ENTER to play again or \"q\" to quit: "); 49 50 //handle the user input, if user presses q exit game 51 handleInput(); 52 } 53 } 54 55 //Handles the user input 56 private void handleInput() { 57 //handle input 58 String userinput = inputHandler.nextLine(); 59 System.out.println(userinput); 60 if (userinput.equals("q")) { 61 System.out.println("\nThank you for playing and welcome back!"); 62 playing = false; 63 } 64 } 65 66 //display cards and determine if user won 67 private void displayCards(ArrayList<Card> cards) { 68 //display cards 69 for (int i = 0; i < cards.size(); i++) { 70 Card card = cards.get(i); //get current card 71 72 //print out cards suit, rank and value 73 System.out.println("Card " + i + ": " + card.getSuit() 74 + " -> " + card.getRank() + " Value = " + card.getValue()); 75 } 76 } 77 78 private void displayResult(boolean hasWon) { 79 //display win 80 if (hasWon) { 81 System.out.println("You win!"); 82 } else { 83 System.out.println("You lose!"); 84 } 85 } 86 87 private boolean isWin(ArrayList<Card> cards) { 88 //grab values from drawnCards 89 int[] cardValues = new int[cards.size()]; 90 for (int i = 0; i < cards.size(); i++) { 91 cardValues[i] = cards.get(i).getValue(); 92 } 93 94 //compare values from drawnCards 95 if ((cardValues[cardValues.length-1] > cardValues[0] 96 && cardValues[cardValues.length-1] < cardValues[1]) 97 || (cardValues[cardValues.length-1] < cardValues[0] 98 && cardValues[cardValues.length-1] > cardValues[1])){ 99 return true; 100 } 101 return false; 102 } 103 }