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
91 lines (71 loc) · 2.65 KB
/
War.java
File metadata and controls
91 lines (71 loc) · 2.65 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.util.ArrayList;
/**
* Simulates a simple card game.
*/
public class War {
public static void main(String[] args) {
// create and shuffle the deck
Deck deck = new Deck();
System.out.println(deck.toString());
deck.shuffle();
System.out.println(deck.toString());
// 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));
ArrayList<Card> warList = new ArrayList<>();
// while both piles are not empty
while (!p1.isEmpty() && !p2.isEmpty()) {
Card c1 = p1.popCard();
Card c2 = p2.popCard();
System.out.println("C1: "+ c1.toString());
System.out.println("C2: "+ c2.toString());
// compare the cards
int diff = c1.getRank() - c2.getRank();
if (diff > 0) { //player 1 won - gets all cards incl war list
p1.addCard(c1);
p1.addCard(c2);
if (warList.size() > 0) {
for (Card card : warList) {
p1.addCard(card);
}
warList.clear();//remove all from warlist
}
} else if (diff < 0) {
p2.addCard(c1);
p2.addCard(c2);
if (warList.size() > 0) {
for (Card card : warList) {
p2.addCard(card);
}
warList.clear();
}
} else {
// it's a tie...draw four more cards
System.out.println("WAR");
if(p1.size() < 4 || p2.size() <4) {
System.out.println("Game ended! No winner");
break;
}
warList.add(c1);
warList.add(c2);
for (int i = 0; i < 3; i++) {
warList.add(p1.popCard());
warList.add(p2.popCard());
}
}
System.out.println("size of p1: "+p1.size());
System.out.println("size of p2: "+p2.size());
System.out.println("size of warList: "+warList.size());
}
// display the winner
if (p2.isEmpty()) {
System.out.println("Player 1 wins!");
} else if (p1.isEmpty()) {
System.out.println("Player 2 wins!");
} else {
System.out.println("TIE!");
}
}
}