Rock, paper, scissors game javascript - javascript

Currently stuck with a rock, paper, scissors game in javascript. Only my last function game() which needs to play a round 5 times is not working. Have tried to work with a for loop but it seems that I'm getting 5 times the same answer instead of 5 different random ones.
Could someone please help me out?
let playerScore = 0;
let computerScore = 0;
const playerSelection = playerPlay();
const computerSelection = computerPlay();
// computer select function
function computerPlay() {
const option = ['rock', 'paper', 'scissors'];
let random = Math.floor(Math.random() * 3);
return option[random];
}
console.log('Computer: ' + computerSelection);
// player select function
function playerPlay() {
const input = prompt('Please enter input');
const option = input.toLowerCase();
return option;
}
console.log('Player: ' + playerSelection);
// play 1 single round
function playRound(playerSelection, computerSelection) {
if(playerSelection === computerSelection) {
return 'It is a tie';
}
if(playerSelection === 'rock') {
if(computerSelection === 'scissors') {
playerScore++;
return 'Player wins with rock';
} else if(computerSelection === 'paper') {
computerScore++;
return 'Computer wins with paper'
}
}
if(playerSelection === 'paper') {
if(computerSelection === 'rock') {
playerScore++;
return 'Player wins with paper';
} else if(computerSelection === 'scissors') {
computerScore++;
return 'Computer wins with scissors';
}
}
if(playerSelection === 'scissors') {
if(computerSelection === "paper") {
playerScore++;
return 'Player wins with scissors';
} else if(computerSelection === 'rock') {
computerScore++;
return 'Computer wins with rock';
}
}
}
// console.log(playRound(playerSelection, computerSelection));
playRound(playerSelection, computerSelection);
console.log('Player: ' + playerScore);
console.log('Computer: ' + computerScore);
// game
function game() {
for(var i = 1; i <= 5; i++) {
console.log('repeat 5 times');
playRound(playerSelection, computerSelection);
}
}
game();

You have put a loop without asking for the player and computer input, hence it runs 5 times without taking any input. I have fixed this in the snippet. Not entirely sure if you want to run it this way though.
let playerScore = 0;
let computerScore = 0;
// computer select function
function computerPlay() {
const option = ['rock', 'paper', 'scissors'];
let random = Math.floor(Math.random() * 3);
return option[random];
}
// player select function
function playerPlay() {
const input = prompt('Please enter input');
const option = input.toLowerCase();
return option;
}
// play 1 single round
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return 'It is a tie';
}
if (playerSelection === 'rock') {
if (computerSelection === 'scissors') {
playerScore++;
return 'Player wins with rock';
} else if (computerSelection === 'paper') {
computerScore++;
return 'Computer wins with paper'
}
}
if (playerSelection === 'paper') {
if (computerSelection === 'rock') {
playerScore++;
return 'Player wins with paper';
} else if (computerSelection === 'scissors') {
computerScore++;
return 'Computer wins with scissors';
}
}
if (playerSelection === 'scissors') {
if (computerSelection === "paper") {
playerScore++;
return 'Player wins with scissors';
} else if (computerSelection === 'rock') {
computerScore++;
return 'Computer wins with rock';
}
}
}
// console.log(playRound(playerSelection, computerSelection));
// game
function game() {
for (i = 0; i <= 5; i++) {
var playerSelection = playerPlay();
var computerSelection = computerPlay();
playRound(playerSelection, computerSelection);
console.log('Computer: ' + computerSelection);
console.log('Player: ' + playerSelection);
console.log('Player: ' + playerScore);
console.log('Computer: ' + computerScore);
}
console.log('Final Player: ' + playerScore);
console.log('Final Computer: ' + computerScore);
}
game();

Your probleme is because you're set your playerSelection and computerSelection once (and even on a const ! So choice cannot be updated)
You just have to move this part into you for loop (and update to let instead of const)
let playerSelection = playerPlay();
let computerSelection = computerPlay();
let playerScore = 0;
let computerScore = 0;
// computer select function
function computerPlay() {
const option = ['rock', 'paper', 'scissors'];
let random = Math.floor(Math.random() * 3);
return option[random];
}
// player select function
function playerPlay() {
const input = prompt('Please enter input');
const option = input.toLowerCase();
return option;
}
// play 1 single round
function playRound(playerSelection, computerSelection) {
if(playerSelection === computerSelection) {
return 'It is a tie';
}
if(playerSelection === 'rock') {
if(computerSelection === 'scissors') {
playerScore++;
return 'Player wins with rock';
} else if(computerSelection === 'paper') {
computerScore++;
return 'Computer wins with paper'
}
}
if(playerSelection === 'paper') {
if(computerSelection === 'rock') {
playerScore++;
return 'Player wins with paper';
} else if(computerSelection === 'scissors') {
computerScore++;
return 'Computer wins with scissors';
}
}
if(playerSelection === 'scissors') {
if(computerSelection === "paper") {
playerScore++;
return 'Player wins with scissors';
} else if(computerSelection === 'rock') {
computerScore++;
return 'Computer wins with rock';
}
}
}
// game
function game() {
for(var i = 1; i <= 5; i++) {
let playerSelection = playerPlay();
let computerSelection = computerPlay();
console.log(`[Play turn ${i}] Player: ${playerSelection} | Computer: ${computerSelection}`);
playRound(i);
}
}
game();

Your code has a few issues.
You don't display output of next games. They are played but result is the same. It's same game configuration repeated 5 times.
console.log('repeat 5 times');
console.log(playRound(playerSelection, computerSelection));
Instead of:
console.log('repeat 5 times');
console.log(playRound(playerSelection, computerSelection));
You run functions playerSelection, computerSelection only once. So every next play has the same result.
You should execute these functions with every loop iteration.
Example:
let playerSelection = function () {
const input = prompt('Please enter input');
const option = input.toLowerCase();
return option;
};
let computerSelection = function () {
const option = ['rock', 'paper', 'scissors'];
let random = Math.floor(Math.random() * 3);
return option[random];
};
[...]
playRound(playerSelection(), computerSelection());

Related

How to set the result in a loop. Building the game: rock, paper, scissors

I am working on a game of rock, paper, scissors in the course "The Odin Project." Unfortunately, I've been at a standstill for several days because I can't figure out how to set the outcome of the duel. I am uploading my code below. I am a beginner so please understand :) I would appreciate your help.
const choice = ['rock', 'paper', 'scissors']
function getComputerChoice() {
const computerPlay = choice[Math.floor(Math.random() * choice.length)]
return computerPlay
}
function playRound(playerSelection, computerSelection) {
let YouLose = `You lose ${computerSelection} beats ${playerSelection.toLowerCase()}!`
let YouWin = `You win ${playerSelection.toLowerCase()} beats ${computerSelection}!`
if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'paper') {
return YouLose
score ++
} else if (playerSelection.toLowerCase() === 'paper' && computerSelection === 'rock') {
return YouWin
}
else if (playerSelection.toLowerCase() === 'paper' && computerSelection === 'scissors') {
return YouLose
}
else if (playerSelection.toLowerCase() === 'scissors' && computerSelection === 'paper') {
return YouWin
} else if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'scissors') {
return YouLose
}
else if (playerSelection.toLowerCase() === 'scissors' && computerSelection === 'rock') {
return YouLose
}else if(playerSelection.toLowerCase() === computerSelection) {
return "Tie!"
} else {
return "Error"
}
}
// function checkWinner() {
// if (playRound(playerSelection, computerSelection) === YouWin) {
// playerScore++;
// }else if (playRound(playerSelection, computerSelection) === YouLose) {
// computerScore++;
// }
// }
function game() {
console.log("Let's play the game!");
let playerScore = 0
let computerScore = 0
for (let i = 0; i < 5; i++) {
const playerSelection = prompt('What do you choose, rock, scissors or paper?')
const computerSelection = getComputerChoice()
playRound(playerSelection, computerSelection)
if (playRound(playerSelection.toLowerCase(), computerSelection) === YouWin) {
playerScore++;
}else if (playRound(playerSelection.toLowerCase(), computerSelection) === YouLose) {
computerScore++;
}
console.log(playRound(playerSelection, computerSelection));
console.log('-------------------');
console.log(playerScore);
console.log(computerScore);
}
}
console.log(game());
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js"></script>
<title>Document</title>
</head>
<body>
<script>
// function computerPlay() {
// let game = ['rock', 'paper' , 'scissors'];
// let randomPlay = Math.floor(Math.random()*game.length);
// return game[randomPlay]
// }
// let player = 0
// let computer = 0
// let round = 0
// function playRound(playerSelection, computerSelection) {
// if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'paper') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// } else if (playerSelection.toLowerCase() === 'paper' && computerSelection === 'rock') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// }
// else if (playerSelection.toLowerCase() === 'paper' && computerSelection === 'scissors') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// }
// else if (playerSelection.toLowerCase() === 'scissors' && computerSelection === 'paper') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// } else if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'scissors') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// }
// else if (playerSelection.toLowerCase() === 'scissors' && computerSelection === 'rock') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// } else if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'rock') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// } else if (playerSelection.toLowerCase() === 'paper' && computerSelection === 'paper') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// } else if (playerSelection.toLowerCase() === 'scissors' && computerSelection === 'scissors') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// } else {
// return "Erorr"
// }
// console.log(computer);
// }
// function game () {
// for (let i = 0; i < 5; i++) {
// playerSelection = prompt('What do you choose, rock, scissors or paper?');
// computerSelection = computerPlay();
// console.log(playRound(playerSelection, computerSelection));
// }
// }
// // console.log(computerSelection);
// // console.log(playerSelection);
// console.log(game());
</script>
</body>
</html>
https://github.com/RadekLewandowski/rock-paper-scissors/blob/6f60d9721a3f7e7835e5e9254cb26fcb766bedc2/script.js
i just fixed your ideas:
const choice = ['rock', 'paper', 'scissors']
function getComputerChoice() {
const computerPlay = choice[Math.floor(Math.random() * choice.length)]
return computerPlay
}
function playRound(playerSelection, computerSelection) {
if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'paper') {
return 'YouLose'
score ++
} else if (playerSelection.toLowerCase() === 'paper' && computerSelection === 'rock') {
return 'YouWin'
}
else if (playerSelection.toLowerCase() === 'paper' && computerSelection === 'scissors') {
return 'YouLose'
}
else if (playerSelection.toLowerCase() === 'scissors' && computerSelection === 'paper') {
return 'YouWin'
} else if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'scissors') {
return 'YouLose'
}
else if (playerSelection.toLowerCase() === 'scissors' && computerSelection === 'rock') {
return 'YouLose'
}else if(playerSelection.toLowerCase() === computerSelection) {
return "Tie!"
} else {
return "Error"
}
}
function game() {
console.log("Let's play the game!");
let playerScore = 0
let computerScore = 0
for (let i = 0; i < 5; i++) {
const playerSelection = prompt('What do you choose, rock, scissors or paper?')
const computerSelection = getComputerChoice()
const outcome = playRound(playerSelection, computerSelection)
if (outcome === 'YouWin')
{
alert(`You win ${playerSelection.toLowerCase()} beats ${computerSelection}!`)
playerScore++;
}
else if (outcome === 'YouLose')
{
computerScore++;
alert(`You lose ${computerSelection} beats ${playerSelection.toLowerCase()}!`)
}
console.log(playRound(playerSelection, computerSelection));
console.log('-------------------');
console.log(playerScore);
console.log(computerScore);
}
}
console.log(game());
Applied lots of fixes, simplified the code which determines whether you win or lose and ended up with this:
const choice = ['rock', 'paper', 'scissors']
function getComputerChoice() {
const computerPlay = choice[Math.floor(Math.random() * choice.length)]
return computerPlay
}
let YouLose;
let YouWin;
function playRound(playerSelection, computerSelection) {
YouLose = `You lose ${computerSelection} beats ${playerSelection.toLowerCase()}!`;
YouWin = `You win ${playerSelection.toLowerCase()} beats ${computerSelection}!`;
let diff = ((choice.indexOf(playerSelection.toLowerCase()) - choice.indexOf(computerSelection.toLowerCase())) + 3) % 3;
switch (diff) {
case 1: return YouWin;
case 2: return YouLose;
default: return "Tie!";
}
}
// function checkWinner() {
// if (playRound(playerSelection, computerSelection) === YouWin) {
// playerScore++;
// }else if (playRound(playerSelection, computerSelection) === YouLose) {
// computerScore++;
// }
// }
function game() {
console.log("Let's play the game!");
let playerScore = 0
let computerScore = 0
function round(index) {
let playerSelection = prompt('What do you choose, rock, scissors or paper?');
while (choice.indexOf(playerSelection ? playerSelection.toLowerCase() : "") < 0) {
playerSelection = prompt('Invalid choice. What do you choose, rock, scissors or paper?');
}
const computerSelection = getComputerChoice();
let result = playRound(playerSelection.toLowerCase(), computerSelection.toLowerCase());
if (result === YouWin) {
playerScore++;
}else if (result === YouLose) {
computerScore++;
}
alert(result);
console.log('-------------------');
console.log('Player: ' + playerScore);
console.log('Computer: ' + computerScore);
setTimeout(function() {
round(index + 1);
}, 1000);
}
round(0);
}
console.log(game());

Rock, Paper, Scissors: Scores remain at 0 on the first round

As you can tell by my messy code, I am still a beginner at JavaScript so I'm really sorry If this will hurt your eyes.
I am working on this Rock, Paper, Scissors project from The Odin Project where we would add a simple UI to it by applying DOM Methods. To be honest, I really don't know if I'm doing this right. I feel like the if statements shouldn't be inside the event listener but this is the only way I have found to make the tallying of scores work. By putting the code here I made it playable, but not quite right:
let playerScore = 0;
let computerScore = 0;
let scores = document.createElement('p');
let body = document.querySelector('body');
const results = document.createElement('div');
body.appendChild(results);
const buttons = document.querySelectorAll('button');
buttons.forEach((button) => {
button.addEventListener('click', () => {
let playerSelection = button.className;
let computerSelection = computerPlay();
let roundResult = playRound(playerSelection, computerSelection);
console.log(roundResult);
score();
gameEnd();
if (roundResult === 'playerWin') {
playerScore++;
} else if (roundResult === 'computerWin') {
computerScore++;
}
})
})
//computer pick
function computerPlay() {
const pick = ['rock', 'paper', 'scissors'];
return pick[Math.floor(Math.random() * pick.length)];
}
// Round Play
function playRound(playerSelection, computerSelection) {
//message that specifies the winner
let tie = `It's a tie you both picked ${playerSelection}`;
let playerWin = `You win this round! ${playerSelection} beats ${computerSelection}`;
let computerWin = `You lose this round! ${computerSelection} beats
${playerSelection}`;
if(playerSelection === computerSelection) {
results.innerHTML = tie;
return 'tie';
} else if (playerSelection === 'rock' && computerSelection === 'scisors') {
results.innerHTML = playerWin;
return 'playerWin';
} else if (playerSelection === 'paper' && computerSelection === 'rock') {
results.innerHTML = playerWin;
return 'playerWin';
} else if (playerSelection === 'scissors' && computerSelection === 'paper') {
results.innerHTML = playerWin;
return 'playerWin';
} else {
results.innerHTML = computerWin;
return 'computerWin';
}
}
function score() {
//new element where score would be seen
scores.innerHTML = `player: ${playerScore} | computer: ${computerScore}`;
body.appendChild(scores);
}
function gameEnd() {
if(playerScore === 5 || computerScore === 5) {
document.querySelector('.rock').disabled = true;
document.querySelector('.paper').disabled = true;
document.querySelector('.scissors').disabled = true;
if (playerScore > computerScore) {
alert('You win the game');
} else if (computerScore > playerScore) {
alert('Aww you lose');
}
}
}
<button class="rock">Rock</button>
<button class="paper">Paper</button>
<button class="scissors">Scissors</button>
Here's the problem, scores remain both at 0 after the first round. It would show who the winner is but it won't tally its score until I have picked for the next round. Where exactly did I go wrong with this one? (feels like in everything I'm genuinely sorry if my explanation sounds as confusing as my code.)
Anyways this is what the initial code looks like, before applying the DOM Methods.
I was initially trying to use this code but I cant even tally the scores with this one because I can't seem to get the return value of of the function playRound().
function computerPlay() {
const pick = ['rock', 'paper', 'scissors'];
return pick[Math.floor(Math.random() * pick.length)];
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
alert(`It's a tie! you both picked ${playerSelection}`);
return "tie";
} else if (playerSelection !== "rock" && playerSelection !== "paper" &&
playerSelection !== "scissors"){
alert(`You sure about using ${playerSelection} on a game of "Rock, Paper,
Scissors"?`)
} else if (playerSelection === "rock" && computerSelection === "scissors") {
alert(`You win this round! ${playerSelection} beats ${computerSelection}`);
return "playerWin";
} else if (playerSelection === "paper" && computerSelection === "rock") {
alert(`You win this round! ${playerSelection} beats ${computerSelection}`);
return "playerWin";
} else if (playerSelection === "scissors" && computerSelection === "paper") {
alert(`You win this! ${playerSelection} beats ${computerSelection}`);
return "playerWin";
} else {
alert(`You lose this round! ${computerSelection} beats ${playerSelection}`);
return "botWin";
}
}
const computerSelection = computerPlay();
// to loop the game until 5 rounds
function game() {
let playerScore = 0;
let botScore = 0;
let gameWinner = '';
for (let i = 0; i < 5; i++) {
let playerSelection = prompt(`Round ${i+1}: Choose among "Rock, Paper, Scissors"
as your weapon`).toLowerCase();
let roundResult = playRound(playerSelection, computerPlay());
if (roundResult === "playerWin" ) {
playerScore++;
} else if (roundResult === "botWin" ) {
botScore++;
}
}
if (playerScore > botScore) {
gameWinner = 'You win!';
} else if (botScore > playerScore) {
gameWinner = 'You lose, Computer wins!';
} else {
gameWinner = 'Draw';
}
alert(`Player: ${playerScore} | Bot: ${botScore}`);
if (gameWinner === 'Draw') {
alert("There is no match winner, draw!");
} else {
alert(`${gameWinner}`);
}
}
game();
between these codes which is more likely to be fixed? or would it be better to completely throw this code and just start anew?
The problem is in this part of the code:
score();
gameEnd();
if (roundResult === 'playerWin') {
playerScore++;
} else if (roundResult === 'computerWin') {
computerScore++;
}
score() will update the score in the HTML page, but at that moment the scores have not been updated yet. That only happens later in that if ... else if block.
So the solution is to first update the score, and then to call score():
score();
gameEnd();
if (roundResult === 'playerWin') {
playerScore++;
} else if (roundResult === 'computerWin') {
computerScore++;
}
There is another issue related to this: at the end of the game (when a player reaches 5 points), gameEnd() will call alert. But alert does not allow the page to actually display the latest changes. Instead it blocks any update to it. I would display the game-over message in an HTML element instead of in an alert, just like you already do for the scores. Alternatively, you could delay the execution of alert with a timer, but I would just avoid using alert.
Here is what you can do in the function gameEnd where you currently use alert:
if (playerScore > computerScore) {
results.innerHTML += '<p><b>You win the game</b>';
} else if (computerScore > playerScore) {
results.innerHTML += '<p><b>Aww you lose</b>';
}

Rock Paper Scissors help (JavaScript)

Currently working on TOP rock paper scissors game and I'm having some trouble. The function playRound is showing up as undefined in the console. I'm not sure why as all my other function are working. Maybe i did something wrong in the other functions but I'm not sure. I feel like I'm so close yet so far from this thing working. Maybe it's just common beginner mistakes not sure. Any help would be appreciated.
function computerPlay() {
var pickRandom = ["Rock", "Paper", "Scissors"];
var randomMove = pickRandom[Math.floor(Math.random() * 3)];
if (randomMove == "Rock") {
randomMove.value = 0;
} else if (randomMove == "Paper") {
randomMove.value = 1;
} else if (randomMove == "Scissors") {
randomMove.value = 2;
}
return randomMove;
}
console.log(computerPlay());
var playerSelection = prompt("pick rock paper or scissors");
function userPlay() {
if (playerSelection == "rock") {
playerSelection.value = 0;
} else if (playerSelection == "paper") {
playerSelection.value = 1;
} else if (playerSelection == "scissors") {
playerSelection.value = 2;
}
return playerSelection;
}
console.log(userPlay());
function playRound(playerPick, computerSelection) {
if (playerPick == 0 && computerSelection == 2) {
alert("you win!!!");
} else if (playerPick == 0 && computerSelection == 1) {
alert("you lose hahahahaha!!!");
} else if (playerPick == computerSelection) {
alert("its a tie");
}
}
const playerPick = userPlay();
const computerSelection = computerPlay();
console.log(playRound(playerPick, computerSelection));
You shouldn't run it in console.log, as it doesn't have a return keyword, so it will return undefined. Just run it normally and it will be fine.
You are close. I cleaned it up a bit, added a function that maps variants of human input to a normalized value, and replaced the (incomplete) conditions in playRound with an object that captures all of the win conditions in an object (see beats)...
function normalizePlay(play) {
const variants = { r: 'rock', rock: 'rock', p: 'paper', paper: 'paper', s: 'scissors', scissors: 'scissors' };
return variants [play.toLowerCase()];
}
function computerPlay() {
var pickRandom = ["rock", "paper", "scissors"];
return pickRandom[Math.floor(Math.random() * 3)];
}
function playRound(human, computer) {
const beats = { rock: 'scissors', scissors: 'paper', paper: 'rock' }
let result;
if (human === computer) {
result = 'tie';
}
else if (beats[human] === computer) {
result = 'you win';
}
else result = 'computer wins';
console.log(`you picked ${human}, computer picked ${computer}... ${result}`)
}
const human = normalizePlay(prompt("pick rock paper or scissors (or r, p, s)"));
const computer = computerPlay();
playRound(human, computer);
function computerPlay() {
var pickRandom = ["Rock", "Paper", "Scissors"];
var randomMove = pickRandom[Math.floor(Math.random() * 3)];
if (randomMove == "Rock") {
return 0;
} else if (randomMove == "Paper") {
return 1;
} else if (randomMove == "Scissors") {
return 2;
}
}
var playerSelection = prompt("pick Rock, Paper or Scissors");
function userPlay() {
if (playerSelection == "Rock") {
return 0;
} else if (playerSelection == "Paper") {
return 1;
} else if (playerSelection == "Scissors") {
return 2;
}
}
function playRound(playerPick, computerSelection) {
console.log("player", playerPick)
console.log("computerSelection", computerSelection)
if (playerPick == 0 && computerSelection == 2) {
console.log("you win!!!");
} else if (playerPick == 0 && computerSelection == 1) {
console.log("you lose hahahahaha!!!");
} else if (playerPick == computerSelection) {
console.log("its a tie");
}
}
const playerPick = userPlay();
const computerSelection = computerPlay();
playRound(playerPick, computerSelection);
You you just needed to return the numbers from computerPlay and userPlay. Also, be careful with case sensitivity when using the prompt.

How to call a function inside of another function multiple times

I am creating a rock paper scissors game where I have a playRound() function. I am trying to create a game() function where I can call this playRound() function multiple times with different results.
I want to use this game() function to play multiple rounds in order to find a winner
but I am still stuck on getting the playRound() to run multiple times.
With my current code, the playRound() function only runs once in the console.
Here is my code :
function playRound(playerSelection, computerSelection) {
const lose = "You Lose! Paper beats rock";
const win = "You Win! rock beats paper";
const tie = "its a tie";
console.log(`Your selection is : ${playerSelection}`);
console.log(`PC selection is : ${computerSelection}`);
if (playerSelection === playerSelection && computerSelection === "paper") {
return lose;
} else if (
playerSelection === playerSelection &&
computerSelection === "scissors"
) {
return win;
} else {
return tie;
}
}
function game() {
for (let i = 0; i < 3; i++) {
return playRound(playerSelection, computerSelection);
}
}
function computerPlay() {
let choices = ["rock", "paper", "scissors"];
let choice = choices[Math.floor(Math.random() * choices.length)];
return choice;
}
const string = "ROck";
const playerSelection = string.toLowerCase() || string.toUpperCase();
const computerSelection = computerPlay();
console.log(game());
Not only is your game() function returning the results of the round thus leaving the loop... but you are setting the computerSelection only once... before calling the game() function.. so neither playerSelection or computerSelection ever changes.
I rearranged your code a bit and added an overall game score. Take a look.
function playRound(playerSelection, round) {
console.log("Round " + round);
const computerSelection = computerPlay();
console.log(`Your selection is : ${playerSelection}`);
console.log(`PC selection is : ${computerSelection}`);
if (playerSelection === playerSelection && computerSelection === "paper") {
return 'lose';
} else if (
playerSelection === playerSelection &&
computerSelection === "scissors"
) {
return 'win';
} else {
return 'tie';
}
}
function game() {
const lose = "You Lose! Paper beats rock";
const win = "You Win! Rock beats scissors";
const tie = "It's a tie";
let playerScore = 0;
let computerScore = 0;
for (let i = 1; i < 4; i++) {
const result = playRound(playerSelection, i);
switch (result) {
case 'win':
console.log(win);
playerScore++;
break;
case 'lose':
console.log(lose);
computerScore++;
break;
default:
console.log(tie);
playerScore++;
computerScore++;
break;
}
}
console.log("Final Results: Player: " + playerScore + " Computer: " + computerScore);
if (playerScore > computerScore) {
console.log("You win the game!");
} else if (playerScore < computerScore) {
console.log("You lose the game.");
} else {
console.log("The game was an overall tie.");
}
}
function computerPlay() {
let choices = ["rock", "paper", "scissors"];
let choice = choices[Math.floor(Math.random() * choices.length)];
return choice;
}
const playerSelection = "rock";
game();

How do I make my function game loop so that it updates the user and computer scores?

I am looping this rock paper scissors game 5 times, if user wins they get 1 if computer wins they get 1 and so on. How do i update the user and computer score? and if it ends up being a tie how do i make it so no one gets a point?
// Computer makes a choice
function computerPlay() {
let compchoice = ['Rock', 'Paper', 'Scissors'];
return compchoice[Math.floor(Math.random() * compchoice.length)];
}
//Plays a single round Player vs Computer
function playRound(playerSelection, computerSelection) {
//Player
if (playerSelection === 'Rock' && computerSelection === 'Scissors')
{
return 'You chose ' + playerSelection + ',' + ' You win!';
} else if (playerSelection === 'Paper' && computerSelection ===
'Rock') {
return 'You chose ' + playerSelection + ',' + ' You win!';
} else if (playerSelection === 'Scissors' && computerSelection ===
'Paper') {
return 'You chose ' + playerSelection + ',' + ' You win!';
}
// Computer
else if (computerSelection === 'Rock' && playerSelection ===
'Scissors') {
return 'Computer chose ' + computerSelection + ',' + 'Computer
wins!';
} else if (computerSelection === 'Paper' && playerSelection ===
'Rock') {
return 'Computer chose ' + computerSelection + ',' + 'Computer
wins!';
} else if (computerSelection === 'Scissors' && playerSelection ===
'Paper') {
return 'Computer chose ' + computerSelection + ',' + ' Computer
wins!';
} else if (computerSelection === playerSelection) {
return 'Its a draw!';
} else {
return 'Please chose Rock, Paper, or Scissors';
}
}
//loops game 5 times to decide a winner.
function game() {
for(var i=0;i<5;i++){
let playerSelection = prompt("Rock, Paper, Scissors");
const computerSelection = computerPlay()
console.log(playRound(playerSelection, computerSelection))
console.log("your score = " + userScore);
console.log("Computer's score = " + computerScore);
}
}
let userScore =0;
let computerScore =0;
console.log(game());
I think this is what you're trying to achieve. You just need to keep track of the scores while your loop (i.e: game) iterates. I modified playRound to return an array - the first element is signifies whether the player beat the computer in the round & the second is the message that you were originally console.loging in the function:
// Computer makes a choice
function computerPlay() {
let compchoice = ['Rock', 'Paper', 'Scissors'];
return compchoice[Math.floor(Math.random() * compchoice.length)];
}
//Plays a single round Player vs Computer
function playRound(playerSelection, computerSelection) {
let playerWinsRound = false;
let text;
//Player
if (playerSelection === 'Rock' && computerSelection === 'Scissors') {
playerWinsRound = true;
text = 'You chose ' + playerSelection + ',' + ' You win!';
} else if (playerSelection === 'Paper' && computerSelection ===
'Rock') {
playerWinsRound = true;
text = 'You chose ' + playerSelection + ',' + ' You win!';
} else if (playerSelection === 'Scissors' && computerSelection ===
'Paper') {
playerWinsRound = true;
text = 'You chose ' + playerSelection + ',' + ' You win!';
}
// Computer
else if (computerSelection === 'Rock' && playerSelection ===
'Scissors') {
text = 'Computer chose ' + computerSelection + ', Computer wins!';
} else if (computerSelection === 'Paper' && playerSelection ===
'Rock') {
text = 'Computer chose ' + computerSelection + ', Computer wins!';
} else if (computerSelection === 'Scissors' && playerSelection ===
'Paper') {
text = 'Computer chose ' + computerSelection + ', Computer wins!';
} else if (computerSelection === playerSelection) {
playerWinsRound = null;
text = 'Its a draw!';
} else {
text = 'Please chose Rock, Paper, or Scissors';
}
return [playerWinsRound, text];
}
//loops game 5 times to decide a winner.
function game() {
//Score is part of the game - so move the score vars inside the game function
let userScore = 0;
let computerScore = 0;
//Update the scores on each iteration of the loop (i.e.: each round)
for (var i = 0; i < 5; i++) {
const playerSelection = prompt("Rock, Paper, Scissors");
const computerSelection = computerPlay();
const [playerWinsRound, text] = playRound(playerSelection, computerSelection)
if (playerWinsRound) {
userScore += 1;
} else {
if (playerWinsRound === false) {
computerScore += 1;
}
}
console.log(text);
console.log(`Your score = ${userScore}`);
console.log(`Computer score = ${computerScore}`);
}
}
game();

Categories