Loop functionality and tallying in javascript rock paper scissors game() function - javascript

Just as a foreword, I'm very new to programming so apologies if the error is something simple that I've simply overlooked. Also in advance I know the game function is a mess right now, I copied it in the state that it's in now after I've fiddled with it for a couple days.
I've been working on the odin project rock paper scissors project and although I've developed a single round function that works well, I haven't been able to make the overarching game function work properly. I've tried shifting syntax around and I suspect that the problem lies somewhere with the scope of specific variables but I haven't been able to figure out a way that works as of yet. I've also been doing research for the last few days trying to figure out how to do it while I was streamlining the single round but I wasn't able to find a query that worked with how my code is set up.
I've put everything within the same function but I can't seem to get the loop to work properly when I do, and I've tried pulling variables out from local to global scale but haven't been successful- as I mentioned though the function for a single round works without error and returns a correct string no matter the outcome so I have a hunch the error does lie somewhere in the variable scale and I just haven't been able to pinpoint it.
My game function, which is about the fifth or sixth rendition that doesn't work:
function game() {
let playerScore = 0;
let computerScore = 0;
let roundResult = computerPlay();
for (let counter = 0; counter <= 5; ++counter) {
computerPlay();
if (roundResult === 'You win, rock beats scissors' || roundResult === 'You win, paper beats rock.' || roundResult === 'You win, scissors beats paper.') {
++playerScore;
} else if (roundResult === 'You lose, paper beats rock.' || roundResult === 'You lose, scissors beats paper.' || roundResult === 'You lose, rock beats scissors.') {
++computerScore
}
if (playerScore > computerScore) {
return ('You win ' + playerScore + ' to ' + computerScore + '.');
} else if (playerScore < computerScore) {
return ('You lose ' + computerScore + ' to ' + playerScore + '.');
} else {
return 'It was a tie, you both won the same number of rounds.';
}
}
}
// and the single round (computerPlay) function that works fine:
function computerPlay() {
let playerInput = prompt('Enter your selection of rock, paper, or scissors.');
let playerTrimmed = playerInput.trim();
let playerSelection = playerTrimmed.charAt(0).toUpperCase();
let playerScore = 0;
let computerScore = 0;
if (playerSelection === 'R' || playerSelection === 'P' || playerSelection === 'S') {
let myArray = ['R', 'P', 'S'];
let computerSelection = myArray[Math.floor(Math.random() * myArray.length)];
if (playerSelection === 'R') {
if (computerSelection === 'S') {
++playerScore;
return 'You win, rock beats scissors.';
} else if (computerSelection === 'P') {
++computerScore;
return 'You lose, paper beats rock.';
} else {
return 'Tie.';
}
} else if (playerSelection === 'P') {
if (computerSelection === 'R') {
++playerScore;
return 'You win, paper beats rock.';
} else if (computerSelection === 'S') {
++computerScore;
return 'You lose, scissors beats paper.';
} else {
return 'Tie.';
}
} else if (playerSelection === 'S') {
if (computerSelection === 'P') {
++playerScore;
return 'You win, scissors beats paper.';
} else if (computerSelection === 'R') {
++computerScore;
return 'You lose, rock beats scissors.';
} else {
return 'Tie.';
}
}
} else {
//makes sure player entered a string starting with a valid letter (r, p, or s)
alert('Please make sure you enter a valid selection.');
}
}
game()

Like DBS said the return statement will stop your function and your loop with it, so try it like this:
function game() {
let playerScore = 0;
let computerScore = 0;
let roundResult = computerPlay();
for (let counter = 0; counter <= 5; ++counter) {
computerPlay();
if (roundResult === 'You win, rock beats scissors' || roundResult === 'You win, paper beats rock.' || roundResult === 'You win, scissors beats paper.') {
++playerScore;
} else if (roundResult === 'You lose, paper beats rock.' || roundResult === 'You lose, scissors beats paper.' || roundResult === 'You lose, rock beats scissors.') {
++computerScore
}
}
if (playerScore > computerScore) {
return ('You win ' + playerScore + ' to ' + computerScore + '.');
} else if (playerScore < computerScore) {
return ('You lose ' + computerScore + ' to ' + playerScore + '.');
} else {
return 'It was a tie, you both won the same number of rounds.';
}
}
Like this it will return the result only when the loop is finished.
(And btw the playerScore and computerScore variables in your computerPlay() function are useless :p)

Related

Scoreboard and determine winner Rock Paper Scissors (JavaScript)

I'm working on Rock Paper Scissors and I'm lost at how to keep and display scores as well as determine a winner when they reach a score of 5. Right now, I'm adding +1 to the playerScore or compScore depending on the single round result, but I don't know how to display or keep track of it. Here is my code so far. Any tips are greatly appreciated!
//choices array
const choices = ["rock", "paper", "scissors"];
//set scores to 0
let playerScore = 0;
let compScore = 0;
//Get random choice from comp
function getComputerChoice() {
const randomNum = Math.floor(Math.random() * 3) //Generate random num with Math.random(), to ensure it's between 0 and 3, multiply by 3. Use Math.floor to round to down to nearest num
switch (randomNum) { //Create switch statement to take randomNum variable to perform different action based on the condition (case)
case 0:
return "rock";
case 1:
return "paper";
case 2:
return "scissors";
}
}
//single round gameplay
function playRound(playerSelection, computerSelection) {
if (playerSelection == "rock" && computerSelection == "scissors") {
//Add 1 to playerScore
playerScore+= 1
return "You win! Rock beats scissors";
} else if (playerSelection == "rock" && computerSelection == "paper") {
//Add 1 to compScore
compScore+= 1
return "You lose. Paper beats rock";
} else if (playerSelection == "scissors" && computerSelection == "paper") {
playerScore+= 1
return "You win! Scissors beat paper";
} else if (playerSelection == "scissors" && computerSelection == "rock") {
compScore+= 1
return "You lose. Rock beats scissors";
} else if (playerSelection == "paper" && computerSelection == "rock") {
playerScore+= 1
return "You win! Paper beats rock";
} else if (playerSelection == "paper" && computerSelection == "scissors") {
compScore+= 1
return "You lose. Scissors beat paper";
} else if (playerSelection === computerSelection) {
return "It's a tie";
} else {
return "Try again";
}
}
function userInput() {
let ask = false;
//while ask is still false, continue looping
while (ask == false){
const selction = prompt("Rock Paper or Scissors?")
// if the prompt return is empty
if (selction == null){
//keep looping
continue;
}
const selctionLower = selction.toLowerCase();
//ask if array of choices [rock, paper, scissors] is in the user input
if (choices.includes(selctionLower)){
//then ask is true
ask = true;
return selctionLower;
}
}
}
function game() {
//loop
for (let i = 0; i < 5; i++) {
const playerSelection = userInput();
const computerSelection = getComputerChoice();
//call playRound function
console.log(playRound(playerSelection, computerSelection));
}
}
game()

Javascript output in alert is different in console, and counter is not working properly even when condition is met

I'm making a rock paper scissors games where the counter should add 1 if user wins, add 0.5 if it's a tie, and remains the same if user lost. But in the alert and what's shown in the console doesn't match. Sometimes its shown in the alert that I win and in the console its shown I lose or its a tie. And the counter doesn't add up correctly.
In the image above it's shown 3 wins, 1 tie, and 1 lose. It should show I've won 3.5 games but it shows 5.5. And there is only 5 games played so it should be impossible to win 5.5.
Here is the code:
let winCounter = 0;
// playRound function will play a game of rock, paper, scissors and returns the result
function playRound(playerSelection, computerSelection) {
let getPlayerInsensitive = playerSelection.toLowerCase();
if (getPlayerInsensitive === "rock" && computerSelection === "Rock") {
winCounter+=0.5;
return "It's a tie, both are Rock";
} else if (getPlayerInsensitive === "rock" && computerSelection === "Paper") {
winCounter = winCounter;
return "You Lose! Paper beats Rock";
} else if (getPlayerInsensitive === "rock" && computerSelection === "Scissors") {
winCounter+=1;
return "You win! Rock beats Scissors";
} else if (getPlayerInsensitive === "paper" && computerSelection === "Rock") {
winCounter+=1;
return "You win! Paper beats Rock";
} else if (getPlayerInsensitive === "paper" && computerSelection === "Paper") {
winCounter+=0.5;
return "It's a tie! Both are Paper";
} else if (getPlayerInsensitive === "paper" && computerSelection === "Scissors") {
winCounter = winCounter;
return "You lose! Scissors beats Paper";
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Rock") {
winCounter = winCounter;
return "You lose! Rock beats Scissors";
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Scissors") {
winCounter=0.5;
return "It's a tie! Both are Scissors";
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Paper") {
winCounter+=1;
return "You win! Scissors beat Paper";
} else {
return "Check your spelling!";
}
}
// game function returns the winner after five rounds
function game() {
for (let i = 0; i < 5; i++) {
let getSelect = prompt("Choose Rock, Paper, or Scissors", "");
if (getSelect === null || getSelect === "") {
alert("You clicked Cancel!");
}
alert(playRound(getSelect, computerPlay()));
if (i < 5) {
console.log(playRound(getSelect, computerPlay()));
}
//outputs the winner of 5 games
if (i === 4) {
alert("You've played 5 games");
if (winCounter >= 3) {
alert(`You've won ${winCounter} out of 5 games. You win!`);
return `You've won ${winCounter} out of 5 games. You win!`;
} else if (winCounter === 2.5) {
alert(`You've won 2.5 out of 5 games. It's a tie!`);
return `You've won 2.5 out of 5 games. It's a tie!`;
} else if (winCounter < 2.5) {
alert(`You've won ${winCounter} out of 5 games. You lost!`);
return `You've won ${winCounter} out of 5 games. You lost!`;
}
}
}
}
console.log(game());
And here is the fiddle: https://jsfiddle.net/JaredDev/o62hr7as/125/
Why does it show different results in alert and console.log
It's because you called the computerPlay function twice, thus could returns different selection each time it is called,
alert(playRound(getSelect, computerPlay()));
if (i < 5) {
console.log(playRound(getSelect, computerPlay()));
}
you could change it to this, so it is called only once
const result = playRound(getSelect, computerPlay())
alert(result);
if (i < 5) {
console.log(result)
}
also why the score could be more than it should have, its because playRound function also called twice each turn
Caling code with random behaviour and side-effects twice
This piece of code produces an unintended result because the function computerPlay has random behaviour and the function playRound has has side-effects (modifies the winCounter).
alert(playRound(getSelect, computerPlay()));
if (i < 5) {
console.log(playRound(getSelect, computerPlay()));
}
You could correct this part of the problem by calling the function only once and assigning its result to a variable:
const result = playRound(getSelect, computerPlay());
alert(result);
if (i < 5) {
console.log(result);
}
Typo
You also have a typo:
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Scissors") {
winCounter=0.5;
return "It's a tie! Both are Scissors";
This should say += not just =:
winCounter+=0.5;

JS CLI RPS game issue

Greetings to the caring people of Stack Overflow.
I just recently started to learn JS and am now trying to make a CLI Rock Paper Scissors game. Yes, I know that I am the 100th person who has asked questions about it, but I could not find the 'no-make-sense' code through the code of other people. So just I ask for help from everyone who is not indifferent to helping a newbie!
The situation is this: the most common rules of a familiar game, but I can't get the counter to work, plus sometimes the text I type in is not recognized (I think the reason for the input comparison function).
Also, I'm sure that my func scopes are broken but where and why I can't figure out or trace it.
function computerPlay() {
let anyPick = Math.random();
if (anyPick < 0.3) {
return "Rock";
}
if (anyPick > 0.3 && anyPick < 0.6) {
return "Paper";
}
if (anyPick > 0.6) {
return "Scissors";
}
}
let aiScore = 0;
let playerScore = 0;
function battleRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return "None of you are win or lose, cuz it is an equal!";
}
if (playerSelection === "rock" && computerSelection === "Scissors") {
playerScore += 1;
return "You Win! Rock beats Scissors";
}
if (playerSelection === "rock" && computerSelection === "Paper") {
aiScore += 1;
return "You Loose! Paper beats Rock";
}
if (playerSelection === "paper" && computerSelection === "Scissors") {
aiScore += 1;
return "You Loose! Scissors cut Paper";
}
if (playerSelection === "paper" && computerSelection === "Rock") {
playerScore += 1;
return "You Win! Paper beats Rock";
}
if (playerSelection === "scissors" && computerSelection === "Paper") {
playerScore += 1;
return "You Win! Scissors cut Paper";
}
if (playerSelection === "scissors" && computerSelection === "Rock") {
aiScore += 1;
return "You Loose! Rock beats Scissors";
} else return "U misspelled, try again";
}
function scores(aiScore, playerScore) {
if (aiScore > playerScore) {
return "CONGRAS, AI IS SMARTER THEN YOU!";
}
if (playerScore > aiScore) {
return "CONGRAS, YOU ARE SMARTER THEN AI";
}
}
for (let i = 0; i < 5; i++) {
const playerSelection = prompt(
"Choose: Rock, Paper or Scissors",
" "
).toLowerCase();
const computerSelection = computerPlay();
console.log("AI choose: " + computerSelection);
console.log(battleRound(playerSelection, computerSelection));
console.log("AI score: " + aiScore, "Player score: " + playerScore);
}
Please, indicate an obvious problem in the code and what exactly I need to replace.
Much obliged for any tips!
There are two main problems with your code that might be causing this issue,
You are setting the default prompt value to an empty space. By using:
prompt("Choose: Rock, Paper or Scissors", " ")
The default prompt value is an empty space, making it easier to mistype the value.
To fix this, I removed the default value and added the .trim() method to remove whitespace from the start and end of the input.
You are making impossible comparisons. In your code you made the comparison:
if (playerSelection === computerSelection) {
return ("None of you are win or lose, cuz it is an equal!");
}
This condition will never be true, as the playerSelection is always converted to lowercase e.g "rock", but the computerSelection's first letter is always uppercase e.g "Rock".
I added the .toLowerCase() method to the end of computerSelection before comparing.
Full code:
function computerPlay() {
let anyPick = Math.random();
if (anyPick < 0.3) {
return "Rock";
}
if (anyPick > 0.3 && anyPick < 0.6) {
return "Paper";
}
if (anyPick > 0.6) {
return "Scissors";
}
}
let aiScore = 0;
let playerScore = 0;
function battleRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection.toLowerCase()) {
return "None of you are win or lose, cuz it is an equal!";
}
if (playerSelection === "rock" && computerSelection === "Scissors") {
playerScore += 1;
return "You Win! Rock beats Scissors";
}
if (playerSelection === "rock" && computerSelection === "Paper") {
aiScore += 1;
return "You Loose! Paper beats Rock";
}
if (playerSelection === "paper" && computerSelection === "Scissors") {
aiScore += 1;
return "You Loose! Scissors cut Paper";
}
if (playerSelection === "paper" && computerSelection === "Rock") {
playerScore += 1;
return "You Win! Paper beats Rock";
}
if (playerSelection === "scissors" && computerSelection === "Paper") {
playerScore += 1;
return "You Win! Scissors cut Paper";
}
if (playerSelection === "scissors" && computerSelection === "Rock") {
aiScore += 1;
return "You Loose! Rock beats Scissors";
} else return "U misspelled, try again";
}
function finalScores() {
if (aiScore > playerScore) {
return "CONGRATS, AI IS SMARTER THEN YOU!";
}
if (playerScore > aiScore) {
return "CONGRATS, YOU ARE SMARTER THEN AI";
}
}
for (let i = 0; i < 5; i++) {
const playerSelection = (prompt("Choose: Rock, Paper or Scissors") ?? "")
.trim()
.toLowerCase();
const computerSelection = computerPlay();
console.log("AI choose: " + computerSelection);
console.log(battleRound(playerSelection, computerSelection));
console.log("AI score: " + aiScore, "Player score: " + playerScore);
}
console.log(finalScores())

JavaScript project rock-paper-scissors---issues with console during first load of the page

When you open the page for the first time, you are presented with a prompt box like intended, but you want to open dev-tools/console to watch the console.log messages appear.
For some reason, if u open dev-tools/console after the prompt window pops, console.logs don't appear and you have to play the game till the end to see them.
Here is the link to the page : https://kloba1004.github.io/project-rock-paper-scissors/
Can anyone give your honest opinion on my code given that I am not experienced:
let userWins = 0,
computerWins = 0;
function game() {
for (i = 0; i < 5; i++) {
let playerSelection = prompt("Choose rock, paper or scissors: "),
computerSelection;
const choices = ['rock', 'paper', 'scissors'];
let computerPlay = Math.random() * 10;
if (playerSelection !== null) {
playerSelection = playerSelection.toLowerCase().trim();
}
while ((playerSelection === null) || (playerSelection === '') || (!choices.includes(playerSelection))) {
if (playerSelection === '' || playerSelection === null) {
playerSelection = prompt("U entered absolutely nothing. Try again...Rock, paper or scissors:")
} else {
playerSelection = prompt("You typed it wrong. Try again. Choose rock, paper or scissors: ");
if (playerSelection !== null) {
playerSelection = playerSelection.toLowerCase().trim();
};
}
}
playerSelection = playerSelection.toLowerCase().trim();
function playRound(playerSelection, computerSelection) {
if (computerPlay >= 0 && computerPlay < 3.5) {
computerSelection = 'rock';
if (playerSelection === 'scissors') {
computerWins = computerWins + 1;
return `You lost this round. Rock beats scissors.`;
} else if (playerSelection === 'paper') {
userWins = userWins + 1;
return `You won this round. Paper beats rock.`;
} else {
return `Neither won this round. Rock can\'t beat rock.`;
}
} else if (computerPlay >= 3.5 && computerPlay < 6.5) {
computerSelection = 'paper';
if (playerSelection === 'scissors') {
userWins = userWins + 1;
return `You won this round. Scissors beat paper.`;
} else if (playerSelection === 'rock') {
computerWins = computerWins + 1;
return `You lost this round. Paper beats rock.`;
} else {
return `Neither won this round. Paper can\'t beat paper.`
}
} else {
computerSelection = 'scissors';
if (playerSelection === 'rock') {
userWins = userWins + 1;
return `You won this round. Rock beats scissors.`;
} else if (playerSelection === 'paper') {
computerWins = computerWins + 1;
return `You lost this round. Scissors beat paper.`;
} else {
return `Neither win. Scissors can\'t beat scissors.`;
}
}
}
console.log(playRound(playerSelection, computerSelection) + `Current score is ${userWins} : ${computerWins}.`);
}
if (userWins > computerWins) {
console.log(`You won the game. Final score is ${userWins} : ${computerWins}.`);
} else if (userWins === computerWins) {
console.log(`Neither won the game. Final score is ${userWins} : ${computerWins}.`);
} else {
console.log(`You lost the game. Final score is ${userWins} : ${computerWins}.`);
}
}
game();
Your code looks like this:
function game() {
// Loop
for (i = 0; i < 5; i++) {
let playerSelection = prompt("Choose rock, paper or scissors: "),
computerSelection;
const choices = ["rock", "paper", "scissors"];
let computerPlay = Math.random() * 10;
if (playerSelection !== null) {
playerSelection = playerSelection.toLowerCase().trim();
}
while (
playerSelection === null ||
playerSelection === "" ||
!choices.includes(playerSelection)
) {
if (playerSelection === "" || playerSelection === null) {
playerSelection = prompt(
"U entered absolutely nothing. Try again...Rock, paper or scissors:"
);
} else {
playerSelection = prompt(
"You typed it wrong. Try again. Choose rock, paper or scissors: "
);
if (playerSelection !== null) {
playerSelection = playerSelection.toLowerCase().trim();
}
}
}
playerSelection = playerSelection.toLowerCase().trim();
function playRound(playerSelection, computerSelection) {
...
}
console.log(
playRound(playerSelection, computerSelection) +
`Current score is ${userWins} : ${computerWins}.`
);
}
// Console logs
if (userWins > computerWins) {
console.log(
`You won the game. Final score is ${userWins} : ${computerWins}.`
);
} else if (userWins === computerWins) {
console.log(
`Neither won the game. Final score is ${userWins} : ${computerWins}.`
);
} else {
console.log(
`You lost the game. Final score is ${userWins} : ${computerWins}.`
);
}
}
As you can see, the console.logs are placed after the for loop, which prompts the user.
So naturally they would execute after the game ends.
Update:
Regarding the first console.log, it executed at the end of loop because you are declaring the playRound function at each iteration (and it gets pushed to stack).
To get the expected behavior, move it's declaration like this:
<script>
let userWins = 0,
computerWins = 0;
function playRound(playerSelection, computerSelection, computerPlay) {
if (computerPlay >= 0 && computerPlay < 3.5) {
computerSelection = "rock";
if (playerSelection === "scissors") {
computerWins = computerWins + 1;
return `You lost this round. Rock beats scissors.`;
} else if (playerSelection === "paper") {
userWins = userWins + 1;
return `You won this round. Paper beats rock.`;
} else {
return `Neither won this round. Rock can\'t beat rock.`;
}
} else if (computerPlay >= 3.5 && computerPlay < 6.5) {
computerSelection = "paper";
if (playerSelection === "scissors") {
userWins = userWins + 1;
return `You won this round. Scissors beat paper.`;
} else if (playerSelection === "rock") {
computerWins = computerWins + 1;
return `You lost this round. Paper beats rock.`;
} else {
return `Neither won this round. Paper can\'t beat paper.`;
}
} else {
computerSelection = "scissors";
if (playerSelection === "rock") {
userWins = userWins + 1;
return `You won this round. Rock beats scissors.`;
} else if (playerSelection === "paper") {
computerWins = computerWins + 1;
return `You lost this round. Scissors beat paper.`;
} else {
return `Neither win. Scissors can\'t beat scissors.`;
}
}
}
function game() {
for (i = 0; i < 5; i++) {
let playerSelection = prompt("Choose rock, paper or scissors: "),
computerSelection;
const choices = ["rock", "paper", "scissors"];
let computerPlay = Math.random() * 10;
if (playerSelection !== null) {
playerSelection = playerSelection.toLowerCase().trim();
}
while (
playerSelection === null ||
playerSelection === "" ||
!choices.includes(playerSelection)
) {
if (playerSelection === "" || playerSelection === null) {
playerSelection = prompt(
"U entered absolutely nothing. Try again...Rock, paper or scissors:"
);
} else {
playerSelection = prompt(
"You typed it wrong. Try again. Choose rock, paper or scissors: "
);
if (playerSelection !== null) {
playerSelection = playerSelection.toLowerCase().trim();
}
}
}
playerSelection = playerSelection.toLowerCase().trim();
console.log(
playRound(playerSelection, computerSelection, computerPlay) +
`Current score is ${userWins} : ${computerWins}.`
);
}
if (userWins > computerWins) {
console.log(
`You won the game. Final score is ${userWins} : ${computerWins}.`
);
} else if (userWins === computerWins) {
console.log(
`Neither won the game. Final score is ${userWins} : ${computerWins}.`
);
} else {
console.log(
`You lost the game. Final score is ${userWins} : ${computerWins}.`
);
}
}
game();
</script>
The function game() is called right after loading the page, which it will be fired and shows up directly the alert modal, I would suggest adding a button with onclick attribute and call the function from there, so you can before start playing open the console
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rock | paper | scissors</title>
</head>
<body>
<button onclick="game()">Play</button>
<script>
let userWins = 0,
computerWins = 0;
function game() {
for(i=0; i<5; i++) {
let playerSelection = prompt("Choose rock, paper or scissors: "),
computerSelection;
const choices = [ 'rock', 'paper', 'scissors'];
let computerPlay= Math.random()*10;
if (playerSelection!==null) {
playerSelection = playerSelection.toLowerCase().trim();
}
while ((playerSelection===null) || (playerSelection==='') || (!choices.includes(playerSelection)) ) {
if (playerSelection==='' || playerSelection===null) {
playerSelection = prompt("U entered absolutely nothing. Try again...Rock, paper or scissors:")
}
else {
playerSelection = prompt("You typed it wrong. Try again. Choose rock, paper or scissors: ");
if (playerSelection!==null) {
playerSelection = playerSelection.toLowerCase().trim();
};
}
}
playerSelection = playerSelection.toLowerCase().trim();
function playRound(playerSelection, computerSelection) {
if (computerPlay>=0 && computerPlay<3.5) {
computerSelection= 'rock';
if (playerSelection==='scissors') {
computerWins= computerWins+1;
return `You lost this round. Rock beats scissors.`;
} else if (playerSelection==='paper') {
userWins= userWins+1;
return `You won this round. Paper beats rock.`;
} else{
return `Neither won this round. Rock can\'t beat rock.`;
}
}
else if (computerPlay>=3.5 && computerPlay<6.5) {
computerSelection= 'paper';
if (playerSelection==='scissors') {
userWins= userWins+1;
return `You won this round. Scissors beat paper.`;
} else if (playerSelection==='rock') {
computerWins= computerWins+1;
return `You lost this round. Paper beats rock.`;
} else{
return `Neither won this round. Paper can\'t beat paper.`
}
}
else {
computerSelection= 'scissors';
if (playerSelection==='rock') {
userWins= userWins+1;
return `You won this round. Rock beats scissors.`;
} else if (playerSelection==='paper') {
computerWins= computerWins+1;
return `You lost this round. Scissors beat paper.`;
} else{
return `Neither win. Scissors can\'t beat scissors.`;
}
}
}
console.log(playRound(playerSelection,computerSelection)+`Current score is ${userWins} : ${computerWins}.`);
}
if (userWins>computerWins) {
console.log(`You won the game. Final score is ${userWins} : ${computerWins}.`);
} else if (userWins===computerWins) {
console.log(`Neither won the game. Final score is ${userWins} : ${computerWins}.`);
} else {
console.log(`You lost the game. Final score is ${userWins} : ${computerWins}.`);
}
}
</script>
</body>
</html>

Javascript if/else not working. Odin project's Rock, paper, scissors

I’ve been trying to solve the Rock, Paper and Scissors project but I can’t figure out how to make the if/else statement. I did it a lot of times and finally I think I’m near to solve the issue, but the thing is, every time I run the program I get the wrong output.
For example, I used ‘Paper’ and the computer used ‘Rock’, but the console showed that ‘It’s a tie’, but in the code I wrote that if player chose paper and computer chose rock the message should have been ‘You win. Paper beats Rock’. The same happens when I choose ‘Paper’ and the computer chooses ‘Scissors’.
I used toLowerCase() method but after many changes, even when remove it and write exactly the words in the if/else this does not appear to be the problem.
What do I need to correct? Thank you so much!!!
This is the code:
<!DOCTYPE html>
<html>
<head>
<title>Rock Paper Scissors!</title>
</head>
<body>
<script>
//Computer's selection
function computerPlay() {
let selectRandom = Math.floor(Math.random() * 3);
if (selectRandom === 0) {
return 'Rock';
} else if (selectRandom === 1) {
return 'Paper';
} else {
return 'Scissors';
}
}
console.log('Computer chose: ' + computerPlay());
//Play round between humand and computer
function playRound(playerSelection, computerSelection) {
//Change to lowercase
let player = playerSelection.toLowerCase();
let computer = computerSelection.toLowerCase();
//If player chooses rock
if (player === 'rock') {
if (computer === 'rock') {
return 'It\'s a tie. Try again'
} else if (computer === 'paper') {
return 'You loose. Paper beats Rock'
} else {
return 'You win. Rock beats scissors'
}
}
//If player chooses paper
else if (player === 'paper') {
if (computer === 'paper') {
return 'It\'s a tie. Try again'
}
if (computer === 'scissors') {
return 'You loose. Scissors beats Paper'
} else {
return 'You win. Paper beats Rock'
}
}
//If player chooses scissors
else {
if (computer === 'scissors') {
return 'It\'s a tie. Try again'
} else if (computer === 'rock') {
return 'You loose. Rock beats Scissors'
} else {
return 'You win. Scissors beats Paper'
}
}
}
const playerSelection = 'Paper';
const computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
</script>
</body>
</html>
As you must have already known, every time you call computerPlay(), computer chooses a random value.
When you call computerPlay() in below statement, you get a random selection.
console.log('Computer chose: ' + computerPlay()); // Random selection.
And when you call the function again later in the code as shown below, you get another random selection.
const computerSelection = computerPlay(); // Random selection.
console.log(playRound(playerSelection, computerSelection));
This is the reason the output you see is not consistent with the actual result.
Solution: Move above console.log() statement to execute after computer selection, and log the returned value, don't call computerPlay() again. If you call it again, you'll get another random selection, not the one you are passing to playRound() function.
const computerSelection = computerPlay();
console.log('Computer chose: ' + computerSelection);
console.log(playRound(playerSelection, computerSelection));
Working Example:
<!DOCTYPE html>
<html>
<head>
<title>Rock Paper Scissors!</title>
</head>
<body>
<script>
//Computer's selection
function computerPlay() {
let selectRandom = Math.floor(Math.random() * 3);
if (selectRandom === 0) {
return 'Rock';
} else if (selectRandom === 1) {
return 'Paper';
} else {
return 'Scissors';
}
}
//Play round between human and computer
function playRound(playerSelection, computerSelection) {
//Change to lowercase
let player = playerSelection.toLowerCase();
let computer = computerSelection.toLowerCase();
//If player chooses rock
if (player === 'rock') {
if (computer === 'rock') {
return 'It\'s a tie. Try again'
} else if (computer === 'paper') {
return 'You loose. Paper beats Rock'
} else {
return 'You win. Rock beats scissors'
}
}
//If player chooses paper
else if (player === 'paper') {
if (computer === 'paper') {
return 'It\'s a tie. Try again'
}
if (computer === 'scissors') {
return 'You loose. Scissors beats Paper'
} else {
return 'You win. Paper beats Rock'
}
}
//If player chooses scissors
else {
if (computer === 'scissors') {
return 'It\'s a tie. Try again'
} else if (computer === 'rock') {
return 'You lose. Rock beats Scissors'
} else {
return 'You win. Scissors beats Paper'
}
}
}
const playerSelection = 'Paper';
const computerSelection = computerPlay();
console.log('Computer chose: ' + computerSelection);
console.log(playRound(playerSelection, computerSelection));
</script>
</body>
</html>

Categories