Infinite Loop in JavaScript - While Loop - javascript

Does anyone know why this may be causing an infinite loop. I just can't see why!
I feel the issue may be with my while loop under play to five.
The while loop should be stopping at 5 and when the player or computer reaches this the game should stop.
This is Rock, Paper, Scissors. The result of each game is either player win, computer win or draw.
The game should end once either player reaches 5 wins.
The problem is the game is not ending as intended!
function getInput() {
console.log("Please choose either 'rock', 'paper', or 'scissors'.");
return prompt("Please choose either 'rock', 'paper', or 'scissors'");
}
function getPlayerMove() {
return getInput();
}
function randomPlay() {
var randomNumber = Math.random();
if (randomNumber < 0.33) {
return "rock";
}
else if (randomNumber < 0.66) {
return "paper";
}
else {
return "scissors";
}
}
function getComputerMove() {
return randomPlay();
}
function getWinner(playerMove,computerMove) {
var winner;
if (playerMove === 'rock' && computerMove === 'scissors') {
winner = 'Player';
}
else if (playerMove === 'scissors' && computerMove === 'paper') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'rock') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'scissors') {
winner='Computer';
}
else if (playerMove === 'rock' && computerMove === 'paper') {
winner='Computer';
}
else if (playerMove === 'scissors' && computerMove === 'rock') {
winner = 'Computer';
}
else {
winner = "tie";
}
return winner;
}
// A big limitation of this game is the user is only allowed to choose once! To allow more choices you'd need to design the program differently
function playToFive() {
var playerWins = 0;
var computerWins = 0;
var playerMove = getPlayerMove();
while ((playerWins <= 5) || (computerWins <= 5)) {
var computerMove = getComputerMove();
var winner = getWinner(getPlayerMove, getComputerMove);
console.log('The player has chosen ' + playerMove + '. The computer has chosen ' + computerMove);
if (winner === "player") {
playerWins += 1;
}
else if (winner === "computer") {
computerWins += 1;
}
if ((playerWins = 5) || (computerWins = 5)) {
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
else {
console.log("The " + winner + ' takes the round. It is now ' + playerWins + ' to ' + computerWins);
}
}
}
playToFive ();

Problem is this line
var winner = getWinner(getPlayerMove, getComputerMove);
you are passing the function reference to the getWinner() method
var winner = getWinner(playerMove , computerMove );
Which means that you need to get moves again later, so change your method to (multiple issues fixed in your code)
function playToFive()
{
var playerWins = 0;
var computerWins = 0;
while ((playerWins <= 5) && (computerWins <= 5)) //this line has && instead of ||
{
var computerMove = getComputerMove();
var playerMove = getPlayerMove(); //this line is now inside while loop
var winner = getWinner( playerMove , computerMove );
console.log('The player has chosen ' + playerMove + '. The computer has chosen ' + computerMove);
if (winner === "Player") { //P caps
playerWins += 1;
}
else if (winner === "Computer") { //C caps
computerWins += 1;
}
if ((playerWins == 5) || (computerWins == 5)) { //= is replaced by ==
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
else {
console.log("The " + winner + ' takes the round. It is now ' + playerWins + ' to ' + computerWins);
}
}
}

In order for this if to run accordingly:
if ((playerWins = 5) || (computerWins = 5)) {}
You'll need to use the == operator, because just one = is used for value assignation.
if ((playerWins == 5) || (computerWins == 5)) {}

Firstly in the while loop you need to change it too a && statement otherwise if the computer is 8 and the player is 3 the loop will continue until both players are >5.

I Think first you should understand the difference between (==) and (===) here.
Use This Code (Conditional Code not assignment)
if ((playerWins == 5) || (computerWins == 5)) { //use logical Operator not assignment Oprtr.
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
Instead of ##
if ((playerWins = 5) || (computerWins = 5)) { // Error Code.
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
Problem is this line
you are passing the function reference to the getWinner() method
use this
var winner = getWinner(playerMove , computerMove );
instead of
var winner = getWinner(getPlayerMove, getComputerMove);
For This Function...
function getWinner(playerMove,computerMove) {
var winner;
if (playerMove === 'rock' && computerMove === 'scissors') {
winner = 'Player';
}
else if (playerMove === 'scissors' && computerMove === 'paper') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'rock') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'scissors') {
winner='Computer';
}
else if (playerMove === 'rock' && computerMove === 'paper') {
winner='Computer';
}
else if (playerMove === 'scissors' && computerMove === 'rock') {
winner = 'Computer';
}
else {
winner = "tie";
}
return winner;
}
Every time this method set tie as winner.
But you should know the difference between (==) equalto and (===) equal value and equal type here

Thanks guys. There were quite a few issues.
Cheers guys. Definitely needed && rather than ||. The || was resulting in the game continuing even
Also var winner = getWinner(getPlayerMove, getComputerMove) was required. This was causing an infinite loop.

Related

My code is not running but i have no errors

The project is about making a rock paper scissors game using functions and loops etc.
the code below is how the project looks
the first function is to get the randomized computer choice
the second function is to get the user or players choice
the third function is to play the game and check if the player won or the computer won
the final function is to create a for loop to run the third function a certain number of times to see who is the winner of the game
Been working on it since and have no idea why it doesn't work
```
function getComputerChoice() {
let values = ["rock", "paper", "scissors"];
return values[Math.floor(Math.random() * values.length)];
}
function getPlayerChoice() {
let getChoice = "rock";
let value = getChoice.trim();
let lowCase = value.toLowerCase();
let capitalize = lowCase.charAt(0).toUpperCase + lowCase.slice(1);
while (!["Rock", "Paper", "Scissors"].includes(capitalize)) {
value = getChoice.trim();
lowCase = value.toLowerCase();
capitalize = lowCase.charAt(0).toUpperCase + lowCase.slice(1);
}
return capitalize;
}
function playRound(playerSelection, computerSelection) {
let games = "";
if (
(playerSelection == "rock" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "rock")
) {
return (games =
"player loses!! " + computerSelection + " beats " + playerSelection);
} else if (
(playerSelection == "paper" && computerSelection == "rock") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "rock" && computerSelection == "scissors")
) {
return (games =
"player Wins!! " + playerSelection + " beats " + computerSelection);
} else if (playerSelection == computerSelection) {
return (games =
"it a tie noice " + playerSelection + " v " + computerSelection);
} else {
return (games = "euphoria");
}
}
function game() {
let playerScores = 0;
let computerScores = 0;
let computerSelection = "";
let playerSelection = "";
computerSelection = getComputerChoice();
playerSelection = getPlayerChoice();
for (let i = 0; i < 5; i++) {
if (
playRound(
"player loses!! " + computerSelection + " beats " + playerSelection
)
) {
computerScores += 1;
console.log(
"you lost this round!! boo hoo!! scores are " +
computerScores +
" v " +
playerScores
);
} else if (
playRound(
"player Wins!! " + playerSelection + " beats " + computerSelection
)
) {
playerScores += 1;
console.log(
"you Won this round!! hurray!! scores are " +
computerScores +
" v " +
playerScores
);
}
}
if (playerScores > computerScores) {
console.log("congratulations you won this round");
} else if (playerScores < computerScores) {
console.log("im sorry you lost this round");
} else {
console.log("there is a problem");
}
}
game();
```
It doesn't seem that playRound() is returning anything:
function playRound(playerSelection, computerSelection) {
let games = '';
if (
(playerSelection == "rock" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "rock")
) {
games = "player loses!! " + computerSelection + " beats " + playerSelection;
// ADD RETURN HERE
} else if (
(playerSelection == "paper" && computerSelection == "rock") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "rock" && computerSelection == "scissors")
) {
games = "player Wins!! " + playerSelection + " beats " + computerSelection;
// ADD RETURN HERE
} else if (playerSelection == computerSelection) {
games = "it a tie noice " + playerSelection + " v " + computerSelection;
// ADD RETURN HERE
} else {
games = "euphoria";
// ADD RETURN HERE
}
}
Explanation
In your game() function definition you are checking if(playRound()). playRound is not returning anything so this is interpreted as a void function, hence, the if will always evaluate to false.

score stops at 5 some times, but other times it will just keep going. How to fix this

When running this function the first few times, it will work and display if I won the game or not when the score hits 5. But other times the score will keep incrementing (6, 7, 8, and so on). Why does the score not stop at 5 sometimes, and how do I stop this from happening?
const playerText = document.querySelector("#playerText");
const computerText = document.querySelector("#computerText");
const resultText = document.querySelector("#resultText");
const choiceBtns = document.querySelectorAll(".choiceBtn");
let player;
let computer;
let playerScore = 0;
let computerScore = 0;
choiceBtns.forEach(button => button.addEventListener("click", () => {
player = button.textContent;
computerSelection();
playerText.textContent = "Player: " + player;
computerText.textContent = "Computer: " + computer;
resultText.textContent = "Result: " + result();
}));
function computerSelection(){
const randNum = Math.floor(Math.random() * 3) + 1;
switch(randNum){
case 1:
computer = "rock";
break;
case 2:
computer = "paper";
break;
case 3:
computer = "scissors";
break;
}
}
function disable() {
document.getElementById("rock").disabled = true;
document.getElementById("paper").disabled = true;
document.getElementById("scissors").disabled = true;
}
function result() {
if ((player === "paper" && computer === "rock") ||
(player === "scissors" && computer === "paper") ||
(player === "rock" &&
computer === "scissors" &&
(computerScore <=5 && playerScore <=5 )))
{
playerScore += 1;
resultText.textContent = ("You win! " + "Player score: " + playerScore + " Computer score: " + computerScore);
return resultText.textContent;
}
if (playerScore == 5) {
resultText.textContent = ("Winner winner chicken dinner! You won the game! " + " Player score: " + playerScore + "Computer score: " + computerScore);
computerScore = 0;
playerScore = 0;
disable();
return resultText.textContent;
}
else if
((player === "rock" && computer === "paper") ||
(player === "paper" && computer === "scissors") ||
(player === "scissors" &&
computer === "rock" &&
(playerScore <=5 && computerScore <=5))
) {
computerScore += 1;
resultText.textContent = ("You lose! "+ "Player score: " + playerScore + " Computer score: " + computerScore);
return resultText.textContent;
}
if (computerScore == 5) {
resultText.textContent = ("You lost the game!!!!! " + " Player score: " + playerScore + " Computer score: " + computerScore);
computerScore = 0;
playerScore = 0;
disable();
return resultText.textContent;
}
else (computer == player)
{
resultText.textContent = ("Draw! " + "Player score: " + playerScore + " Computer score: " + computerScore);
return resultText.textContent;
}
}
When running this function the first few times, it will work and display if I won the game or not when the score hits 5. But other times the score will keep incrementing (6, 7, 8, and so on). Why does the score not stop at 5 sometimes, and how do I stop this from happening?
There are some issues with your result function:
function result() {
if (
((player === "paper" && computer === "rock") ||
(player === "scissors" && computer === "paper") ||
(player === "rock" && computer === "scissors")) &&
playerScore + 1 <= 5
) {
console.log({
test: computerScore <= 5 || playerScore <= 5,
computerScore,
playerScore,
});
playerScore += 1;
resultText.textContent =
"You win! " +
"Player score: " +
playerScore +
" Computer score: " +
computerScore;
if (playerScore == 5) {
resultText.textContent =
"Winner winner chicken dinner! You won the game! " +
" Player score: " +
playerScore +
"Computer score: " +
computerScore;
computerScore = 0;
playerScore = 0;
disable();
}
return resultText.textContent;
} else if (
((player === "rock" && computer === "paper") ||
(player === "paper" && computer === "scissors") ||
(player === "scissors" && computer === "rock")) &&
computerScore + 1 <= 5
) {
computerScore += 1;
resultText.textContent =
"You lose! " +
"Player score: " +
playerScore +
" Computer score: " +
computerScore;
if (computerScore == 5) {
resultText.textContent =
"You lost the game!!!!! " +
" Player score: " +
playerScore +
" Computer score: " +
computerScore;
computerScore = 0;
playerScore = 0;
disable();
}
return resultText.textContent;
} else {
resultText.textContent =
"Draw! " +
"Player score: " +
playerScore +
" Computer score: " +
computerScore;
return resultText.textContent;
}
Your conditions:
if ((player === "paper" && computer === "rock") ||
(player === "scissors" && computer === "paper") ||
(player === "rock" &&
computer === "scissors" &&
(computerScore <=5 && playerScore <=5 )))
There's no need to check the computerScore if only the score for the player will be affected by the player winning a round. Same applies to the inverse of this if statement.
Also, the score will exceed 5 because you are checking computerScore and playerScore before incrementing them. You can either add the increment value (in this case 1) in the if statement or you could add a nested if statement after the increment.
Your code is too messy, please refactor the code, after that find your bug later.
> Compute the result
> If player win set playerPoint++;
> else set computerPoint++;
// draw, go to new game.
> Check the winner
> if playerPoint >= 5 --> show message;
> else if computerPoint >=5 --> show message;
> end. go to new game.
Your code stop because you return too soon.

JS in HTML Game Won't Run [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm trying to build a Rock/Paper/Scissor game, first-to-five, in a script tag in HTML. As far as I can tell everything is A-ok, but when I run it I receive an error message in the console at my closing script tag.
Can you folks take a look and let me know:
1.) Why I'm getting an error message at the closing script tag, and what I need to do to resolve that and have that code run as I want it to?
2.) If you have any suggestions for my code in general? I'm self taught and trying to soak up as much as possible.
//Game parameters to start
var computerScore = 0
var playerScore = 0
//Game functions
function game() {
while (computerScore >= 5 && playerScore >= 5) {
//Computer Selection
function computerPlay() {
let playerSelection = prompt("Make your choice: rock, paper, or scissors!")
let computerSelection = Math.floor(Math.random() * 3)
//Player Selection
if (playerSelection.toLowerCase() == "rock") {
var playerChoice = 0;
} else if (playerSelection.toLowerCase() == "paper") {
var playerChoice = 1;
} else if (playerSelection.toLowerCase() == "scissors") {
var playerChoice = 2;
} else {
alert("Sorry, that word isn't recognized. Please select rock, paper, or scissors.")
}
//Rock
if (computerSelection == 0) {
var computerChoice = 0
//Paper
} else if (computerSelection == 1) {
var computerChoice = 1
//Scissors
} else if (computerSelection == 2) {
var computerChoice = 2
} else {}
//OUTCOMES
if (computerSelection == 0 && playerChoice == 0 || computerSelection == 1 && playerChoice == 1 || computerSelection == 2 && playerChoice == 2) {
alert("Tie game!")
} else if (computerSelection == 1 && playerChoice == 0) {
alert("Paper beats rock. You lose!")
} else if (computerSelection == 2 && playerChoice == 0) {
alert("Rock beats scissors. You win!")
} else if (computerSelection == 0 && playerChoice == 1) {
alert("Paper beats rock. You win!")
} else if (computerSelection == 0 && playerChoice == 2) {
alert("Rock beats scissors. You lose!")
} else if (computerSelection == 1 && playerChoice == 2) {
alert("Scissors beat paper. You win!")
} else if (computerSelection == 2 && playerChoice == 1) {
alert("Scissors beat paper. You lose!")
} else {}
//Increments
if (computerSelection > playerChoice) {
computerScore++
} else if (computerSelection < playerChoice) {
playerScore++
} else {}
if (computerScore == 5 && playerScore < 5) {
alert("Computer wins, " + computerScore + " to " + playerScore + "!")
} else if (playerScore == 5 && computerScore < 5) {
alert("Player wins, " + playerScore + " to " + computerScore + "!")
} else {}
}
game()
So there's a couple things here,
Firstly your game function has no closing bracket.
Secondly your computerPlay function inside your game function is never called (and it also has no closing bracket but I would suggest removing it anyway)
Thirdly your while condition (line 12) triggers when computer/playerScore is more than 5 but on lines 7 and 8 you set them to 0. You probably want them as less than or equal to instead.
See fixed version below.
<!DOCTYPE HTML >
<html>
<body>
<script>
//Game parameters to start
var computerScore = 0
var playerScore = 0
//Game functions
function game() {
while (computerScore <= 5 && playerScore <= 5) {
//Computer Selection
let playerSelection = prompt("Make your choice: rock, paper, or scissors!")
let computerSelection = Math.floor(Math.random() * 3)
//Player Selection
if (playerSelection.toLowerCase() == "rock") {
var playerChoice = 0;
} else if (playerSelection.toLowerCase() == "paper") {
var playerChoice = 1;
} else if (playerSelection.toLowerCase() == "scissors") {
var playerChoice = 2;
} else {
alert("Sorry, that word isn't recognized. Please select rock, paper, or scissors.")
}
//Rock
if (computerSelection == 0) {
var computerChoice = 0
//Paper
} else if (computerSelection == 1) {
var computerChoice = 1
//Scissors
} else if (computerSelection == 2) {
var computerChoice = 2
} else {}
//OUTCOMES
if (computerSelection == 0 && playerChoice == 0 || computerSelection == 1 && playerChoice == 1 || computerSelection == 2 && playerChoice == 2) {
alert("Tie game!")
} else if (computerSelection == 1 && playerChoice == 0) {
alert("Paper beats rock. You lose!")
} else if (computerSelection == 2 && playerChoice == 0) {
alert("Rock beats scissors. You win!")
} else if (computerSelection == 0 && playerChoice == 1) {
alert("Paper beats rock. You win!")
} else if (computerSelection == 0 && playerChoice == 2) {
alert("Rock beats scissors. You lose!")
} else if (computerSelection == 1 && playerChoice == 2) {
alert("Scissors beat paper. You win!")
} else if (computerSelection == 2 && playerChoice == 1) {
alert("Scissors beat paper. You lose!")
} else {}
//Increments
if (computerSelection > playerChoice) {
computerScore++
} else if (computerSelection < playerChoice) {
playerScore++
} else {}
if (computerScore == 5 && playerScore < 5) {
alert("Computer wins, " + computerScore + " to " + playerScore + "!")
} else if (playerScore == 5 && computerScore < 5) {
alert("Player wins, " + playerScore + " to " + computerScore + "!")
} else {}
}
}
game();
</script>
</body>
</html>

Rock paper scissors Javascript

I'm trying to build an RPS game with Javascript, using a click event as input.
I can get the program to see Watson's input and clock the number of games I've lost, but I can't get the program to recognize my input.
What steps have I missed out? Please check out the following link for all the code including HTML.
https://codepen.io/szewah/pen/daMKbK
var rockPaperScissors = ['Rock', 'Paper', 'Scissors'];
//gueses
var computerGuess = rockPaperScissors[Math.floor(Math.random()*rockPaperScissors.length)];
var myGuess = function (input) {
if (input === 'Rock' || input === 'Paper' || input === "Scissors") {
return input;
} else {
console.log('That\'s not a valid choice. Try again.');
};
};
// results
var wins =0;
var losses = 0;
var ties = 0;
//returns information to the DOM
var userChoiceText = document.getElementById('userchoice-text');
var computerChoiceText = document.getElementById('userchoice-text');
var winsText = document.getElementById('wins-text');
var lossesText = document.getElementById('losses-text');
var tiesText = document.getElementById('ties-text');
//adds event listener
document.getElementById('rock-btn').addEventListener('click', runGame);
document.getElementById('paper-btn').addEventListener('click', runGame);
document.getElementById('scissors-btn').addEventListener('click', runGame);
//function to run after event listener is triggered
function runGame () {
if ((myGuess === 'Rock' && computerGuess === 'Scissors') ||
(myGuess === 'Scissors' && computerGuess === 'Paper') ||
(myGuess === 'Paper' && computerGuess === 'Rock')) {
wins++;
console.log('I win!')
} else if (myGuess === computerGuess) {
ties++;
console.log('It\'s a tie!')
} else {
losses++;
console.log('Watson won!')
}
userChoiceText.textContent = 'You chose ' + myGuess + '.';
computerChoiceText.textContent = 'Watson chose ' + computerGuess + '.';
winsText.textContent = 'Wins: ' + wins + '.';
tiesText.textContent = 'Ties: ' + ties + '.';
lossesText.textContent = 'Losses: ' + losses + '.';
};
// array for choices of rock, paper, scissors
var rockPaperScissors = ['Rock', 'Paper', 'Scissors'];
function myGuessFn(input) {
if (input === 'Rock' || input === 'Paper' || input === 'Scissors') {
return input;
} else {
console.log('That\'s not a valid choice. Try again.');
};
};
// results
var wins = 0;
var losses = 0;
var ties = 0;
//returns information to the DOM
var userChoiceText = document.getElementById('userchoice-text');
var computerChoiceText = document.getElementById('computerchoice-text');
var winsText = document.getElementById('wins-text');
var lossesText = document.getElementById('losses-text');
var tiesText = document.getElementById('ties-text');
//adds event listener
document.getElementById('rock-btn').addEventListener('click', runGame);
document.getElementById('paper-btn').addEventListener('click', runGame);
document.getElementById('scissors-btn').addEventListener('click', runGame);
//function to run after event listener is triggered
function runGame(event) {
var myGuess = myGuessFn(event.target.innerHTML);
var computerGuess = rockPaperScissors[Math.floor(Math.random() * rockPaperScissors.length)];
if ((myGuess === 'Rock' && computerGuess === 'Scissors') ||
(myGuess === 'Scissors' && computerGuess === 'Paper') ||
(myGuess === 'Paper' && computerGuess === 'Rock')) {
wins++;
console.log('I win!')
} else if (myGuess === computerGuess) {
ties++;
console.log('It\'s a tie!')
} else {
losses++;
console.log('Watson won!')
}
userChoiceText.textContent = 'You chose ' + myGuess + '.';
computerChoiceText.textContent = 'Watson chose ' + computerGuess + '.';
winsText.textContent = 'Wins: ' + wins + '.';
tiesText.textContent = 'Ties: ' + ties + '.';
lossesText.textContent = 'Losses: ' + losses + '.';
};
#rock-btn,
#paper-btn,
#scissors-btn {
cursor: pointer;
}
<div class="container">
<h1>Press Rock Paper Scissors to play</h1>
<div class="choices">
<div id="rock-btn">Rock</div>
<div id="paper-btn">Paper</div>
<div id="scissors-btn">Scissors</div>
</div>
<hr>
<div class="resultChoice">
<p id="userchoice-text"></p>
<br>
<p id="computerchoice-text"></p>
</div>
<hr>
<div class="results">
<p id="wins-text"></p>
<p id="losses-text"></p>
<p id="ties-text"></p>
</div>
</div>

Need help resolving the loop issue

I recently started learning Javascript, enjoying it a lot. So, after learning some info about loops, i decided to improve a simple Rock, Scissors, Paper game. The improvement is to keep player wins and computer wins values as variables, and than loop the function until playerScore variable reaches value of 10. Im not so good at syntax yet, though trying to get the general logic and where i've made a mistake.
To reach my goal, i've declared two variables - playerScore and computerScore, their initial value is 0. After each player win or computer win i decided to add + 1 to variable.
Than start the game, i've declared a function playGame() and looped it using While. The loop seems infinite and more than that, current results are not logging to console. Any help is much appreciated, will help me to understand the logic much more than any courses i've passed.
Here's the code:
var playerScore = 0;
var computerScore = 0;
function getUserChoice() {
var userInput = prompt('Choose stone, scissors or paper');
userInput = userInput.toLowerCase();
if(userInput === 'stone' || userInput === 'paper' || userInput === 'scissors' || userInput === 'bomb') {
return userInput;
}
else {
alert('Error! Choose stone, scissors or paper!');
}
}
function getComputerChoice() {
var randomNumber = Math.floor(Math.random() *3);
if(randomNumber === 1) {
return 'stone';
}
else if(randomNumber === 2) {
return 'paper';
}
else {
return 'scissors';
}
}
function determineWinner (userChoice, computerChoice) {
if(userChoice === computerChoice) {
return 'That's a tie!';
}
if(userChoice === 'stone') {
if(computerChoice === 'scissors') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player won!';
}
else {
if(computerChoice === 'paper') {
computerScore = computerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Computer won!'
}
}
}
if(userChoice === 'paper') {
if(computerChoice === 'scissors') {
computerScore = computerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Computer won!';
}
else {
if(computerChoice === 'stone') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player wonи!';
}
}
}
if(userChoice === 'scissors') {
if(computerChoice === 'stone') {
computerScore = computerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Computer won!';
}
else {
if(computerChoice === 'paper') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player won!';
}
}
}
if(userChoice === 'bomb') {
if(computerChoice === 'stone' || computerChoice === 'scissors' || computerChoice === 'paper') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player won!';
return 'Player won!';
}
}
}
while(playerScore < 10) {
function playGame() {
var userChoice = getUserChoice();
var computerChoice = getComputerChoice();
alert('Player chose' + ' ' + userChoice + '!');
alert('Computer chose' + ' ' + computerChoice + '!');
alert(determineWinner(userChoice, computerChoice));
playGame() = false;
}
};
playGame();
You need to move your while-loop into the function playGame().
function playGame() {
while(playerScore < 10) {
var userChoice = getUserChoice();
var computerChoice = getComputerChoice();
alert('Player chose' + ' ' + userChoice + '!');
alert('Computer chose' + ' ' + computerChoice + '!');
alert(determineWinner(userChoice, computerChoice));
}
}

Categories

Resources