-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathrockPaperScissor.js
46 lines (40 loc) · 1.34 KB
/
rockPaperScissor.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
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function computerPlay() {
const choices = ['rock', 'paper', 'scissors'];
const randomIndex = Math.floor(Math.random() * choices.length);
return choices[randomIndex];
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return "It's a tie!";
} else if (
(playerSelection === 'rock' && computerSelection === 'scissors') ||
(playerSelection === 'paper' && computerSelection === 'rock') ||
(playerSelection === 'scissors' && computerSelection === 'paper')
) {
return 'You win!';
} else {
return 'Computer wins!';
}
}
function startGame() {
rl.question('Choose your move (rock, paper, or scissors): ', (playerSelection) => {
const computerSelection = computerPlay();
const result = playRound(playerSelection.toLowerCase(), computerSelection);
console.log(`You chose ${playerSelection}. Computer chose ${computerSelection}. ${result}`);
rl.question('Do you want to play again? (yes/no): ', (answer) => {
if (answer.toLowerCase() === 'yes') {
startGame();
} else {
console.log('Thanks for playing!');
rl.close();
}
});
});
}
console.log('Welcome to Rock, Paper, Scissors!');
startGame();