// Name: Ron Cytron // Date: 19 Feb 99 // CS101 Lab 6 // Deck.java // // You need not modify this file. This file's selfTest() tests // the CardList class as well. import cs101.terminal.*; public class Deck { private CardList deck; /* Generate a deck of 52 cards */ public Deck() { newDeck(); } private void newDeck() { deck = null; for (int i=0; i <=51; ++i) { deck = new CardList(new Card(i),deck); } } /* * Shuffle the deck by taking the ith card and exchanging it * with a random card in the middle */ public void shuffle() { int num = deck.cardinality(); for (int i=num-1; i>=1; --i) { CardList c1 = deck.findCard(i); int swap = (int) (i * Math.random()); CardList c2 = deck.findCard(swap); c1.exchange(c2); } } public Card draw() { if (deck == null) { Terminal.println("\n[ Reshuffle ]\n"); newDeck(); for (int i=1; i <=100; ++i) shuffle(); } Card ans = deck.getFirst(); deck = deck.getRest(); return(ans); } public String toString() { if (deck == null) return "Empty Deck"; else return "Deck of " + deck.cardinality() + " cards " + deck.toString(); } public static void main(String[] args) { selfTest(); } public static void selfTest() { Deck d = new Deck(); Terminal.println("Deck is "); Terminal.println(d); CardList rev = d.deck.reverse(); Terminal.println("\nAfter reversal by CardList.reverse()\n"); Terminal.println(rev); for (int i=0; i <= 25; ++i) { CardList c1 = d.deck.findCard(i); CardList c2 = d.deck.findCard(51-i); c1.exchange(c2); } Terminal.println("\nAfter reversal by exchange\n"); Terminal.println(d); for (int i=1; i <=100; ++i) d.shuffle(); Terminal.println("\nAfter 100 shuffles\n"); Terminal.println(d); for (int i=1; i<=53; ++i) { Card c = d.draw(); Terminal.println("\nDrew " + c + " deck now " + d); } } }