jeudi 12 août 2021

if else statement failing in a paper-rock-scissors challenge

I'm a complete beginner in Javascript and coding in general.
I'm trying to make a simple command-line javascript paper-rock-scissors game but I keep getting a bug. I've created a function for the computer to randomly pick paper, rock or scissors and getting the user's selection from a prompt. To get the result I've written an if else statement that will show an alert with the outcome but regardless the input it always shows a tie. It seems that the code always ends up on the else part of the statement and I can't figure out why. Can someone help me with what's wrong with the statement and why it skips to else?

function computerPlay() {
  let computerChoices = ["paper", "rock", "scissors"];
  let computerChoice = computerChoices[Math.floor(Math.random() * computerChoices.length)];
  return computerChoice;
}

function playRound(computerSelection, playerSelection) {
  if (computerSelection === "rock" && playerSelection.toLowerCase() === "paper") {
    alert("You win, paper beats rock!")
  } else if (computerSelection === "paper" && playerSelection.toLowerCase() === "scissors") {
    alert("You win, scissors beat paper!")
  } else if (computerSelection === "scissors" && playerSelection.toLowerCase() === "rock") {
    alert("You win, rock beat scissors")
  } else if (computerSelection === "rock" && playerSelection.toLowerCase() === "scissors") {
    alert("You loose, rock beats scissors")
  } else if (computerSelection === "paper" && playerSelection.toLowerCase() === "rock") {
    alert("You loose, paper beats rock")
  } else if (computerSelection === "scissors" && playerSelection.toLowerCase() === "paper") {
    alert("You loose, scissors beats paper")
  } else {
    alert("even steven")
  }
}

for (let i = 1; i <= 5; i++) {
  computerPlay()
  const playerSelection = prompt("Please enter your choice", " ");
  const computerSelection = computerPlay();
  console.log(computerSelection);
  console.log(playerSelection);
  playRound(computerSelection, playerSelection);
}

Aucun commentaire:

Enregistrer un commentaire