Advertisement
Anon017706349

aaadeck

Sep 26th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1.  
  2. /*
  3. An object of type Deck represents an ordinary deck of 52 playing cards.
  4. The deck can be shuffled, and cards can be dealt from the deck.
  5. */
  6.  
  7. public class Deck {
  8.  
  9. private Card[] deck; // An array of 52 Cards, representing the deck.
  10. private int cardsUsed; // How many cards have been dealt from the deck.
  11.  
  12. public Deck() {
  13. // Create an unshuffled deck of cards.
  14. deck = new Card[52];
  15. int cardCt = 0; // How many cards have been created so far.
  16. for ( int suit = 0; suit <= 3; suit++ ) {
  17. for ( int value = 1; value <= 13; value++ ) {
  18. deck[cardCt] = new Card(value,suit);
  19. cardCt++;
  20. }
  21. }
  22. cardsUsed = 0;
  23. }
  24.  
  25. public void shuffle() {
  26. // Put all the used cards back into the deck, and shuffle it into
  27. // a random order.
  28. for ( int i = 51; i > 0; i-- ) {
  29. int rand = (int)(Math.random()*(i+1));
  30. Card temp = deck[i];
  31. deck[i] = deck[rand];
  32. deck[rand] = temp;
  33. }
  34. cardsUsed = 0;
  35. }
  36.  
  37. public int cardsLeft() {
  38. // As cards are dealt from the deck, the number of cards left
  39. // decreases. This function returns the number of cards that
  40. // are still left in the deck.
  41. return 52 - cardsUsed;
  42. }
  43.  
  44. public Card dealCard() {
  45. // Deals one card from the deck and returns it.
  46. if (cardsUsed == 52)
  47. shuffle();
  48. cardsUsed++;
  49. return deck[cardsUsed - 1];
  50. }
  51.  
  52. } // end class Deck
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement