forked from ChrisMayfield/ThinkJavaCode2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWar.java
More file actions
44 lines (37 loc) · 1.09 KB
/
War.java
File metadata and controls
44 lines (37 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Simulates a simple card game.
*/
public class War {
public static void main(String[] args) {
// create and shuffle the deck
Deck deck = new Deck();
deck.shuffle();
// divide the deck into piles
Pile p1 = new Pile();
p1.addDeck(deck.subdeck(0, 25));
Pile p2 = new Pile();
p2.addDeck(deck.subdeck(26, 51));
// while both piles are not empty
while (!p1.isEmpty() && !p2.isEmpty()) {
Card c1 = p1.popCard();
Card c2 = p2.popCard();
// compare the cards
int diff = c1.getRank() - c2.getRank();
if (diff > 0) {
p1.addCard(c1);
p1.addCard(c2);
} else if (diff < 0) {
p2.addCard(c1);
p2.addCard(c2);
} else {
// it's a tie...draw four more cards
}
}
// display the winner
if (p2.isEmpty()) {
System.out.println("Player 1 wins!");
} else {
System.out.println("Player 2 wins!");
}
}
}