Rock Paper Scissors -- Loop -- Javascript - javascript

I am having issues trying to make a loop. When I include a "for" loop, the game will iterate in (i) amount, for (i) is the condition of the "for" loop. How can I get the game to loop until the player/computer/tie reaches the goal of "5"?
I searched and read through multiple similar problems on this site and have tried to replicate a resolution without any success.
Any guidance is appreciated!
function gameOver() is where I THINK I did not code my thoughts correctly.
const buttons = document.querySelectorAll('.button');
let matchResults = document.querySelector('.match-results');
let winnerResults = document.querySelector('.winner-results');
let playerPoint = document.querySelector('#playerPoint');
let computerPoint = document.querySelector('#computerPoint');
let tiePoint = document.querySelector('#tiePoint');
let matchOutcome = document.querySelector('.match-outcome');
let retryBtn = document.querySelector('.retry-btn');
let running = false;
let tie = 0;
let player = 0;
let computer = 0;
startGame();
function startGame(){
buttons.forEach(button => {
button.addEventListener('click', ()=>{
playRound(button.id);
gameOver()
})
});
retryBtn.addEventListener('click', restartGame);
running = true;
};
function playRound (playerSelection) {
computerSelection = getComputerChoice();
playerSelection = playerSelection.toLowerCase();
matchResults.textContent = `You selected ${playerSelection} : Computer selected ${computerSelection}`
if (playerSelection == computerSelection){
tie = ++tie;
tiePointAdd();
winnerResults.textContent = `${playerSelection} is tied with ${computerSelection}!`
}else if (
(playerSelection == 'rock' && computerSelection == 'scissors') ||
(playerSelection == 'scissors' && computerSelection == 'paper') ||
(playerSelection == 'paper' && computerSelection == 'rock')
){
player = ++player;
playerPointAdd();
winnerResults.textContent = `${playerSelection} beats ${computerSelection}!`
}else {
computer = ++computer;
computerPointAdd();
winnerResults.textContent = `${playerSelection} loses to ${computerSelection}!`
}
}
function getComputerChoice() {
let possibleChoices = ['rock', 'paper', 'scissors']
let randomChoice = possibleChoices[Math.floor(Math.random() * possibleChoices.length)]
return randomChoice
}
function playerPointAdd(){
playerPoint.textContent = player;
}
function computerPointAdd(){
computerPoint.textContent = computer
}
function tiePointAdd(){
tiePoint.textContent = tie
}
function restartGame(){
tie = 0;
player = 0;
computer = 0;
tiePoint.textContent = 0;
playerPoint.textContent = 0;
computerPoint.textContent = 0;
matchResults.textContent = ``;
winnerResults.textContent= ``;
matchOutcome.textContent = ``;
running = true;
buttons.forEach(button => {
button.addEventListener('click', ()=>{
playRound(button.id);
gameOver()
})
})
}
function gameOver(){
let playerGame = false;
let computerGame = false;
let nanGame = false; //no one wins
for(let i = 0; i < 14; i++){
if (tie === 5){
nanGame = true;
break;
}
if (player === 5){
playerGame = true;
break;
}
if (computer === 5){
computerGame = true;
break;
}
}
if (nanGame) {
matchOutcome.textContent = `Game over! Tie Game! Try Again?`
endGame()
running = false
} else if (playerGame){
matchOutcome.textContent = `Game over! You Win! Congrats!!!`
endGame()
running = false
} else if (computerGame){
matchOutcome.textContent = `Game over! You Lose! Try Again?`
endGame()
running = false
} else {
matchOutcome.textContent = ``
}
}
I am having issues trying to make a loop. When I include a "for" loop, the game will iterate in (i) amount, for (i) is the condition of the "for" loop. How can I get the game to loop until the player/computer/tie reaches the goal of "5"?

This should be able to work.
function gameOver(){
for(let i = 0; i < 14; i++){
if (tie === 5){
matchOutcome.textContent = `Game over! Tie Game! Try Again?`
endGame()
running = false
}
if (player === 5){
matchOutcome.textContent = `Game over! You Win! Congrats!!!`
endGame()
running = false
}
if (computer === 5){
matchOutcome.textContent = `Game over! You Lose! Try Again?`
endGame()
running = false
}else {
matchOutcome.textContent = ``
}
}

Related

Why is this loop executing without me clicking any button?

I am trying to build a rock paper scissors game and I’m having a hard time with loops and events in JS. When I run this script, it counts userChoice as undefined. Why is the loop not waiting till I click any button?
This is part of the oddin project: Revisiting Rock Paper Scissors - Foundations Course
// Setting the game score to 0.
let userScore = 0;
let computerScore = 0;
const rock = document.querySelector('.rock');
const paper = document.querySelector('.paper');
const scissors = document.querySelector('.scissors');
// Main game function.
function game() {
for (let i = 0; i < 5; i++) {
/* Play the game 5 rounds. */
let values = ["rock", "paper", "scissors"]; /* The possibilities the computer can choose. */
let index = Math.floor(Math.random() * values.length); /* I use the random built-in function to randomly pick a value from the array. */
function getComputerChoice() { /* Function for the computer choice. */
return values[index];
}
let computerChoice = getComputerChoice();
let userChoice
rock.addEventListener("click", function() {
userChoice = 'rock';
});
paper.addEventListener("click", function() {
userChoice = 'paper';
});
scissors.addEventListener("click", function() {
userChoice = 'scissors';
});
function roundOfGame(userChoice, computerChoice) {
if (userChoice === computerChoice) {
return ("It is a tie");
} else if ((userChoice === "rock" && computerChoice === "scissor") || (userChoice === "paper" && computerChoice == "rock") || (userChoice === "scissor" && computerChoice === "paper")) {
userScore = userScore += 1;
return (`Player wins! ${userChoice} beats ${computerChoice}. User score = ${userScore} and computer score = ${computerScore}`)
} else {
computerScore = computerScore += 1;
return (`Computer wins! ${computerChoice} beats ${userChoice}. User score = ${userScore} and computer score = ${computerScore}`)
}
}
console.log(roundOfGame(userChoice, computerChoice));
}
}
game()
It's not how you usually handle user events in JavaScript. addEventListener takes a callback instead of returning for a reason. It's a non-blocking operation and by default everything after addEventListener will run immediately
To make it work as you want you can create a function like this:
function waitForClick(options) {
return new Promise(r => {
const listeners = []
options.forEach(option => {
const waitFor = () => {
r(option.value)
listeners.forEach(listener => {
listener.element.removeEventListener('click', listener.fn)
})
}
option.element.addEventListener('click', waitFor)
listeners.push({ element: option.element, fn: waitFor })
})
})
}
and than await for it:
const userChoice = await waitForClick([{
element: rock,
value: 'rock'
},
{
element: paper,
value: 'paper'
},
{
element: scissors,
value: 'scissors'
},
])
let userScore = 0;
let computerScore = 0;
const rock = document.querySelector('.rock');
const paper = document.querySelector('.paper');
const scissors = document.querySelector('.scissors');
async function game() {
for (let i = 0; i < 5; i++) {
let values = ["rock", "paper", "scissors"];
let index = Math.floor(Math.random() * values.length);
function getComputerChoice() {
return values[index];
}
let computerChoice = getComputerChoice();
const userChoice = await waitForClick([{
element: rock,
value: 'rock'
},
{
element: paper,
value: 'paper'
},
{
element: scissors,
value: 'scissors'
},
])
console.log('player', userChoice, 'computer', computerChoice)
function roundOfGame(userChoice, computerChoice) {
if (userChoice === computerChoice) {
return ("It is a tie");
} else if ((userChoice === "rock" && computerChoice === "scissors") || (userChoice === "paper" && computerChoice == "rock") || (userChoice === "scissors" && computerChoice === "paper")) {
userScore = userScore += 1;
return (`Player wins! ${userChoice} beats ${computerChoice}. User score = ${userScore} and computer score = ${computerScore}`)
} else {
computerScore = computerScore += 1;
return (`Computer wins! ${computerChoice} beats ${userChoice}. User score = ${userScore} and computer score = ${computerScore}`)
}
}
console.log(roundOfGame(userChoice, computerChoice));
}
}
game()
function waitForClick(options) {
return new Promise(r => {
const listeners = []
options.forEach(option => {
const waitFor = () => {
r(option.value)
listeners.forEach(listener => {
listener.element.removeEventListener('click', listener.fn)
})
}
option.element.addEventListener('click', waitFor)
listeners.push({
element: option.element,
fn: waitFor
})
})
})
}
<button class="rock">rock</button>
<button class="paper">paper</button>
<button class="scissors">scissors</button>

Rock,Paper&Scissors game problem in JavaScript

Whenever I run the code , computer-Point has score 1 before the game
started . Second issue that I couldn't figure out is that how to set a
play round for 5 set. these are the JavaScript code
describe the values
set computer choices
set check-winner Function
set Player choices
set game function
````
var playerPoint = 0;
var computerPoint = 0;
const userScore_p = document.querySelector(".human > p");
const computerScore_p = document.querySelector(".machine > p");
const result_p = document.querySelector('.result > p');
const rock = document.getElementById('rock')
const paper = document.getElementById('paper');
const scissors = document.getElementById('scissors');
const playerSelection = [rock, paper, scissors]
const weapons = ["rock", "paper", "scissors"];
// set the computer random choice
function getComputerChoice(){
const choice = weapons[Math.floor(Math.random() * weapons.length)];
return choice;
}
function checkWinner(playerSelection) {
const computerSelection = getComputerChoice();
if (playerSelection == computerSelection) {
result_p.textContent = "Tie";
}
else if ((playerSelection == "rock" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "rock")) {
result_p.textContent = "player Winnnn";
playerPoint++;
userScore_p.innerHTML = playerPoint;
} else {
result_p.textContent = "Player lost!!!!";
computerPoint++;
computerScore_p.innerHTML = computerPoint;
}
console.log(computerSelection)
console.log(playerSelection);
}
function getPlayerChoice() {
rock.addEventListener("click", function () {
checkWinner("rock");
});
paper.addEventListener("click", function() {
checkWinner("paper");
});
scissors.addEventListener("click", function() {
checkWinner("scissors")
});
}
function game() {
const computerSelection = getComputerChoice();
for (let i = 0; i < 5; i++) {
if (playerPoint > computerPoint) {
result_p.innerHTML = "you won the game"
} else if (playerPoint < computerPoint) {
result_p.innerHTML = "you lose the game"
} else {
result_p.innerHTML = "Drawwww"
}
}
}
game()
checkWinner();
getPlayerChoice();
````
The problem here is, player is not going to choose a weapon until they click on 1 of the 3 buttons, so when you call the function getPlayerChoice() it actually doesn't mean the player clicked on one of those buttons.
You should process the logics inside the checkWinner() function, which is called whenever the user clicks on a button.
let playerPoint = 0;
let computerPoint = 0;
const userScore_p = document.querySelector(".human > p");
const computerScore_p = document.querySelector(".machine > p");
const result_p = document.querySelector('.result > p');
const rock = document.getElementById('rock')
const paper = document.getElementById('paper');
const scissors = document.getElementById('scissors');
const playerSelection = [rock, paper, scissors]
rock.addEventListener("click", function() {
checkWinner("rock");
});
paper.addEventListener("click", function() {
checkWinner("paper");
});
scissors.addEventListener("click", function() {
checkWinner("scissors")
});
const weapons = ["rock", "paper", "scissors"];
// set the computer random choice
function getComputerChoice() {
const choice = weapons[Math.floor(Math.random() * weapons.length)];
return choice;
}
function checkWinner(playerSelection) {
const computerSelection = getComputerChoice();
if (playerSelection == computerSelection) {
result_p.textContent = "Tie";
} else if ((playerSelection == "rock" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "rock")) {
result_p.textContent = "player Winnnn";
playerPoint++;
userScore_p.innerHTML = playerPoint;
} else {
result_p.textContent = "Player lost!!!!";
computerPoint++;
computerScore_p.innerHTML = computerPoint;
}
console.log(computerSelection)
console.log(playerSelection);
}
<button id="rock">rock</button>
<button id="paper">paper</button>
<button id="scissors">scissors</button>
<div>
HUMAN
<div class="human">
<p>0</p>
</div>
</div>
<div>
MACHINE
<div class="machine">
<p>0</p>
</div>
</div>
<div>
RESULT
<div class="result">
<p></p>
</div>
</div>

Rock, Paper, Scissors - debugging multiple round game

Kindly assist with the completion of the code. Especially with the game() function. The problems are listed below.
The computerPlay() does not change when the loop runs over, it maintains the same answer to the end of the loop.
Also, I need the game() function to be able to print out the player with the most WIN OUTPUT
WHAT MY CODE DOES
Because the outputs are the same, it is able to tell the winner after the number of rounds set.
The output is then stored in an array.
Kindly note that some of the codes are commented. You can uncomment it to help me modify it if possible or give similar solutions.
//Computer player argorithm
function computerPlay(){
let comOption = ""
const guess = Math.floor(Math.random()*10)+1;
let finalAnswer = guess % 3;
if(finalAnswer > 1){
comOption = "Rock";
}else if(finalAnswer === 1){
comOption = "Paper";
}else if(finalAnswer < 1){
comOption = "Scissors";
}
return comOption;
}
//Single round function
function playRound(computerSelection, playerSelection){
let ansDeclaration = "";
var computerWin = `Computer Win! ${computerSelection} beats ${playerSelection}`;
var noBodyWin = `Equals ${computerSelection} = ${playerSelection}`;
var youWin = `You Win! ${playerSelection} beats ${computerSelection}`;
if(playerSelection == "Scissors" && computerSelection == "Paper"){
ansDeclaration = youWin;
}else if(playerSelection =="Paper" && computerSelection == "Rock"){
ansDeclaration = youWin;
}else if(playerSelection =="Rock" && computerSelection == "Scissors"){
ansDeclaration = youWin;
}else if(computerSelection == "Paper" && playerSelection == "Rock"){
ansDeclaration = computerWin;
}else if(computerSelection == "Scissors" && playerSelection == "Paper"){
ansDeclaration = computerWin;
}else if(computerSelection == "Rock" && playerSelection == "Scissors"){
ansDeclaration = computerWin;
}else{
ansDeclaration = noBodyWin;
}
return ansDeclaration;
}
//Creating game function
function game(){
var computerWin = `Computer Win! ${computerSelection} beats ${playerSelection}`;
var noBodyWin = `Equals ${computerSelection} = ${playerSelection}`;
var youWin = `You Win! ${playerSelection} beats ${computerSelection}`;
const rounds = parseInt(prompt("Enter the number of turns you would like to play the game: "))
let outComeArr = []; //Outcome of the game in array
for(let count = 0; count < rounds; count++){
let outCome = (playRound(computerSelection, playerSelection));
outComeArr.push(outCome);
}
for(let count = 0; count < outComeArr.length; count++){
if(outComeArr[count]=== youWin){
console.log("Player Win")
}else if(outComeArr[count] === computerWin){
console.log("Computer Win")
}else if(outComeArr[count]=== noBodyWin){
console.log("Draw Round")
}
}
return outComeArr;
//The code below helps in breaking the array "outComeArray to determine the winner"
/* for(let count = 0; count < outComeArr.length; count++){
if(outComeArr[count] === youWin){
let countWin = 0;
countWin++
console.log(`Player win ${countWin} times`);
}else if(outComeArr[count]=== computerWin){
let countWin = 0;
countWin++;
console.log(`Computer Win ${countWin} times`);
}else if(outComeArr[count]=== noBodyWin){
let countWin = 0;
countWin++;
console.log(`Draw Round ${countWin} times`);
}
} */
}
const computerSelection = computerPlay();
const playerSelection = "Scissors";
console.log(game());
The problem is that you define the moves exactly once at the end of the file. You need to redefine them upon each move. I fixed the issue and also implemented player move for you.
//Computer player argorithm
function computerPlay(){
let comOption = ""
const guess = Math.floor(Math.random()*10)+1;
let finalAnswer = guess % 3;
if(finalAnswer > 1){
comOption = "Rock";
}else if(finalAnswer === 1){
comOption = "Paper";
}else if(finalAnswer < 1){
comOption = "Scissors";
}
return comOption;
}
function playerPlay() {
let move = prompt("What do you move?");
if (['Rock', 'Paper', 'Scrissors'].indexOf(move) === -1) move = 'Scrissors';
return move;
}
//Single round function
function playRound(){
computerSelection = computerPlay();
playerSelection = playerPlay();
let ansDeclaration = "";
var computerWin = `Computer Win! ${computerSelection} beats ${playerSelection}`;
var noBodyWin = `Equals ${computerSelection} = ${playerSelection}`;
var youWin = `You Win! ${playerSelection} beats ${computerSelection}`;
if(playerSelection == "Scissors" && computerSelection == "Paper"){
ansDeclaration = youWin;
}else if(playerSelection =="Paper" && computerSelection == "Rock"){
ansDeclaration = youWin;
}else if(playerSelection =="Rock" && computerSelection == "Scissors"){
ansDeclaration = youWin;
}else if(computerSelection == "Paper" && playerSelection == "Rock"){
ansDeclaration = computerWin;
}else if(computerSelection == "Scissors" && playerSelection == "Paper"){
ansDeclaration = computerWin;
}else if(computerSelection == "Rock" && playerSelection == "Scissors"){
ansDeclaration = computerWin;
}else{
ansDeclaration = noBodyWin;
}
return ansDeclaration;
}
//Creating game function
function game(){
var computerWin = `Computer Win! ${computerSelection} beats ${playerSelection}`;
var noBodyWin = `Equals ${computerSelection} = ${playerSelection}`;
var youWin = `You Win! ${playerSelection} beats ${computerSelection}`;
const rounds = parseInt(prompt("Enter the number of turns you would like to play the game: "))
let outComeArr = []; //Outcome of the game in array
for(let count = 0; count < rounds; count++){
let outCome = (playRound());
outComeArr.push(outCome);
}
for(let count = 0; count < outComeArr.length; count++){
if(outComeArr[count]=== youWin){
console.log("Player Win")
}else if(outComeArr[count] === computerWin){
console.log("Computer Win")
}else if(outComeArr[count]=== noBodyWin){
console.log("Draw Round")
}
}
return outComeArr;
//The code below helps in breaking the array "outComeArray to determine the winner"
/* for(let count = 0; count < outComeArr.length; count++){
if(outComeArr[count] === youWin){
let countWin = 0;
countWin++
console.log(`Player win ${countWin} times`);
}else if(outComeArr[count]=== computerWin){
let countWin = 0;
countWin++;
console.log(`Computer Win ${countWin} times`);
}else if(outComeArr[count]=== noBodyWin){
let countWin = 0;
countWin++;
console.log(`Draw Round ${countWin} times`);
}
} */
}
var computerSelection;
var playerSelection;
console.log(game());

How do I get my rock paper scissors game to reset after 5 wins with javascript (The Odin Project)?

I have tried making a function endGame() but I just can't figure out exactly what I need to do to reset everything back to 0. I've used result_p.innerHTML to change the message to say who has won the game after 5 points (user or computer) but the user can still continue after this and I'd like to actually have the game reset to 0-0. Any suggestions? Thanks
Code Below:
let userScore = 0;
let compScore = 0;
const userScore_span = document.getElementById("user-score");
const compScore_span = document.getElementById("comp-score");
// Get reference to scoreboard div
const scoreBoard_div = document.querySelector(".score-board");
const result_p = document.querySelector(".result > p");
const rock_div = document.getElementById("r");
const paper_div = document.getElementById("p");
const scissors_div = document.getElementById("s");
//Gets random selection from computer
function getComputerSelection() {
const choices=['r','p','s'];
const result = Math.floor(Math.random()*3);
return choices[result]
}
//Converts r,p,s to rock, paper, scissors for output on screen
function convertToWord(letter) {
if (letter === 'r') return "Rock";
if (letter === 'p') return "Paper";
return "Scissors";
}
function win(playerSelection, computerSelection) {
userScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (userScore < 5){result_p.innerHTML = `${convertToWord(playerSelection)} beats ${convertToWord(computerSelection)}. You win! =D`;
}else if(userScore === 5){result_p.innerHTML='Game over, you win! Refresh to play again'};
}
function lose(playerSelection, computerSelection) {
compScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (compScore<5){result_p.innerHTML = `${convertToWord(computerSelection)} beats ${convertToWord(playerSelection)}. You lose =(`;
}else if(compScore === 5){result_p.innerHTML='Game over, you lose! Refresh to play again'};
}
function draw() {
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_p.innerHTML = `It\'s a tie!`;
}
function game(playerSelection) {
const computerSelection = getComputerSelection();
if (playerSelection === computerSelection) {
draw(playerSelection, computerSelection);
} else if (playerSelection === 'r' && computerSelection === 's'){
win(playerSelection, computerSelection);
}else if (playerSelection === 'p' && computerSelection === 'r'){
win(playerSelection, computerSelection);
}else if (playerSelection === 's' && computerSelection === 'p'){
win(playerSelection, computerSelection);
}else{
lose(playerSelection, computerSelection);
}
}
function main() {
rock_div.addEventListener('click', () => game("r"));
paper_div.addEventListener('click', () => game("p"));
scissors_div.addEventListener('click', () => game("s"));
}
main ();
your score: <div id="user-score"></div> <br>
computer's score: <div id="comp-score"></div>
<div id="a1" class="score-board"></div>
<div id="a2" class="result"><p></p></div>
<button id="r">use rock</button>
<button id="p">use paper</button>
<button id="s">use scissor</button>
What should happen when the game ends?
show the result
show a button to play again
disable the RPS buttons so that user cannot continue to play
therefore, the code to end the game when score is already 5 is:
...
else if(userScore === 5){
// show the result & show a button to play again
result_p.innerHTML='Game over, you win! <button onclick="endGame()">Click here to play again</button>';
// disable the RPS buttons so that user cannot continue to play
rock_div.setAttribute("disabled", 1);
paper_div.setAttribute("disabled", 1);
scissors_div.setAttribute("disabled", 1);
};
...
What should happen when the game starts again?
reset both score to 0
display the new score to user
show blank result
reenable all the RPS buttons so that user can continue to play
therefore, the code to restart the game is:
function endGame() {
// reset both score to 0
userScore = 0;
compScore = 0;
// display the new score to user
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
// show blank result
result_p.innerHTML = ``;
// reenable all the RPS buttons so that user can continue to play
rock_div.removeAttribute("disabled");
paper_div.removeAttribute("disabled");
scissors_div.removeAttribute("disabled");
}
Here is working snippet
let userScore = 0;
let compScore = 0;
const userScore_span = document.getElementById("user-score");
const compScore_span = document.getElementById("comp-score");
// Get reference to scoreboard div
const scoreBoard_div = document.querySelector(".score-board");
const result_p = document.querySelector(".result > p");
const rock_div = document.getElementById("r");
const paper_div = document.getElementById("p");
const scissors_div = document.getElementById("s");
//Gets random selection from computer
function getComputerSelection() {
const choices=['r','p','s'];
const result = Math.floor(Math.random()*3);
return choices[result]
}
//Converts r,p,s to rock, paper, scissors for output on screen
function convertToWord(letter) {
if (letter === 'r') return "Rock";
if (letter === 'p') return "Paper";
return "Scissors";
}
function win(playerSelection, computerSelection) {
userScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (userScore < 5){result_p.innerHTML = `${convertToWord(playerSelection)} beats ${convertToWord(computerSelection)}. You win! =D`;
}else if(userScore === 5){
result_p.innerHTML='Game over, you win! <button onclick="endGame()">Click here to play again</button>'
rock_div.setAttribute("disabled", 1);
paper_div.setAttribute("disabled", 1);
scissors_div.setAttribute("disabled", 1);
};
}
function lose(playerSelection, computerSelection) {
compScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (compScore<5){result_p.innerHTML = `${convertToWord(computerSelection)} beats ${convertToWord(playerSelection)}. You lose =(`;
}else if(compScore === 5){
result_p.innerHTML='Game over, you lose! <button onclick="endGame()">Click here to play again</button>'
rock_div.setAttribute("disabled", 1);
paper_div.setAttribute("disabled", 1);
scissors_div.setAttribute("disabled", 1);
};
}
function draw() {
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_p.innerHTML = `It\'s a tie!`;
}
function game(playerSelection) {
const computerSelection = getComputerSelection();
if (playerSelection === computerSelection) {
draw(playerSelection, computerSelection);
} else if (playerSelection === 'r' && computerSelection === 's'){
win(playerSelection, computerSelection);
}else if (playerSelection === 'p' && computerSelection === 'r'){
win(playerSelection, computerSelection);
}else if (playerSelection === 's' && computerSelection === 'p'){
win(playerSelection, computerSelection);
}else{
lose(playerSelection, computerSelection);
}
}
function endGame() {
userScore = 0;
compScore = 0;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_p.innerHTML = ``;
rock_div.removeAttribute("disabled"); paper_div.removeAttribute("disabled"); scissors_div.removeAttribute("disabled");
}
function main() {
rock_div.addEventListener('click', () => game("r"));
paper_div.addEventListener('click', () => game("p"));
scissors_div.addEventListener('click', () => game("s"));
}
main ();
your score: <div id="user-score"></div> <br>
computer's score: <div id="comp-score"></div>
<div id="a1" class="score-board"></div>
<div id="a2" class="result"><p></p></div>
<button id="r">use rock</button>
<button id="p">use paper</button>
<button id="s">use scissor</button>
userScore = 0;
compScore = 0;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
I think this will be enough to "refresh" your game. So you should basically call this in lose and win functions when score of the winner is bigger than 5. Please note that the code can be refactored as you are repeating the same pattern in win and lose functions. Applying these changes, I added a refresh button, here is the code (again, note that I did not refactor the code):
let userScore = 0;
let compScore = 0;
const userScore_span = document.getElementById("user-score");
const compScore_span = document.getElementById("comp-score");
// Get reference to scoreboard div
const scoreBoard_div = document.querySelector(".score-board");
const result_p = document.querySelector(".result > p");
const rock_div = document.getElementById("r");
const paper_div = document.getElementById("p");
const scissors_div = document.getElementById("s");
//Gets random selection from computer
function getComputerSelection() {
const choices = ['r', 'p', 's'];
const result = Math.floor(Math.random() * 3);
return choices[result]
}
//Converts r,p,s to rock, paper, scissors for output on screen
function convertToWord(letter) {
if (letter === 'r') return "Rock";
if (letter === 'p') return "Paper";
return "Scissors";
}
function win(playerSelection, computerSelection) {
userScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (userScore < 5) {
result_p.innerHTML = `${convertToWord(playerSelection)} beats ${convertToWord(computerSelection)}. You win! =D`;
} else if (userScore === 5) {
result_p.innerHTML = 'Game over, you win! Refresh to play again'
endGame();
};
}
function lose(playerSelection, computerSelection) {
compScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (compScore < 5) {
result_p.innerHTML = `${convertToWord(computerSelection)} beats ${convertToWord(playerSelection)}. You lose =(`;
} else if (compScore === 5) {
result_p.innerHTML = 'Game over, you lose! Refresh to play again'
endGame();
};
}
function draw() {
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_p.innerHTML = `It\'s a tie!`;
}
function game(playerSelection) {
const computerSelection = getComputerSelection();
if (playerSelection === computerSelection) {
draw(playerSelection, computerSelection);
} else if (playerSelection === 'r' && computerSelection === 's') {
win(playerSelection, computerSelection);
} else if (playerSelection === 'p' && computerSelection === 'r') {
win(playerSelection, computerSelection);
} else if (playerSelection === 's' && computerSelection === 'p') {
win(playerSelection, computerSelection);
} else {
lose(playerSelection, computerSelection);
}
}
function endGame() {
rock_div.disabled = true;
paper_div.disabled = true;
scissors_div.disabled = true;
}
function restartGame() {
restartScores();
rock_div.disabled = false;
paper_div.disabled = false;
scissors_div.disabled = false;
}
function restartScores() {
userScore = 0;
compScore = 0;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
}
function main() {
rock_div.addEventListener('click', () => game("r"));
paper_div.addEventListener('click', () => game("p"));
scissors_div.addEventListener('click', () => game("s"));
}
main();
your score:
<div id="user-score"></div> <br> computer's score:
<div id="comp-score"></div>
<div id="a1" class="score-board"></div>
<div id="a2" class="result">
<p></p>
</div>
<button id="r">use rock</button>
<button id="p">use paper</button>
<button id="s">use scissor</button>
<button onclick="restartGame()">restart game</button>
Now when you win or lose, the game "stops", and the buttons used to play the game are disabled. When the user clicks the refresh button, the score refreshes and the buttons are again enabled.

Testing if the user input value is in a given array (JavaScript)

I just created a five rounds rock-paper-scissors game using vanilla JavaScript. The program runs just fine so far except for the fact every time I start the game for the very first time it will take any user input as invalid no matter what and won't count that round.
This is my code:
// Global variables
let playerWins = 0;
let computerWins = 0;
let array = [];
let validInput = 0;
let newRound = "";
// This function generates a computer selection
const computerPlay = () => {
array = ["rock", "paper", "scissors"]
return array[Math.floor(Math.random() * array.length)];
}
// This function stores player selection
const playerSelection = (selection) => {
selection = prompt("Enter: 'Rock', 'Paper' or 'Scissors'").toLowerCase();
validInput = array.indexOf(selection);
console.log(validInput);
// This loop will validate user input is correct
while (validInput === -1) {
alert("Invalid input, try again");
selection = prompt("Enter 'Rock', 'Paper' or 'Scissors'").toLowerCase();
validInput = array.includes(selection);
}
return selection;
}
// This function plays a single round of Rock-Paper-Scissors
const playRound = (playerSelection, computerPlay) => {
// If both players select the same item
if (playerSelection === computerPlay) {
return alert("It's a tie!");
}
// If player selects "Rock"
if (playerSelection === "rock") {
if (computerPlay === "scissors") {
playerWins += 1;
return alert("Rock crushes scissors: YOU WIN!!!");
} else {
computerWins += 1;
return alert("Paper covers rock: YOU LOOSE!!!");
}
}
// If player selects "Paper"
if (playerSelection === "paper") {
if (computerPlay === "rock") {
playerWins += 1;
return alert("Paper covers rock: YOU WIN!!!");
} else {
computerWins += 1;
return alert("Scissors cuts paper: YOU LOOSE!!!");
}
}
// If player selects "Scissors"
if (playerSelection === "scissors") {
if (computerPlay === "rock") {
computerWins += 1;
return alert("Rock crushes scissors: YOU LOOSE!!!");
} else {
playerWins += 1;
return alert("Scissors cuts paper: YOU WIN!!!");
}
}
}
// This function keeps score and reports a winner or loser at the end
const trackWins = (pw, cw) => {
alert("COMPUTER WINS: " + cw + "\nPLAYER WINS: " + pw)
if (pw > cw) {
alert("YOU WIN THIS ROUND, CONGRAX!!!")
} else if (cw > pw) {
alert("YOU LOOSE THIS ROUND, SO BEST LUCK FOR THE NEXT TIME :_(")
} else {
alert("IT'S A TIE")
}
}
// This function creates a 5 round game
const game = () => {
for (let i = 0; i < 5; i++) {
playRound(playerSelection(), computerPlay());
}
trackWins(playerWins, computerWins);
}
do {
game();
newRound = prompt("Do yo want to play another round? Type 'y' to continue or any other key to exit").toLowerCase();
} while (newRound === "y");
alert("It was a good game, bye for now!")
I will appreciate any ideas to fix this problem or improve my script, thank you in advance!
Your posted code can be simplified to better reflect question - say, you have an array, and a variable that stores user input. How do you test if the input value is in the array?
var arr=['Rock','Paper','Scissors'];
var inp='Rock'; //user input
You could use a while loop, but there's a much faster way:
var options={'rock':0,'paper':1,'scissors':2}
var inp='Rock'; //user input
var ninp=inp.toLowerCase().trim(); //normalize input
var pick=(options[ninp]);
if (pick==null) // invalid selection
if (pick==0) //rock
if (pick==1) //paper
if (pick==2) //scissors
The code can be further cleaned up with a switch:
switch (pick){
case 0: ... break; //rock
case 1: ... break; //paper
case 2: ... break; //scissors
default: //invalid
}

Categories