storing value of a looped function into a variable , javascript - javascript

Hey all i need your help. In this rock paper scissor game the winner is the first to get to five wins between the user and computer. Although i have not looped this yet, i need help storing the counts of each win into a variable from my points() function into var playerPoints = 0 ; or
var compPoints = 0 ; depending on who wins the round. if you have loop suggestions feel free to advice me on that as well! thanks
//decalring an array with weapons of choice
const weaponArray = ["rock", "paper", "scissors"];
// selects a random index from array to represent computer choice
const computerChoice = weaponArray[[Math.floor(Math.random() * weaponArray.length)]];
//prompts user to make a choice of weapon
const playerPrompt = prompt("Please enter Rock, Paper, or Scissors!");
//lowers all alphabet input to lower case
const playerChoice = playerPrompt.toLowerCase();
//function runs player vs computer choices and determines winner of round
const round = (computerChoice, playerChoice) => {
if (playerChoice === "scissors" && computerChoice === "rock" || playerChoice === "rock" && computerChoice === "paper" || playerChoice ==="paper" && computerChoice === "scissors") {
return "Just Give Up Now Looser!";
}
else if (playerChoice === "rock" && computerChoice === "scissors" || playerChoice === "paper" && computerChoice === "rock" || playerChoice==="scissors" && computerChoice === "paper")
{
return "You Won This Round!";
}
else {
return "Its a Tie!";
}
};
//stores round function value into a variable
var state = round(computerChoice, playerChoice);
// adds points to player or computer based on "state" value
const points = () => {
if (state === "You Won This Round!"){
return playerPoints + 1;
}
else if (state === "Just Give Up Now Looser!"){
return compPoints + 1;
}
else{
return null
}
};
var playerPoints = points() ;
var compPoints = points() ;
console.log(state);
console.log(points());
//console.log(compPoints);
//console.log(playerPoints);

Might as well add my answer here. I wouldn't use a prompt approach, but buttons instead. Store the scores in an object and use a conditional to check if someone has reached five points after each game:
const userScore = document.querySelector('.user .score')
const computerScore = document.querySelector('.computer .score')
const resultContainer = document.querySelector('.result')
const userThrowContainer = document.querySelector('.userThrow')
const opponentThrowContainer = document.querySelector('.opponentThrow')
const buttons = document.querySelectorAll('button')
const score = {
user: 0,
computer: 0
}
function rpsMatch(userThrow) {
// Define possible throws
const throwOptions = [
'rock',
'paper',
'scissors'
]
// Choose randomly from array of throws
let opponentThrow = throwOptions[Math.floor(Math.random() * throwOptions.length)]
// Print user and computer throws
userThrowContainer.innerText = `You threw ${userThrow}`
opponentThrowContainer.innerText = `Computer threw ${opponentThrow}`
function userWins() {
resultContainer.innerText = 'You win'
score.user++
updateScores()
}
function computerWins() {
resultContainer.innerText = 'You lose'
score.computer++
updateScores()
}
function updateScores() {
userScore.innerText = score.user
computerScore.innerText = score.computer
}
function resetScore() {
userScore.innerText = 0
computerScore.innerText = 0
score.user = 0
score.computer = 0
}
// RPS logic
if (userThrow == opponentThrow) {
resultContainer.innerText = 'You tied'
} else {
if (userThrow == 'rock') {
opponentThrow == 'scissors' ? userWins() : computerWins()
} else if (userThrow == 'paper') {
opponentThrow == 'rock' ? userWins() : computerWins()
} else {
opponentThrow == 'paper' ? userWins() : computerWins()
}
}
if (score.user === 5) {
alert('You won the first to 5!')
resetScore()
}
if (score.computer === 5) {
alert('You lost the first to 5!')
resetScore()
}
}
// Attach event handlers to each button
buttons.forEach(button => {
button.addEventListener('click', e => {
// Assign data attribute to variable
let userThrow = e.target.dataset.type
e.preventDefault()
// Pass user selection to rpsMatch
rpsMatch(userThrow)
})
})
<div class="user">User Score: <span class="score">0</span></div>
<div class="computer">Computer Score: <span class="score">0</span></div>
<button data-type="rock">Rock</button>
<button data-type="paper">Paper</button>
<button data-type="scissors">Scissors</button>
<div class="userThrow"></div>
<div class="opponentThrow"></div>
<div class="result"></div>

I would not use prompt but HTML buttons to get the user's input. That way they don't have to type, just click.
Here is how you could do it:
//declaring an array with weapon of choice
const weaponArray = ["rock", "paper", "scissors"];
const players = ["tie", "you", "computer"];
const points = [0, 0, 0]; // tie, player, computer
const human = document.querySelector('#human');
const computer = document.querySelector('#computer');
const winner = document.querySelector('#winner');
const humanScore = document.querySelector('#humanScore');
const computerScore = document.querySelector('#computerScore');
// Respond to input
document.querySelector("#buttons").onclick = function(e) {
const playerChoice = +e.target.value; // 0, 1 or 2
human.textContent = weaponArray[playerChoice];
// selects a random index from array to represent computer choice
const computerChoice = Math.floor(Math.random() * weaponArray.length); // 0, 1 or 2
computer.textContent = weaponArray[computerChoice];
// Determine result
const result = (playerChoice + 3 - computerChoice) % 3; // 0 = tie, 1 = player win, 2 = computer win
winner.textContent = players[result];
// add point to the relevant winner. Winner 0 represents the ties - they don't really count
points[result]++;
humanScore.textContent = points[1];
computerScore.textContent = points[2];
if (result && points[result] >= 5) {
alert("Game over. " + players[result] + " won");
location.reload();
}
}
Please make your choice:<br>
<div id="buttons">
<button value="0">rock</button> <button value="1">paper</button> <button value="2">scissors</button><br>
</div>
Your weapon: <span id="human"></span><br>
Computer's weapon: <span id="computer"></span><br>
Winner: <span id="winner"></span><br>
Your score: <span id="humanScore"></span><br>
Computer's score: <span id="computerScore"></span><br>

Related

How to design/redesign a JavaScript function to end and reset the rock paper scissors game after 9 rounds? The current function not working correctly

The following code is the totality of a version of paper rock scissors. The function: limitGameToBestOutOfNine () is only working some of the time. There are instances where the user or computer score increments above 9 wins. How do I fix this? Thanks in advance.
Code:
/*variable statements follow*/
const computerChoiceDisplay = document.getElementById('computer-choice');
const buttons = document.getElementsByClassName('control');
const userChoiceDisplay = document.getElementById('player-choice');
const resultDisplay = document.getElementById('result');
const possibleChoices = document.getElementsByClassName('control');
const resultOutput = document.getElementById('result-output');
const playerImage = document.getElementById('player-image');
const computerImage = document.getElementById('computer-image');
const choices = ["rock", "paper", "scissors"];
let userChoice;
let computerChoice;
let result ;
let playerChoice ;
let score = 0;
let mistakes = 0;
let scoreContainer;
let userSpan;
let computerSpan;
let playerScore = document.getElementById("userScore");
let compScore = document.getElementById("compScore");
let resetButton = document.getElementById("resetScore");
let compChoice;
let completedRounds = 0;
/**
* This Array from statement sets event listener to the button class control array
* which listens for the user and computer choices which are fed to the getresult function
*/
Array.from(possibleChoices).forEach(possibleChoice => possibleChoice.addEventListener('click', (e) => {
userChoice = e.target.id;
resultDisplay.innerHTML = userChoice;
compChoice = generateComputerChoice();
gameImages(userChoice, computerChoice);
getResult();
}));
/**
* This adds an event listener for the reset button
*/
document.getElementById("resetScore").addEventListener("click", resetScore);
/**
* This function generates a random number for the computer and displays
* the output to the innerHTML
*/
function generateComputerChoice() {
const randomNumber = Math.floor(Math.random() * 3) + 1;
if (randomNumber === 1) {
computerChoice = 'rock';
}
if (randomNumber === 2) {
computerChoice = 'paper';
}
if (randomNumber === 3) {
computerChoice = 'scissors';
}
computerChoiceDisplay.innerHTML = computerChoice;
}
/**
* Provides the logic to determin what to do in the event that either
* the user or computer wins, as well as what to do in the even of a draw.
*/
function getResult () {
if (computerChoice === userChoice) {
result = "It's a draw!";
}
if (computerChoice === 'rock' && userChoice === 'paper') {
result = "You Win!";
incrementUserScore();
console.log("paperWin");
}
if (computerChoice === 'rock' && userChoice === 'scissors') {
result = "You lost!";
incrementComputerScore();
}
if (computerChoice === 'paper' && userChoice === 'scissors') {
result = "You Win!";
incrementUserScore();
}
if (computerChoice === 'paper' && userChoice === 'rock') {
result = "You lost!";
incrementComputerScore();
}
if (computerChoice === 'scissors' && userChoice === 'rock') {
result = "You win!";
incrementUserScore();
}
if (computerChoice === 'scissors' && userChoice === 'paper') {
result = "You lost!";
incrementComputerScore();
}
resultOutput.innerHTML = result;
toggleBackgroundColor()
}
/**
* This function allows for the dynamic change of images based on user or
* computer choices.
*/
function gameImages(playerChoice, computerChoice) {
console.log(playerChoice, computerChoice);
playerImage.src = `assets/images/${playerChoice}.jpg`;
playerImage.alt = choices [userChoice];
computerImage.src = `assets/images/${computerChoice}.jpg`;
computerImage.alt = choices[computerChoice];
}
/**
* Gets the user score from the DOM and increments it by 1
*/
function incrementUserScore() {
console.log("incrementing");
// playerScore = playerScore++
score++;
playerScore.innerHTML = score;
console.log(playerScore);
completeRound()
}
/**
* Gets the computer score from the DOM and increments it by 1
*/
function incrementComputerScore() {
mistakes++;
compScore.innerHTML = mistakes;
console.log(compScore);
completeRound()
}
/**
* This function provides the logic used to reset the user and
* computer score back to zero, upon the user request.
*/
function resetScore() {
score = 0;
mistakes = 0;
playerScore.innerHTML = score;
compScore.innerHTML = mistakes;
}
/**
* This function is to limit the amount of playable paper, rock, and scissors game to best out of 9
*/
function limitGameToBestOutOfNine () {
// Check who has the higher score
if (score > mistakes) {
console.log('Player has won the game!');
alert('Player has won the game!');
} else if (mistakes > score) {
console.log('Computer has won the game!');
alert('Computer has won the game!');
} else {
console.log('It\'s a tie!');
alert('It\'s a tie!');
}
// Reset the scores
score = 0;
mistakes = 0;
}
function completeRound() {
// increment a completed round
completedRounds++;
console.log("Completed Rounds: " + completedRounds)
if (completedRounds == 10) {
limitGameToBestOutOfNine()
}
}
/***
* This function toggles the background color of the .player .computer class
* based on the winner of the current game. The winner color is green and the loser color is red
*/
function toggleBackgroundColor() {
const player = document.getElementById('player');
const computer = document.getElementById('computer');
const winner = resultOutput.innerHTML.toLowerCase();
console.log(winner)
if (winner.includes('you win')) {
console.log('win')
player.style.backgroundColor = "#00FF00";
computer.style.backgroundColor = "#FF0000";
}
else if (winner.includes('you lost')) {
console.log('lose')
player.style.backgroundColor = "#FF0000";
computer.style.backgroundColor = "#00FF00";
}
else {
console.log('draw')
player.style.backgroundColor = "#00FF00";
computer.style.backgroundColor = "#00FF00";
}
}
I have reviewed the code and do not know what the issue is. The problem started happening after I added the toggleBackgroundColor() function.

How I make my function in a rock, pepper, scissors game wait for a button press in Javascript?

So I have this code(I added the whole JS code but the part I want help is in the function game) that simply runs 5 rounds of a game of rock, papper, scissors with a press of a button in my html file.
The thing is that each round I want the function to wait for a button click of any of the three buttons (rock, papper or scissors)
I will appriciate any help, thank you and have a nice day!
let rock = "Rock";
let papper = "Papper";
let scissors = "Scissors";
let wins = 0;
let playerSelection;
const btnrock = document.getElementById('btn1');
const btnpapper = document.getElementById('btn2');
const btnscissors = document.getElementById('btn3');
const btnplay = document.getElementById('game')
function getPlayerChoice() {
btnrock.addEventListener('click', () => {
playerSelection = rock;
return playerSelection;
});
btnpapper.addEventListener('click', () => {
playerSelection = papper;
return playerSelection;
});
btnscissors.addEventListener('click', () => {
playerSelection = scissors;
return playerSelection;
});
}
btnplay.addEventListener('click', game)
function getComputerChoice() {
let min = Math.ceil(0);
let max = Math.floor(2);
let random = Math.floor(Math.random() * (max - min + 1) + min);
if (random == 0)
{
return rock;
}
if (random == 1){
return papper;
}
if (random == 2){
return scissors;
}
}
function playRound(playerSelection,pcChoice) {
if(pcChoice == rock && playerSelection == papper) {
wins++;
return "Player Wins!";
}
else if (pcChoice == rock && playerSelection == scissors) {
return "Player Loses!"
}
else if (pcChoice == scissors && playerSelection == rock){ wins++; return "Player Wins!"}
else if (pcChoice == scissors && playerSelection == papper){return "Player Loses!"}
else if (pcChoice == papper && playerSelection == rock){return "Player Loses!"}
else if (pcChoice == papper && playerSelection == scissors){wins++; return "Player Wins!"}
else {return "It's a Draw!"}
}
function game() {
for(let i = 0; i < 5; i++){
const pcChoice = getComputerChoice();
playerSelection = getPlayerChoice(); // I want this to wait
console.log("PC "+ pcChoice );
console.log('Player '+playerSelection);
let roundwinner = playRound(playerSelection,pcChoice);
console.log(roundwinner);
if(i === 2 && wins == 0){
break;
}
if(i === 3 && wins <= 1) {
break;
}
if(wins==3){
break;
}
}
if(wins >= 3) {
console.log("You are the winner of this match")
}
else {console.log('You lost the game');}
}
getPlayerChoice doesn't really get the player's choice - it adds event listeners. Run it 5 times and you get 5 listeners hooked up to the same event. I don't think you can wait for an event to fire in a loop like you're currently trying to. This would be a perfectly fine design in a console app when you want some input from the user, but in JS when working with events you have to leverage the events to execute your game's logic.
In other words, you might want to get rid of the for loop and consider moving that logic to event chain with a listener that first adds the user's input to the board and then executes the follow logic - e.g. gets the computer choice or determines whether the game is finished or not.

How do you display a counter variable inside a div?

Im building rock/paper/scissors where user plays against computer. I want to update the score after each round and display it inside a div. The code works after the 1st score, but never increments after 1.
let computerPlay = () => {
let compChoices = ["rock", "paper", "scissors"]; //array storing computer possible actions
let i = Math.floor(Math.random() * 3);
let choice = compChoices[i];
return choice;
};
//select buttons for player choice
let buttons = document.querySelectorAll(".btn");
//select elements for updating scoreboard
let homeScore = document.querySelector(".home-score");
let awayScore = document.querySelector(".away-score");
let display = document.querySelector(".score-board-display");
//declare player and computer score variables
let playerScore, compScore;
//compare player and computer selections update score of winner
let playRound = (playerSelection, computerSelection) => {
let result = ``;
playerScore = 0;
compScore = 0;
if (playerSelection === computerSelection) {
result = `Tie ${playerSelection} equals ${computerSelection}`;
} else if (
(playerSelection == "rock" && computerSelection == "scissors") ||
(playerSelection == "paper" && computerSelection == "rock") ||
(playerSelection == "scissors" && computerSelection == "paper")
) {
result = `LFG!! ${playerSelection} beats ${computerSelection}`;
playerScore += 1;
homeScore.innerText = playerScore.toLocaleString();
} else {
result = `You Lose! ${computerSelection} beats ${playerSelection}`;
}
return (display.innerHTML = result);
};
buttons.forEach((button) => {
button.addEventListener("click", () => {
let computerSelection = computerPlay();
let playerSelection = button.innerHTML.toLowerCase();
playRound(playerSelection, computerSelection);
});
});
on every playRound the playerScore is reseted / defined as 0
to solve that define playerScore as number before your playRound definition
...
let playerScore=0;
let playRound = (playerSelection, computerSelection) => {
...

Rock Paper Scissors game returns same result

So I'm having some difficulty with my code (hence the post). I'm trying to make it so where when you click on the picture of the rock, the game begins and it returns the computer's decision. It worked before when I prompted the user but since I've rewritten the logic when I click on the rock, it only returns one answer. Is it because of the lack of loops? I assumed each time I would click on the icon, a different answer would display. I haven't done the code for the other options yet because I figured I would use similar logic for the other options. The only thing I can think of is that because I'm not using a loop, the game basically plays only 1 round.
const rock = document.querySelector('.rock');
const paper = document.querySelector('.paper');
const scissors = document.querySelector('.scissors');
const h3 = document.querySelector('h3');
let computerScore = 0;
let playerScore = 0;
function computerPlay() {
var choice = Math.floor(Math.random() * 3 ) + 1; //generate a number 1-3 to find computer choice
if(choice == 1) {
return 'rock';
}
else if(choice == 2) {
return 'paper';
}
else {
return 'scissors'
}
}
// function playGame(computerChoice) {
// // let round = 0
// // while(round < 6) {
// var playerChoice = playerRock || playerPaper || playerScissors;
// var computerChoice = computerPlay();
// if(playerChoice === computerChoice) {
// console.log('Tie!');
// round++;
// }
// else if(playerChoice == 'rock' && computerChoice == 'scissors') {
// playerScore++;
// console.log(`Player chose rock and computer chose scissors! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// round++;
// }
// else if(playerChoice == 'paper' && computerChoice == 'rock') {
// playerScore++;
// round++;
// console.log(`Player chose paper and computer chose rock! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// }
// else if(playerChoice == 'scissors' && computerChoice == 'paper') {
// playerScore++;
// round++;
// console.log(`Player chose scissors and computer chose paper! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// }
// else {
// computerScore++;
// console.log(`The player chose ${playerChoice} and the computer chose ${computerChoice}! The computer wins! Player: ${playerScore} Computer: ${computerScore}.`)
// }
// // }
// }
// computerPlay()
// playerChoice()
// console.log(playGame())
function playGame(computerChoice) {
computerChoice = computerPlay();
let result;
rock.addEventListener('click', () => {
if(computerChoice == 'rock') {
result = `The computer chose ${computerChoice} and you chose rock! It's a tie!`;
h3.textContent = result;
}
else if(computerChoice == 'paper') {
result = `The computer chose ${computerChoice} and you chose rock! You lose!`;
h3.textContent = result;
computerScore++;
}
else {
result = `The computer chose ${computerChoice} and you chose rock! You win!`;
h3.textContent = result;
playerScore++;
}
});
let playerPaper = paper.addEventListener('click', () => {
return 'paper'
});
let playerScissors = scissors.addEventListener('click', () => {
return 'scissors'
})
}
playGame()
console.log(playGame())
This is what I have so far. Initially, I didn't have a result variable but I thought that might help.
When calling playGame() once, computerChoice is only generated once. Everytime you click on rock paper or scissor it evaluates the players choice, but the computers choice has never changed. If it chooses rock at the beginning it will always compare the users choice to rock.
Either take the eventListeners out of the playGame function and call playGame after the result is shown (Recursive-style loop)
Or, after the result is shown reset computerChoice to the result of another computerPlay() call. You can add computerChoice = computerPlay() to the end of your event listener function after the else statement to run regardless of the outcome.
You need to do some changes ...
1- add event at first time
add useChoicevariable
and show reult of game on click
const rock = document.querySelector('.rock');
const paper = document.querySelector('.paper');
const scissors = document.querySelector('.scissors');
const h3 = document.querySelector('h3');
let computerScore = 0;
let playerScore = 0;
let computerChoice = "";
let userChoice = "";
rock.addEventListener('click', () => {
userChoice = "rock";
ShowResult()
});
paper.addEventListener('click', () => {
userChoice = 'paper';
ShowResult()
});
scissors.addEventListener('click', () => {
userChoice = 'scissors';
ShowResult()
})
function computerPlay() {
var choice = Math.floor(Math.random() * 3) + 1; //generate a number 1-3 to find computer choice
if (choice == 1) {
return 'rock';
}
else if (choice == 2) {
return 'paper';
}
else {
return 'scissors'
}
}
// function playGame(computerChoice) {
// // let round = 0
// // while(round < 6) {
// var playerChoice = playerRock || playerPaper || playerScissors;
// var computerChoice = computerPlay();
// if(playerChoice === computerChoice) {
// console.log('Tie!');
// round++;
// }
// else if(playerChoice == 'rock' && computerChoice == 'scissors') {
// playerScore++;
// console.log(`Player chose rock and computer chose scissors! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// round++;
// }
// else if(playerChoice == 'paper' && computerChoice == 'rock') {
// playerScore++;
// round++;
// console.log(`Player chose paper and computer chose rock! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// }
// else if(playerChoice == 'scissors' && computerChoice == 'paper') {
// playerScore++;
// round++;
// console.log(`Player chose scissors and computer chose paper! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// }
// else {
// computerScore++;
// console.log(`The player chose ${playerChoice} and the computer chose ${computerChoice}! The computer wins! Player: ${playerScore} Computer: ${computerScore}.`)
// }
// // }
// }
// computerPlay()
// playerChoice()
// console.log(playGame())
function ShowResult() {
if (computerChoice == userChoice) {
result = `The computer chose ${computerChoice} and you chose ${userChoice}! It's a tie!`;
h3.textContent = result;
} else if (
computerChoice == 'paper' && userChoice == "rock"
|| computerChoice == 'scissors' && userChoice == "paper"
|| computerChoice == 'rock' && userChoice == "scissors"
) {
result = `The computer chose ${computerChoice} and you chose ${userChoice}! You lose!`;
h3.textContent = result;
computerScore++;
} else {
result = `The computer chose ${computerChoice} and you chose ${userChoice}! You win!`;
playerScore++;
h3.textContent = result + playerScore ;
}
playGame()
}
function playGame() {
computerChoice = computerPlay();
console.log( "Computer Choice:" + computerChoice);
}
playGame()
<div class="rock">rock</div>
<div class="paper">paper</div>
<div class="scissors">scissors</div>
<h3></h3>

Why does my function always return the same value?

Newly learning Javascript, so I'm learning to store functions in objects. Currently creating a simple rock,paper, scissors game. I'm stuck, where I need the getWinner function to determine the winner and added 3 conditions to the function = draw, win or lose. Now the problem is, it always returns draw to me. Can anyone help?
const startGameBtn = document.getElementById('start-game-btn');
let ROCK = "ROCK";
let PAPER = "PAPER";
let SCISSORS = "SCISSORS";
let RESULT_DRAW = "It's a draw";
let RESULT_PLAYER_WINS = "Player Wins";
let RESULT_COMPUTER_WINS = "Player Wins";
let GAME_IS_RUNNING = false;
let getPlayerChoice = function () {
let selection = prompt(`${ROCK},${PAPER}, or ${SCISSORS}? `, '').toUpperCase();
if (selection !== ROCK &&
selection !== PAPER &&
selection !== SCISSORS) {
alert ("Invalid choice, defaulted to Rock");
selection = ROCK;
}
return selection
}
const getComputerChoice = function() {
const randomValue = Math.floor(Math.random() * 2);
if (randomValue === 0) {
return ROCK;
} else if (randomValue === 1) {
return PAPER;
} else if (randomValue === 2) {
return SCISSORS;
};
}
const getWinner = function (cChoice, pChoice) {
if (cChoice === pChoice) {
return RESULT_DRAW;
} else if (cChoice === ROCK && pChoice === PAPER ||
cChoice === PAPER && pChoice === SCISSORS ||
cChoice === SCISSORS && pChoice === ROCK
) {
return RESULT_PLAYER_WINS;
} else {
return RESULT_COMPUTER_WINS;
}
}
startGameBtn.addEventListener('click', function () {
if (GAME_IS_RUNNING) {
return
}
GAME_IS_RUNNING = true;
console.log("Game is starting....");
let playerChoice = getPlayerChoice();
console.log(playerChoice);
let computerChoice = getComputerChoice();
console.log(computerChoice);
let winner = getWinner(computerChoice, playerChoice);
console.log(winner);
});
<button id="start-game-btn">Start</button>
Fixing only the problem that the computer can never choose SCISSORS, it runs and works. Maybe you just had a lucky run of draws.
const startGameBtn = document.getElementById('start-game-btn');
let ROCK = "ROCK";
let PAPER = "PAPER";
let SCISSORS = "SCISSORS";
let RESULT_DRAW = "It's a draw";
let RESULT_PLAYER_WINS = "Player Wins";
let RESULT_COMPUTER_WINS = "Player Wins";
let GAME_IS_RUNNING = false;
let getPlayerChoice = function() {
let selection = prompt(`${ROCK},${PAPER}, or ${SCISSORS}? `, '').toUpperCase();
if (selection !== ROCK &&
selection !== PAPER &&
selection !== SCISSORS) {
alert("Invalid choice, defaulted to Rock");
selection = ROCK;
}
return selection
}
const getComputerChoice = function() {
const randomValue = Math.floor(Math.random() * 3); // <----
if (randomValue === 0) {
return ROCK;
} else if (randomValue === 1) {
return PAPER;
} else if (randomValue === 2) {
return SCISSORS;
};
}
const getWinner = function(cChoice, pChoice) {
if (cChoice === pChoice) {
return RESULT_DRAW;
} else if (cChoice === ROCK && pChoice === PAPER ||
cChoice === PAPER && pChoice === SCISSORS ||
cChoice === SCISSORS && pChoice === ROCK
) {
return RESULT_PLAYER_WINS;
} else {
return RESULT_COMPUTER_WINS;
}
}
startGameBtn.addEventListener('click', function() {
if (GAME_IS_RUNNING) {
return
}
GAME_IS_RUNNING = true;
console.log("Game is starting....");
let playerChoice = getPlayerChoice();
console.log(playerChoice);
let computerChoice = getComputerChoice();
console.log(computerChoice);
let winner = getWinner(computerChoice, playerChoice);
console.log(winner);
});
<button id="start-game-btn">START-STOP</button>

Categories

Resources