Rock Paper Scissors JS Game - javascript

I'm a complete beginner with JS and I'm struggling to understand the logic with this one. Nothing is being logged in the console, although I am getting the alert inputs. Can anyone point out where I'm going wrong? Is it perhaps something to do with scope? I feel like this should be really simple but I can't get it working.
function computerPlay() {
const options = ['rock', 'paper', 'scissors'];
let result = options[Math.floor(Math.random() * options.length)];
return result;
}
function playRound(playerSelection, computerSelection) {
let selection = prompt('Please enter your selection');
let playerScore = 0;
let computerScore = 0;
let result = "";
computerSelection = computerPlay();
playerSelection = selection.toLowerCase();
if (playerSelection == 'rock') {
if (computerSelection == 'rock') {
return ["It's a draw!", playerScore + 1, computerScore + 1];
} else if (computerSelection == 'paper') {
return ["You lose!", computerScore + 1];
} else {
return ["You win!", computerScore + 1];
}
} else if (playerSelection == 'paper') {
if (computerSelection == 'paper') {
return "It's a draw!";
} else if (computerSelection == 'scissors') {
return "Computer wins!";
} else {
return "You win!";
}
} else if (playerSelection == 'scissors') {
if (computerSelection == 'scissors') {
return "It's a draw!"
} else if (computerSelection == 'rock') {
return "Computer wins!"
} else {
return "You win!"
}
}
return result + "Player Score = " + playerScore + "Computer Score = " + computerScore;
}
function game() {
for (let i = 0; i < 5; i++) {
computerPlay();
playRound();
}
}
console.log(game())

Move your console log from where it is to inside the game() function like so:
for (let i = 0; i < 5; i++) {
console.log(playRound());
}
You also don't need to call computerPlay() in the game function, as it is doing nothing.

Modify the game function this way.
function game() {
for (let i = 0; i < 5; i++) {
const result = playRound();
console.log(result)
}
}
game()
Then you call game(). You will be able to see your console log and also you do not need to call the computerPlay function inside the game function. It's functionality is already called in the playRound function. Hope this helps cheers

Related

Rock Paper Scissors does an extra loop before return, not sure how to fix this

If you scroll down to my Game loop comment, I have my function game().
I want my game to stop looping when either the playerPoints or computerPoints reaches 5. Both of them have a separate return in the if else statements.
The problem for me is that instead of adding the final point and then returning the "you win" or "you lose" statements, it prompts the user one more time, and then returns the "You win" or "you lose". It doesn't interfere with the points, however it's a small bug I still want to fix.
When I review my code, I know my alert(playRound) is after my gameContinue declaration and I wonder if it's placement is the reason it is happening again and then returning my result. If that is the problem, how can I continue my game loop until someone reaches five points?
If that isn't the problem, then could I just get a tip on what method I should try instead? Thank you.
let playerPoints = 0;
let computerPoints = 0;
// Computer Selection
function computerPlay() {
const compAnswer = options[Math.floor(Math.random() * options.length)];
return compAnswer;
}
// One round of the game results
function playRound(playerSelection, computerSelection) {
let rock = options[0];
let paper = options[1];
let scissors = options[2];
let youWin = "You Win! ";
let youLose = "You Lose! ";
let rockWin = "Rock beats scissors.";
let scissorWin = "Scissors beats paper.";
let paperWin = "Paper beats rock.";
let tie = "It's a tie, no points added."
if (playerSelection === computerSelection) {
console.log(playerPoints, computerPoints);
return tie;
} else if (playerSelection === rock && computerSelection === scissors) {
playerPoints = playerPoints + 1;
console.log(playerPoints, computerPoints);
return youWin + rockWin;
} else if (playerSelection === rock && computerSelection == paper) {
computerPoints = computerPoints + 1;
console.log(playerPoints, computerPoints);
return youLose + paperWin;
} else if (playerSelection === scissors && computerSelection === rock) {
computerPoints = computerPoints + 1;
console.log(playerPoints, computerPoints)
return youLose + rockWin;
} else if (playerSelection === scissors && computerSelection === paper) {
playerPoints = playerPoints + 1;
console.log(playerPoints, computerPoints)
return youWin + scissorWin;
} else if (playerSelection === paper && computerSelection === rock) {
playerPoints = playerPoints + 1;
console.log(playerPoints, computerPoints);
return youWin + paperWin;
} else if (playerSelection === paper && computerSelection === scissors) {
computerPoints = computerPoints + 1;
console.log(playerPoints, computerPoints);
return youLose + scissorWin;
} else {
console.log(playerPoints, computerPoints);
return "I'm sorry please try another answer"
}
};
//Game loop
function game() {
let gameContinue = true;
while (gameContinue) {
const computerSelection = computerPlay();
const playerSelection = prompt("Choose your weapon");
if (playerPoints < 5 && computerPoints < 5) {
gameContinue = true;
alert(playRound(playerSelection, computerSelection));
} else if (playerPoints === 5) {
gameContinue = false;
console.log("You win");
} else if (computerPoints === 5) {
gameContinue = false;
console.log("You Lose")
}
}
};
game();
It's a logic bug in your code. I'm happy to tell you the answer, but maybe I can just give you a hint so you can learn from it.
Imagine the player just won his 5th game.
Put your finger on this line of code:
alert(playRound(playerSelection, computerSelection));
And at this point, we know that playerPoints is 5.
After the user dismisses the alert dialog, what line of code runs next after the alert function returns?
Here's another hint: gameContinue remains true after the alert statement returns. What line of code were you expecting to run to set it to false ?

The counter doesn't change its value in html page

I've put playerScore and computerScore variables in global scope. When user wins or loses these values increment by one number. They do work well. But in my HTML page they do not change dynamically.
Why my playerScore and computerScore values do not change in my HTML page, when I console.log them separately in console they are changed, but not in html page. I've tried to put them in function but it didn't work as expected.
// Selecting all the items with tag button
const buttons = document.querySelectorAll('button');
// Returns random item and assignes it to computerSelection variable
function computerPlay() {
const rps = ['rock', 'paper', 'scissors'];
let numberItem = Math.floor(Math.random() * rps.length);
computerSelection = rps[numberItem];
if (computerSelection === 'rock') {
console.log('computer selections is rock');
return computerSelection;
}
else if (computerSelection === 'paper' ) {
console.log('It is a paper!');
return computerSelection;
}
console.log('it is scissors');
return computerSelection;
}
// Plays game only five rounds;
let computerScore = 0;
let playerScore = 0;
function playRound(playerSelection, computerSelection) {
if(playerScore < 5 && computerScore < 5 ) {
if(((playerSelection == 'rock') && (computerSelection == 'paper')) || ((playerSelection == 'paper') && (computerSelection == 'scissors')) ||
((playerSelection == 'scissors') && (computerSelection == 'rock') )) {
console.log(`${computerSelection} beats ${playerSelection} the ROBOT WINS!`);
playerScore++;
return console.log(playerScore);
}
else if (((playerSelection == 'rock') && (computerSelection == 'scissors')) || ((playerSelection == 'paper') && (computerSelection == 'rock')) ||
((playerSelection == 'scissors') && (computerSelection == 'paper'))) {
console.log(` ${playerSelection} beats ${computerSelection} the PLAYER WINS!`);
computerScore++;
return console.log(computerScore);
}
return console.log('It is a DRAW');;
}
return console.log("GAME OVER!!!");
}
// returns value of clicked button and plays round
function fetchButtonValue(e) {
let itemClicked = e.target.dataset.item;
console.log(` THIS WAS CLICKED ${itemClicked}`);
return playRound(itemClicked, computerPlay());
}
// uses fetchButtonValue
buttons.forEach(function(button) {
button.addEventListener('click', fetchButtonValue);
});
// implement the vlaues to HTML but they doesn't change but the value changes when tracking them in console of browser.
let score= `
<p class = 'playerPoints'>Player: ${playerScore}</p>
<p class = 'computerPoints'>Computer: ${computerScore}</p>
`;
const divScore = document.querySelector('.score');
divScore.insertAdjacentHTML('beforebegin', scoreHTML);

How to change value of outer variable using a inner function?

In following code, the outer variables playerScore and computerScore are not updated when I use the function calcScore? How do I update it, using a function? From what I understand, it is possible to change the value of the outer variable from an inner scope, but why does it not work here?
<script>
function playRound(playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase();
computerSelection = computerSelection.toLowerCase();
if (playerSelection === computerSelection) {
return "draw";
}
else if (playerSelection === "rock"){
if (computerSelection === "scissors") return "win";
else if (computerSelection === "paper") return "lose";
}
else if (playerSelection === "paper"){
if (computerSelection === "scissors") return "lose";
else if (computerSelection === "rock") return "win";
}
else if (playerSelection === "scissors"){
if (computerSelection === "rock") return "lose";
else if (computerSelection === "paper") return "win";
}
}
function computerSelection() {
let selection = ["rock", "paper", "scissors"];
return selection[Math.floor(Math.random() * selection.length)];
}
function calcScore(result, playerScore, computerScore) {
if (result === "win") {
playerScore += 1;
console.log("win");
}
else if (result === "lose") {
computerScore += 1;
console.log("lose");
}
else if (result === "draw") {
playerScore += 1;
computerScore += 1;
}
}
function game() {
let playerScore = 0;
let computerScore = 0;
for (let i = 1; i <= 5; i++) {
let result = playRound(prompt("Select rock, paper, or scissors!"), computerSelection());
calcScore(result, playerScore, computerScore);
console.log(`You have ${playerScore} points! Computer has ${computerScore} points!`);
}
playerScore, computerScore = 0, 0;
}
</script>
Javascript doesn't pass variables by reference - so any modifications you do to playerScore and computerScore within calcScore() are only local to that function.
What you can do is make playerScore and computerScore global variables. That way any modifications will be in the global scope. Alternatively, you could have calcScore() return the modified values.
Using the global method:
<script>
let playerScore = 0;
let computerScore = 0;
function playRound(playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase();
computerSelection = computerSelection.toLowerCase();
if (playerSelection === computerSelection) {
return "draw";
}
else if (playerSelection === "rock"){
if (computerSelection === "scissors") return "win";
else if (computerSelection === "paper") return "lose";
}
else if (playerSelection === "paper"){
if (computerSelection === "scissors") return "lose";
else if (computerSelection === "rock") return "win";
}
else if (playerSelection === "scissors"){
if (computerSelection === "rock") return "lose";
else if (computerSelection === "paper") return "win";
}
}
function computerSelection() {
let selection = ["rock", "paper", "scissors"];
return selection[Math.floor(Math.random() * selection.length)];
}
function calcScore(result) {
if (result === "win") {
playerScore += 1;
console.log("win");
}
else if (result === "lose") {
computerScore += 1;
console.log("lose");
}
else if (result === "draw") {
playerScore += 1;
computerScore += 1;
}
}
function game() {
for (let i = 1; i <= 5; i++) {
let result = playRound(prompt("Select rock, paper, or scissors!"), computerSelection());
calcScore(result);
console.log(`You have ${playerScore} points! Computer has ${computerScore} points!`);
}
playerScore, computerScore = 0, 0;
}
</script>
Alternative method:
<script>
function playRound(playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase();
computerSelection = computerSelection.toLowerCase();
if (playerSelection === computerSelection) {
return "draw";
}
else if (playerSelection === "rock"){
if (computerSelection === "scissors") return "win";
else if (computerSelection === "paper") return "lose";
}
else if (playerSelection === "paper"){
if (computerSelection === "scissors") return "lose";
else if (computerSelection === "rock") return "win";
}
else if (playerSelection === "scissors"){
if (computerSelection === "rock") return "lose";
else if (computerSelection === "paper") return "win";
}
}
function computerSelection() {
let selection = ["rock", "paper", "scissors"];
return selection[Math.floor(Math.random() * selection.length)];
}
function calcScore(result, playerScore, computerScore) {
if (result === "win") {
playerScore += 1;
console.log("win");
}
else if (result === "lose") {
computerScore += 1;
console.log("lose");
}
else if (result === "draw") {
playerScore += 1;
computerScore += 1;
}
return [playerScore, computerScore];
}
function game() {
let playerScore = 0;
let computerScore = 0;
for (let i = 1; i <= 5; i++) {
let result = playRound(prompt("Select rock, paper, or scissors!"), computerSelection());
let scores = calcScore(result, playerScore, computerScore);
playerScore += scores[0];
computerScore += scores[1];
console.log(`You have ${playerScore} points! Computer has ${computerScore} points!`);
}
playerScore, computerScore = 0, 0;
}
</script>
your defining both of those variables twice so now im confused. do you want to be abled to reuse those variables in the game function without re defining them? because if thats the case then they should be global variables instead of function parameters(you wont be able to use those defined in the function parameter outside of that function).

Rock, paper, scissors game - repeating for 5 rounds

I am building the rock, paper scissors task. At the minute my code only works for 1 round. I'm unsure about how I would get this to keep the score, whilst repeating for 5 rounds. I'm under the impression i will need a for loop at least for the rounds, along the lines of:
for(i=0; i<5;i++);
but i don't know where to slot it into my code. I've looked around online, and i cant find a simple enough to understand resource that doesn't start using switch methods or any other more advanced code to build the game. Any help would be appreciated. Thanks.
function computerPlay() {
let random = Math.random();
if (random <= 0.3333) {
return "paper";
} else if (random >= 0.6666) {
return "rock";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
if (playerSelection.toLowerCase() === "rock") {
if (computerSelection === "paper") {
computerScore++;
return lose;
} else if (computerSelection === "rock") {
return tie;
} else {
userScore++;
return win;
}
}
if (playerSelection.toLowerCase() === "scissors") {
if (computerSelection === "paper") {
userScore++;
return win;
} else if (computerSelection === "rock") {
computerScore++;
return lose;
} else {
return tie;
}
}
if (playerSelection.toLowerCase() === "paper") {
if (computerSelection === "paper") {
return tie;
} else if (computerSelection === "rock") {
userScore++;
return win;
} else {
computerScore++;
return lose;
}
}
}
let userScore = parseInt(0);
let computerScore = parseInt(0);
let win = "You win"
let lose = "You lose"
let tie = "It is a tie"
let playerSelection = prompt("Pick a move");
const computerSelection = computerPlay()
console.log(playRound(playerSelection, computerSelection))
console.log("your score = " + userScore);
console.log("Computer's score = " + computerScore);
I have edited your code snipet little bit hope it will fulfill your need :)
just put below code into the for loop
let playerSelection = prompt("Pick a move");
const computerSelection = computerPlay()
console.log(playRound(playerSelection, computerSelection))
console.log("your score = " + userScore);
console.log("Computer's score = " + computerScore);
function computerPlay() {
let random = Math.random();
if (random <= 0.3333) {
return "paper";
} else if (random >= 0.6666) {
return "rock";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
if (playerSelection.toLowerCase() === "rock") {
if (computerSelection === "paper") {
computerScore++;
return lose;
} else if (computerSelection === "rock") {
return tie;
} else {
userScore++;
return win;
}
}
if (playerSelection.toLowerCase() === "scissors") {
if (computerSelection === "paper") {
userScore++;
return win;
} else if (computerSelection === "rock") {
computerScore++;
return lose;
} else {
return tie;
}
}
if (playerSelection.toLowerCase() === "paper") {
if (computerSelection === "paper") {
return tie;
} else if (computerSelection === "rock") {
userScore++;
return win;
} else {
computerScore++;
return lose;
}
}
}
let userScore = parseInt(0);
let computerScore = parseInt(0);
let win = "You win"
let lose = "You lose"
let tie = "It is a tie"
for(var i=0;i<5;i++){
let playerSelection = prompt("Pick a move");
const computerSelection = computerPlay()
console.log(playRound(playerSelection, computerSelection))
console.log("your score = " + userScore);
console.log("Computer's score = " + computerScore);
}
Try below code:
Looping is not a good approach, read here:
Recursion vs loops
https://www.refactoring.com/catalog/replaceIterationWithRecursion.html
It allows the user to play for 5 times.
Using recursion:
function computerPlay() {
let random = Math.random();
if (random <= 0.3333) {
return "paper";
} else if (random >= 0.6666) {
return "rock";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
if (playerSelection.toLowerCase() === "rock") {
if (computerSelection === "paper") {
computerScore++;
return lose;
} else if (computerSelection === "rock") {
return tie;
} else {
userScore++;
return win;
}
}
if (playerSelection.toLowerCase() === "scissors") {
if (computerSelection === "paper") {
userScore++;
return win;
} else if (computerSelection === "rock") {
computerScore++;
return lose;
} else {
return tie;
}
}
if (playerSelection.toLowerCase() === "paper") {
if (computerSelection === "paper") {
return tie;
} else if (computerSelection === "rock") {
userScore++;
return win;
} else {
computerScore++;
return lose;
}
}
}
let userScore = parseInt(0);
let computerScore = parseInt(0);
let win = "You win"
let lose = "You lose"
let tie = "It is a tie"
var i = 0;
const play = () => {
let playerSelection = prompt("Pick a move");
const computerSelection = computerPlay()
console.log(playRound(playerSelection, computerSelection))
console.log("your score = " + userScore);
console.log("Computer's score = " + computerScore);
i++;
if (i !== 5) {
play();
} else {
alert("Game Over=> User("+userScore+") vs Computer("+computerScore+")");
}
}
play();

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