-
Notifications
You must be signed in to change notification settings - Fork 45
/
28Problem.js
70 lines (61 loc) · 1.82 KB
/
28Problem.js
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
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
function playRound(player1Choice, player2Choice) {
if (player1Choice === player2Choice) {
return "It's a tie!";
}
if (
(player1Choice === "rock" && player2Choice === "scissors") ||
(player1Choice === "paper" && player2Choice === "rock") ||
(player1Choice === "scissors" && player2Choice === "paper")
) {
return "Player 1 wins!";
} else {
return "Player 2 wins!";
}
}
function playGame(rounds) {
let player1Score = 0;
let player2Score = 0;
let round = 1;
const playRoundRecursive = () => {
if (round <= rounds) {
rl.question(
`Round ${round}: Player 1, enter your choice (rock, paper, scissors): `,
(player1Choice) => {
rl.question(
`Round ${round}: Player 2, enter your choice (rock, paper, scissors): `,
(player2Choice) => {
const result = playRound(
player1Choice.toLowerCase(),
player2Choice.toLowerCase()
);
console.log(
`Round ${round}: Player 1 chose ${player1Choice}, Player 2 chose ${player2Choice}. ${result}`
);
if (result.includes("Player 1 wins")) {
player1Score++;
} else if (result.includes("Player 2 wins")) {
player2Score++;
}
round++;
playRoundRecursive();
}
);
}
);
} else {
console.log(
`Game over! Player 1 score: ${player1Score}, Player 2 score: ${player2Score}`
);
rl.close();
}
};
playRoundRecursive();
}
rl.question("Enter the number of rounds to play: ", (totalRounds) => {
playGame(parseInt(totalRounds));
});