I have written a rock, paper, scissor game using javascript. I have got it to play 5 rounds and to keep track of the score every round. However, for some reason every now and then it will add 2 points to the score instead of 1. I am a beginner to javascript and have no idea where I am going wrong. I keep logically going through my loop and don't understand why it does this. How can I stop this from happening?
Help would be greatly appreciated!
let playerScore = 0;
let compScore = 0;
let draw;
/* Players Choice */
function round() {
let userInput = prompt('Rock, Paper, or Scissor?: ');
console.log(userInput);
if (userInput == 'rock'){
console.log(userInput = 1);
} else if (userInput == 'paper'){
console.log(userInput = 2);
} else if (userInput == 'scissor'){
console.log(userInput = 3);
}
/* Computers Choice */
let compMove = Math.floor(Math.random()*3) + 1;
console.log(compMove);
if (compMove == 1) {
alert('Rock!');
} else if (compMove == 2){
alert('Paper!');
} else if (compMove == 3){
alert('Scissor!');
}
return {
compMove,
userInput
};
};
/* Compare */
function result(compMove, userInput) {
if (compMove == 2 && userInput == 1) {
alert('You lose!');
compScore += 1;
} else if (compMove == 3 && userInput == 1){
alert('You Win!');
playerScore += 1;
} else if (compMove == 1 && userInput == 2){
alert('You Win!');
playerScore += 1;
} else if (compMove == 1 && userInput == 3){
alert('You Lose!')
compScore += 1;
} else if (compMove == userInput){
compScore;
playerScore;
}
return {
compScore,
playerScore
};
}
function game() {
for (let i=1; i <= 5; i++) {
let roundNumber = round();
result(roundNumber.compMove, roundNumber.userInput);
console.log(result(compScore, playerScore));
};
return {
compScore,
playerScore
};
};
console.log(game());
if (playerScore > compScore) {
alert('You Won the Best of 5!');
} else if (playerScore < compScore) {
alert('You Lost.')
} else {
alert('It is a Draw!');
}
You have made calls to result() twice in game(). Store the result() in a
const and put that in console.log.
Also, in the result function, you haven't really covered all the possibilities of outcomes by computer and the user. You should cover the cases where userInput is 2 and compMove is 3, also where userInput is 3 and compMove is 2.
Related
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 = ``
}
}
I am building a rock, paper, scissors project which is supposed to take 5 rounds. The user will get a prompt and input either "rock", "paper", or "scissors". When I write the code like this:
let playerSelection = prompt("Rock, paper ou scissors?").toLowerCase();
let game = function() {
for (let i = 0; i < 5; i++) {
compare(playerSelection, computerPlay);
if (compare === "You win!") {
playerScore++;
}
else if (compare === "You lose!") {
computerScore++;
}
else if (compare === "It's a tie!") {
}
}
}
The prompt is prompted and I get to input something, however it only happens once and the loop doesn't work. When I put the prompt inside the loop, like this:
let game = function() {
for (let i = 0; i < 5; i++) {
let playerSelection = prompt("Rock, paper ou scissors?").toLowerCase();
compare(playerSelection, computerPlay);
if (compare === "You win!") {
playerScore++;
}
else if (compare === "You lose!") {
computerScore++;
}
else if (compare === "It's a tie!") {
}
}
}
The prompt never shows up!
How can I solve this and make it prompt 5 times?
Well you are not calling the function.
use
game();
after function definition
I think there is some error in your compare function. checkout the snippet below its working fine.
const compare = function(playerSelection, computerPlay) {
// write your logic here
return "You win!";
}
let game = function() {
for (let i = 0; i < 5; i++) {
let playerSelection = prompt("Rock, paper ou scissors?").toLowerCase();
const outputs = ["rock", "paper", "scissor"];
compare(playerSelection, Math.floor(Math.random()*3));
if (compare === "You win!") {
playerScore++;
}
else if (compare === "You lose!") {
computerScore++;
}
else if (compare === "It's a tie!") {
}
}
}
game();
I've been having this issue for several hours and I thought it's finally time to ask for some help. The issue is that my winning counts won't increment according to the winner declared on every of the 5 rounds.
I'm sorry if my code is messy or over complicated.
// The initial variable declarations including the user's pre-picked input/
let computerChoice;
let userChoice = 'paper';
// The function picks a random number that will change the computerChoice variable's value
function computerPlay() {
computerChoice = Math.floor(Math.random() * 3);
switch (computerChoice) {
case 0:
computerChoice = 'rock';
break;
case 1:
computerChoice = 'paper';
break;
case 2:
computerChoice = 'scissors';
break;
}
}
// The function will pick a round winner
function userPlay(userChoice) {
return userChoice.toLowerCase();
}
function playRound() {
computerPlay();
if ((computerChoice === 'rock' && userChoice === 'scissors') || (computerChoice === 'paper' && userChoice === 'rock') || (computerChoice === 'scissors' && userChoice === 'paper')) {
return `You lost! Computer chose ${computerChoice}.`
} else if (computerChoice === userChoice) {
return `It's a tie! Computer chose ${computerChoice}.`
} else {
return `You won! Computer chose ${computerChoice}.`
}
}
// The function will pick a winner of 5 rounds *not working*
function game() {
let userWinnerCount = 0;
let computerWinnerCount = 0;
let ties = 0;
for (let i = 0; i < 5; i++) {
console.log(playRound());
if (playRound() === `You won! Computer chose ${computerChoice}.`) {
userWinnerCount += 1
} else if (playRound() === `You lost! Computer chose ${computerChoice}.`) {
computerWinnerCount += 1
} else {
ties += 1
}
}
console.log(`${userWinnerCount} - times the user won / ${computerWinnerCount} - times the computer won / ${ties} - Ties`);
}
game()
So as a practice, I made a guess game in JavaScript where you have to guess the randomly generated number between 1 and 10 in three tries. It worked fine, but when the three tries are completed (or the user guesses the number), it starts all over again. I want it to stop when the above given circumstances are met.
Here is the code:
function runGame() {
var isPlaying = true;
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying = true) {
runGame();
}
A few things:
Put isPlaying variable global. Although you can remove it entirely as well. You already have a while loop condition that does the same thing.
Remove the equal sign when comparing your tries to zero. Otherwise it will run still when the tries reached zero.
Use a break statement when the user guessed the right answer, otherwise it will still run after guessing.
Other than those your code is fine. Here's the final code:
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries > 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
break;
}
tries--;
}
}
runGame();
= in JavaScript is used for assigning values to a variable. == in JavaScript is used for comparing two variables.
So change isPlaying = true to isPlaying == true and it will be fine.
while (tries >= 0) here you can use just while (tries > 0)
You can also declare these variables outside of the function but it's not necessary.
var isPlaying = true;
var tries = 3;
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying == true) {
runGame();
}
Remove the isPlaying and call runGame() directly, not in a while loop, You can break the execution if chances gets done and rest tries if the user wins
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
if (tries == 0) {
alert("You have finished your chances");
break;
}
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
} else if (guess < num) {
alert("Too low!");
} else {
alert("Exactly! " + num + " it is! You've won!");
// reset tries back to three
tries = 3;
}
tries--;
}
}
runGame();
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
}