This is my first post to the forum with any code so my apologies if my format is wrong. Still trying to learn how the forums work but I am stuck. I have tried to Google some answers as well as search for some help on the forums but no luck. I may have missed an article or I may not have searched with the correct wording.
I finished the Rock, Paper, Scissors game and decided I wanted to try and add a couple features to it. The first was to take a users input. This all works fine but if I enter a word that is not expected I get âundefinedâ instead of the error message. It also shows me the computers answer. Not sure what I am missing there. It looks as though my if/else statement is correct to me but something is not working the way I expected it to.
Also, I canât seem to get the program to ask to play the game more than once. It works fine for one round through and then it just ends on the second try. This has me stumped.
Any input would be greatly appreciated including code formatting if that is way out of line.
Thank you.
const readline = require(âreadline-syncâ);
console.log(âWelcome to Rock, Paper, Scissorsâ);
function start() {
console.log(âPlease choose, Rock, Paper, or Scissorsâ);
const getUserChoice = userInput => {
userInput = readline.question();
userInput = userInput.toLowerCase();
if (userInput === ârockâ || userInput === âpaperâ ||
userInput === âscissorsâ || userInput === âbombâ) {
return userInput;
} else {
console.log(âError, please select rock, paper or scissorsâ);
}
};
const getComputerChoice = () => {
const randomNumber = Math.floor(Math.random() * 3);
switch (randomNumber) {
case 0:
return (ârockâ);
case 1:
return (âpaperâ);
case 2:
return (âscissorsâ);
}
};
const determineWinner = (userChoice, computerChoice) => {
if (userChoice === computerChoice) {
return âThis game is a tieâ;
}
if (userChoice === ârockâ) {
if (computerChoice === âpaperâ) {
return âSorry, the computer has won!â;
} else {
return âCongratulations, you won!â;
}
}
if (userChoice === 'paper') {
if (computerChoice === 'scissors') {
return 'Sorry, the computer has won!';
} else {
return 'Congratulations, you won!';
}
}
if (userChoice === 'scissors') {
if (computerChoice === 'rock') {
return 'Sorry, the computer has won!';
} else {
return 'Congratulations, you won!';
}
}
if (userChoice === 'bomb') {
return 'Congratulations, you won!';
}
};
const playGame = () => {
const userChoice = getUserChoice();
const computerChoice = getComputerChoice();
console.log('You threw: â + userChoice);
console.log('The computer threw: â + computerChoice);
console.log(determineWinner(userChoice, computerChoice));
};
playGame();
}
start();
console.log(âWould you like to play again? y/nâ);
let response = readline.question();
if (response !== ânâ) {
start();
}