import java.util.Random; /** * Deck.java * This is code for a class that represents a standard deck of * 52 playing cards. */ public class Deck { private Card [] deck; private int top; private static Random gen = new Random(); /** * Deck() * Input: none * Output: none * Description: Creates a deck of 52 playing cards - one * for each suit/rank combination */ public Deck() { int count = 0; deck = new Card[52]; for(int i = 2; i <= 14; i++) { for(int j = 1; j <= 4; j++) { deck[count] = new Card(i, j); count++; } } top = 0; }//end constructor /** * getTop() * Input: none * Output: an integer that represents the top of the deck * or its offset in the deck array * Description: gets the index which is currently acting as * the top of the deck. */ public int getTop() { return top; }//end getTop /** * deal() * Input: none * Output: a reference to the card that was previously the top of the deck * Description: returns the card that is the top of the deck and sets the top * pointer to the next card in the array. If the last card in the deck has * just been dealt, the deck is reshuffled. */ public Card deal() { Card topCard = deck[top]; top++; if(top == 52) this.shuffle(); return topCard; }//end deal /** * shuffle() * Input: none * Output: none * Description: shuffles the deck using a random permutation algorithm * that chooses a permutation uniformly at random. */ public void shuffle() { int swapIndex; Card temp; for(int i = 0; i < deck.length; i++) { swapIndex = gen.nextInt(deck.length-i) + i; temp = deck[swapIndex]; deck[swapIndex] = deck[i]; deck[i] = temp; }//end shuffle top = 0; } /** * toString() * Input: none * Output: a String representation of this deck * Descriptions: creates a string representation of the deck * which includes each card printed out in order, 8 per line */ public String toString() { String result = ""; for(int i = 0; i < 52; i++) { result += deck[i] + ", "; if((i+1)%8 == 0 || i == 51) result += "\n"; } return result; }//end toString }