// CMPU-101-51, Spring 2007
// Code used in class
// April 16, 2007

// Implementing a deck of cards (to be continued)

class Deck {
  
  // ------------------------
  //  class-oriented data
  // ------------------------
  
  // a convenient constant
  
  static final int DECK_SIZE = 52;
  
  // ------------------------
  //   object-oriented data
  // ------------------------

  // an array for the cards
  //   (for now, cards are represented as integers)
 
  private Card[] cards = new Card[Deck.DECK_SIZE];

  // the number of cards that have not yet been dealt

  private int numCards = this.cards.length;


  // ----------------------
  //  constructor
  // ----------------------
  
  Deck() {
    // set slots in "cards" array to the ints from 0 to 51.
    for (int i=0; i<this.numCards; i++) 
      this.cards[i] = new Card(i);
  }
  
  // ---------------------------
  //   object-oriented methods
  // ---------------------------

  // deal:  deal a card from the deck
  // --------------------------------
  //   note:  cards with indices between 0 and numCards-1
  //          are available for dealing; those with indices
  //          of numCards or greater are in the discard pile.
  //          Thus, numCards represents a bar between the
  //          the cards that are available and those that
  //          have been dealt already.

  Card deal() {

    // randomly select an index into the "front" part 
    // of the cards array, and store the selected card
    // in a local variable.

    int rnd = (int)(Math.random()*this.numCards);
    Card cardDealt = this.cards[rnd];

    this.numCards--;

    // SWAP selected card with card at position 
    // "numCards" -- since numCards has been decremented,
    // the selected card will no longer be available for
    // dealing ... it is effectively in the discard pile.

    this.cards[rnd] = this.cards[numCards];
    this.cards[numCards] = cardDealt;
   
    return cardDealt;
  }
  
  //  shuffle
  // ---------------------
  //   not much to do here since the randomization is all
  //   taken care of in the "deal" method.  just reset 
  //   the numCards field.
  
  void shuffle() {
    this.numCards = this.cards.length;
  }
  

  //  toString
  // -----------------------------
  //  generate a String representation of the deck of cards
  
  public String toString() {
    return "A deck with " + this.numCards + " undealt cards";
  }
  
}