
/* 
   An object of class Deck represents a deck of playing cards.
   Individual card in the deck are reprecented as objects in
   the class Card.  A deck is a standard poker deck of 52 cards.
   The deck can be shuffled, and cards can be dealt from the
   deck one-by-one.  When a deck is first constructed, it
   is automatically shuffled.
*/


public class Deck {


   private Card[] cards;  // An array containing the 52 cards.
   private int nextCard;  // Number of next card to be dealt.


   public Deck() {  
         // Constuctor creates a shuffled deck of 52 cards.
      cards = new Card[52];
      for (int code = 0; code < 52; code++)
         cards[code] = new Card(code);
      shuffle();
   }


   public void shuffle() {
         // Shuffles the deck into a random order, and
         // prepare to start dealing from the deck starting
         // from card number zero.
      for (int top = 51; top >= 1; top--) {
         int pick = (int)(Math.random()*(top+1));
         Card temp = cards[pick];
         cards[pick] = cards[top];
         cards[top] = temp;
      }
      nextCard = 0;
   }


   public Card dealNextCard() {
         // Deals a card from the deck.  The "nextCard" variable
         // is the index of the next card to be dealt.  This
         // variable is updated after the card is dealt.  If 
         // nextCard has become equal to 52, then the whole
         // deck has been dealt out.  Rather than give an
         // error, the deck is shuffled and dealing starts over
         // again from the start of the array. 
      if (nextCard >= 52)  // All cards have been dealt;
         shuffle();        //   shuffle the deck and start over
      Card c = cards[nextCard];   // c is the card to be dealt.
      nextCard++;
      return c;
   }

   public int cardsLeft() {
         // Returns the number of undealt cards remaining in the deck.
         // This can be between 0 and 52.
      return 52 - nextCard;
   }

}
