0

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!

4
  • 1
    validInput = array.indexOf(selection); at this point, your array variable is still [] becuase computerPlay() (that sets the array values) is called after playerSelection() Commented Apr 22, 2018 at 22:49
  • also your while loop in playerSelection will not loop at all (it runs only once even if selection is wrong again), because array.includes() returns boolean value and you compare it to -1. Commented Apr 22, 2018 at 23:04
  • I totally get it now @user3743266 I just populated my array variable at the beginning and the problem is gone, thank you great wise man. Commented Apr 22, 2018 at 23:30
  • I was testing with includes() and indexfOf() it happened that I forgot to change back to indexfOf() before posting, thank you @rsm Commented Apr 22, 2018 at 23:32

1 Answer 1

0

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think you are right @Schien. Title is already changed. I also implemented some changes in my script based on you suggestions, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.