Recientemente comencé a codificar y elegí aprender JavaScript como mi primer idioma. He escrito un código para un juego de piedra, papel o tijera, pero aparecen resultados incorrectos cuando lo ejecuto. por ejemplo pondría mi respuesta como tijeras y la computadora elegiría roca y el juego saldría empatado.
const getUserChoice = userInput => { if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') { return userInput } else { return 'Error!' } } var getComputerChoice = () => { const randomNumber = Math.floor(Math.random() * 3); switch (randomNumber) { case 0: return 'rock' break; case 1: return 'paper' break; case 2: return 'scissors' break; } }; const determineWinner = (userChoice, computerChoice) => { if (userChoice === computerChoice) { return 'its a tie!'; }; if (userChoice === 'rock') { if (computerChoice === 'paper') { return 'computer won'; } else { return 'user won'; } } if (userChoice === 'paper') { if (computerChoice === 'scissors') { return 'computer won'; } else { return 'user won' } } if (userChoice === 'scissors') { if (computerChoice === 'rock') { return 'computer won'; } else { return 'user won' } } }; const playGame = () => { console.log(`player chose ${getUserChoice('scissors')}`); console.log(`computer chose ${getComputerChoice()}`); console.log(determineWinner(getUserChoice("scissors"), getComputerChoice())); } playGame();Tal vez haya más problemas, pero estos son algunos de ellos:
Cada vez que ejecuta getComputerChoice obtiene un valor diferente porque se selecciona un valor aleatorio dentro:
console.log(`player chose ${getUserChoice('scissors')}`); console.log(`computer chose ${getComputerChoice()}`); console.log(determineWinner(getUserChoice("scissors"), getComputerChoice()));Entonces, en su lugar, debe llamar y almacenar en variables:
let playerChose = getUserChoice('scissors'); let computerChose = getComputerChoice(); let winner = determineWinner(playerChose, computerChose); console.log(`player chose ${playerChose}`); console.log(`computer chose ${computerChose}`); console.log(winner);Puede hacerlo sin variables, pero asegúrese de no invocar getComputerChoice varias veces.
También userInput debe estar entre paréntesis en:
const getUserChoice = (userInput) => {Cada vez que llame a getComputerChoice obtendrá un valor diferente, puede guardar los valores en una variable con la palabra clave const .
const playGame = () => { // It would be nice if you request this to the user, with prompt const userChoice = getUserChoice('scissors'); // Save the random value const computerChoice = getComputerChoice(); console.log(`player chose ${userChoice}`); console.log(`computer chose ${computerChoice}`); // This will work console.log(determineWinner(userChoice, computerChoice)); } playGame();Más información aquí