brainfrz

DeckOfCard

Jan 23rd, 2016
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.72 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6.  
  7. import java.util.Random;
  8.  
  9. /**
  10.  *
  11.  * @author Terry
  12.  */
  13. public class DeckOfCard {
  14.     public static final int DECK_SIZE = 52;         //Number of cards in a deck
  15.     private final Random generator = new Random();  //Random number generator
  16.  
  17.     private Card[] deck;                    //Deck of cards
  18.     private int cardsLeft;                  //Number of cards left in deck (not dealt)
  19.  
  20.  
  21.     DeckOfCard() {
  22.         deck      = new Card[DECK_SIZE];
  23.         cardsLeft = DECK_SIZE;
  24.  
  25.         int currentCard = 0;
  26.         for (int suit = 1; suit <= Card.NUM_SUITS; suit++) {
  27.             for (int face = 1; face <= Card.NUM_FACES; face++) {
  28.                 deck[currentCard++] = new Card(face, suit);
  29.             }
  30.         }
  31.     }
  32.  
  33.  
  34.     //Fisher-Yates shuffle algorithm
  35.     public void shuffle() {
  36.         Card tempCard;
  37.         int j;
  38.  
  39.         for (int i = deck.length - 1; i >= 1; i--) {
  40.             j = generator.nextInt(i);
  41.             tempCard = deck[j];
  42.             deck[j] = deck[i];
  43.             deck[i] = tempCard;
  44.         }
  45.     }
  46.  
  47.     public Card deal() {
  48.         return deck[--cardsLeft];
  49.     }
  50.  
  51.     public int cardsLeft() {
  52.         return cardsLeft;
  53.     }
  54.  
  55.  
  56.     /**
  57.      * @param args Command line arguments aren't supported in this project.
  58.      */
  59.     public static void main(String[] args) {
  60.         DeckOfCard myDeck = new DeckOfCard();
  61.  
  62.         myDeck.shuffle();
  63.  
  64.         for (int i = 0; i < DeckOfCard.DECK_SIZE; i++) {
  65.             System.out.println(myDeck.deal().toString());
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment