File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 22import java .util .Random ;
33
44/**
5- * A deck of playing cards (of fixed size ).
5+ * A deck of playing cards (of fixed length ).
66 */
77public class Deck {
88
@@ -104,16 +104,17 @@ private static Deck merge(Deck d1, Deck d2) {
104104 }
105105
106106 /**
107- * Returns a sorted copy of the deck using merge sort.
107+ * Returns a sorted copy of the deck using selection sort.
108108 */
109- public Deck mergeSort () {
109+ public Deck almostMergeSort () {
110110 return this ;
111111 }
112112
113113 /**
114- * Reorders the cards (in place) using insertion sort.
114+ * Returns a sorted copy of the deck using merge sort.
115115 */
116- public void insertionSort () {
116+ public Deck mergeSort () {
117+ return this ;
117118 }
118119
119120}
Original file line number Diff line number Diff line change 1+ import java .util .ArrayList ;
2+
3+ /**
4+ * A pile of playing cards (of variable size).
5+ */
6+ public class Pile {
7+
8+ private ArrayList <Card > cards ;
9+
10+ /**
11+ * Constructs an empty pile of cards.
12+ */
13+ public Pile () {
14+ this .cards = new ArrayList <Card >();
15+ }
16+
17+ /**
18+ * Adds a card to the bottom of the pile.
19+ */
20+ public void addCard (Card card ) {
21+ this .cards .add (card );
22+ }
23+
24+ /**
25+ * Copies an entire deck into the pile.
26+ */
27+ public void addDeck (Deck deck ) {
28+ for (Card card : deck .getCards ()) {
29+ this .cards .add (card );
30+ }
31+ }
32+
33+ /**
34+ * Removes a card from the top of the pile.
35+ */
36+ public Card popCard () {
37+ return this .cards .remove (0 );
38+ }
39+
40+ /**
41+ * Returns the number of cards in the pile.
42+ */
43+ public int size () {
44+ return this .cards .size ();
45+ }
46+
47+ }
Original file line number Diff line number Diff line change 1+ /**
2+ * Simulates a simple card game.
3+ */
4+ public class War {
5+
6+ public static void main (String [] args ) {
7+
8+ // create and shuffle the deck
9+ Deck deck = new Deck ();
10+ deck .shuffle ();
11+
12+ // divide the deck into piles
13+ Pile p1 = new Pile ();
14+ p1 .addDeck (deck .subdeck (0 , 25 ));
15+ Pile p2 = new Pile ();
16+ p2 .addDeck (deck .subdeck (26 , 51 ));
17+
18+ // while both piles are not empty
19+ while (p1 .size () > 0 && p2 .size () > 0 ) {
20+ Card c1 = p1 .popCard ();
21+ Card c2 = p2 .popCard ();
22+
23+ // compare the cards
24+ int diff = c1 .getRank () - c2 .getRank ();
25+ if (diff > 0 ) {
26+ p1 .addCard (c1 );
27+ p1 .addCard (c2 );
28+ } else if (diff < 0 ) {
29+ p2 .addCard (c1 );
30+ p2 .addCard (c2 );
31+ } else {
32+ // it's a tie...draw four more cards
33+ }
34+ }
35+
36+ // display the winner
37+ if (p1 .size () > 0 ) {
38+ System .out .println ("Player 1 wins!" );
39+ } else {
40+ System .out .println ("Player 2 wins!" );
41+ }
42+ }
43+
44+ }
You can’t perform that action at this time.
0 commit comments