Functions Flashcards

1
Q

Create an example of a working rock, paper, scissors game using functions.

A
const getUserChoice = userInput => {
userInput = userInput.toLowerCase();

if (userInput === ‘rock’ || userInput === ‘paper’ userInput === ‘scissors’) {
return userInput;

} else {
console.log(‘Error, invalid input’);
}

};

const getComputerChoice = () => {

let randomNumber = Math.floor(Math.random() * 3);

switch (randomNumber) {
case 0:
return 'rock';
break;
case 1:
return 'paper';
break;
case 2: 'scissors':
return 'scissors';
break;
}
};
const getWinner (user, comp) => {
if (user === comp) {
return 'Tie!';
}
if (user === 'rock') {
}  if (comp === 'paper') {
return 'CPU Wins!';
} else {
return 'You Win!';

}

if (user === 'paper') {
} if (comp === 'rock') {
return 'You win!';
} else {
return 'CPU Wins!';
}
if (user === 'scissors') {
} if (comp === 'rock') {
return 'CPU Wins!';
} else {
return 'You win!';
}

};

const playGame => {
let user = getUserChoice('rock');
let comp = getComputerChoice();

if (user !== ‘rock’ && user !== ‘paper’ && user !== ‘scissors’) {
console.log(‘Game won’t proceed’);
return;
}

console. log(‘You threw ‘ + user + ‘, computer threw ‘ + comp);
console. log(getWinner(user, comp));

};
playGame();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly