-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiceBoardGameRecursion.java
More file actions
61 lines (46 loc) · 2.05 KB
/
DiceBoardGameRecursion.java
File metadata and controls
61 lines (46 loc) · 2.05 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
import java.util.*;
class DiceBoardGameRecursion {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
System.out.print("Enter the number of players: ");
int numPlayers = scanner.nextInt();
System.out.print("Enter the target score: ");
int targetScore = scanner.nextInt();
int[] scores = new int[numPlayers];
boolean[] completed = new boolean[numPlayers];
playGame(0, numPlayers, scores, completed, targetScore, random, scanner);
System.out.println("Game Over!");
scanner.close();
}
public static void playGame(int currentPlayer, int numPlayers, int[] scores, boolean[] completed,
int targetScore, Random random, Scanner scanner) {
if (checkAllCompleted(completed)) {
return;
}
if (completed[currentPlayer]) {
playGame((currentPlayer + 1) % numPlayers, numPlayers, scores, completed, targetScore, random, scanner);
return;
}
System.out.print("Player " + (currentPlayer + 1) + " - Press Enter to roll the dice: ");
scanner.nextLine();
int diceValue = random.nextInt(6) + 1;
scores[currentPlayer] += diceValue;
System.out.println("Player " + (currentPlayer + 1) + " rolled a " + diceValue);
System.out.println("Current Score: " + scores[currentPlayer]);
if (scores[currentPlayer] >= targetScore) {
System.out.println("Player " + (currentPlayer + 1) + " has won!");
completed[currentPlayer] = true;
}
System.out.println();
playGame((currentPlayer + 1) % numPlayers, numPlayers, scores, completed, targetScore, random, scanner);
}
public static boolean checkAllCompleted(boolean[] completed) {
for (boolean isCompleted : completed) {
if (!isCompleted) {
return false;
}
}
return true;
}
}