Computer’s Move
Explore how to create a JavaScript function that selects the computer's move for a Rock Paper Scissors game. Learn to use JavaScript's random functions to return one of the three options. This lesson helps you build the game's essential interaction before advancing to the game loop.
We'll cover the following...
We'll cover the following...
What have we got?
We have set up the user’s input. 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 contain the flow of the whole programfunction main() {displayInstructions();const rounds = getRounds();const playerChoice = getPlayerChoice();}
Inventory of created functions
In this task, we’ll create a function to get a move ...