-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
81 lines (70 loc) · 2.06 KB
/
script.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
71
72
73
74
75
76
77
78
79
80
81
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function intValueOfPlay(play) {
switch (play) {
case "rock":
return 3;
break;
case "scissors":
return 2;
break;
case "paper":
return 1;
break;
default:
return null;
}
}
function computerPlay() {
let random = randomIntFromInterval(1,3);
if (random===1) {
return "rock";
} else if (random===2) {
return "paper";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
let playerInt = intValueOfPlay(playerSelection.toLowerCase());
let computerInt = intValueOfPlay(computerSelection);
if (playerInt === null) {
return "Invalid user input";
}
if (playerInt===1 && computerInt===3) {
return {winner: 1,message: "You Win! Paper beats Rock"};
} else if (playerInt===3 && computerInt==1) {
return {winner: 2, message: "You Lose! Paper beats Rock"};
} else {
if (playerInt > computerInt) {
return {winner: 1, message: `You Win! ${capitalizeFirstLetter(playerSelection)} beats ${capitalizeFirstLetter(computerSelection)}`};
} else if (playerInt < computerInt) {
return {winner: 2, message: `You Lose! ${capitalizeFirstLetter(computerSelection)} beats ${capitalizeFirstLetter(playerSelection)}`};
} else {
return {winner: 0, message: `It's a tie! ${capitalizeFirstLetter(computerSelection)} equals ${capitalizeFirstLetter(playerSelection)}`};
}
}
}
function game() {
let playerWins = 0;
let computerWins = 0;
for (let i=1;i<=5;i++) {
let userInput = prompt("Enter rock, paper or scissors");
let result = playRound(userInput,computerPlay());
result.winner === 1 ? playerWins += 1 : null;
result.winner === 2 ? computerWins += 1 : null;
console.log(result.message);
}
if (playerWins > computerWins) {
console.log("You win!");
} else if (playerWins < computerWins) {
console.log("You lose!");
} else {
console.log("It's a tie!");
}
}
game();