Having completed the course, I’ve revisited some of the freeform exercises and looking at how I could use learnings to improve (maybe?) the implementation.
My revised code for https://www.codecademy.com/courses/introduction-to-javascript/projects/rock-paper-scissors-javascript is below.
If anyone has time, I’d like some critical feedback on it.
const availableInputs = ['rock', 'paper', 'scissors'];
const tiedGame = 'The game is tied';
const userWin = 'Congratulations, you won!';
const computerWin = 'Sorry, you lost!';
const invalidUserInputError = `You must select one of:${availableInputs.map(input => `\n- ${input}`)}`
function getUserChoice(userInput) {
userInput = userInput.toLowerCase();
if (availableInputs.includes(userInput) || userInput === 'bomb') {
return userInput;
} else {
console.log(invalidUserInputError)
}
};
function getComputerChoice() {
let computerChoice = Math.floor(Math.random() * 3);
return availableInputs[computerChoice];
};
function determineWinner(userChoice, computerChoice) {
if (userChoice === 'bomb') {
return userWin;
} else if (userChoice === computerChoice) {
return tiedGame
} else {
switch(userChoice) {
case 'rock':
return computerChoice === 'paper' ? computerWin : userWin;
break;
case 'paper':
return computerChoice === 'scissors' ? computerWin : userWin;
break;
case 'scissors':
return computerChoice === 'rock' ? computerWin : userWin;
break;
}
}
}
function playGame(userChoice) {
let outcome = determineWinner(getUserChoice(userChoice), getComputerChoice())
console.log(outcome);
}
let times = 30
while (times > 0) {
playGame('Rock');
times--;
}