Check for the Winner
Learn how to check for the winner of the game.
We'll cover the following...
What have we got?
We have collected all the data required to play the game. This is our inventory of already created functions:
// Function to display game instructionsfunction displayInstructions(){console.log('Welcome to Rock Paper Scissors.\n');console.log('The rules are simple:');console.log('1. Rock beats scissors');console.log('2. Scissors beat paper');console.log('3. Paper beats rock');}// Function to ask for the number of roundsfunction getRounds(){let rounds;do {rounds = prompt('How many rounds would you like to play? \nRounds: ');rounds = parseInt(rounds);if (isNaN(rounds) || rounds <= 0) {console.log('Please enter a valid positive integer for rounds.');}} while (isNaN(rounds) || rounds <= 0);return rounds;}// Function to get the player's choicefunction getPlayerChoice(){const validChoices = ['rock', 'paper', 'scissors'];let playerChoice;do {playerChoice = prompt('Please enter rock, paper, or scissors. \nChoice: ').toLowerCase();if (!validChoices.includes(playerChoice)) {console.log('Invalid choice. Please enter either rock, paper, or scissors.');}} while (!validChoices.includes(playerChoice));return playerChoice;}// Function to get the computer’s choicefunction getComputerChoice(){const options = ['rock', 'paper', 'scissors'];const computerChoice = options[Math.floor(Math.random() * options.length)];console.log('Computer chooses', computerChoice);return computerChoice;}// Function to contain the flow of the whole programfunction main() {displayInstructions();const rounds = getRounds();const playerChoice = getPlayerChoice();const computerChoice = getComputerChoice();}
Inventory of created functions
Considering our code so far, we still lack the ability to ...