-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTheGameofPig.java
More file actions
80 lines (61 loc) · 2.1 KB
/
TheGameofPig.java
File metadata and controls
80 lines (61 loc) · 2.1 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
package CS5004.HW2;
import java.util.Random;
import java.util.Scanner;
public class TheGameofPig {
int humanPoints = 0;
int pcPoints = 0;
boolean flag = true; // true - human, flase - pc
Random random = new Random();
Scanner scan = new Scanner(System.in);
public void game() {
while (true) {
System.out.println("-Human's turn");
humanRound();
if (humanPoints >= 100) {
System.out.println("Human wins!");
break;
}
System.out.println("\n-Computer's turn");
pcRound();
if (pcPoints >= 100) {
System.out.println("Computer wins!");
break;
}
}
}
private void humanRound() {
int r = 2;
int roundPoint = 0;
while (humanPoints < 100 && r != 1) {
r = random.nextInt(6) + 1;
System.out.println("Human rolls " + r);
System.out.printf("Human points: %d, Conputer points: %d\n", humanPoints, pcPoints);
if (r == 1) break; // when rolls 1, ends without points
roundPoint += r; // continue with points
System.out.println("Please input “r” to roll again or “h” to hold");
// if hold, add all points and ends
if (scan.next().charAt(0) == 'h') {
humanPoints += roundPoint;
break;
}
// else roll again
} // end while
}
private void pcRound() {
int r = 2;
int roundPoint = 0;
while (pcPoints < 100 && r != 1) {
r = random.nextInt(6) + 1;
if (r == 1) break; // when rolls 1, ends without points
roundPoint += r; // else continue with points
if (roundPoint >= 20) {
pcPoints += roundPoint;
break;
}
} // end while
}
public static void main(String[] args) {
TheGameofPig p = new TheGameofPig();
TheGameofPig.game();
}
}