lundi 8 juin 2020

Javascript If Else boolean component not functioning as expected [closed]

This is my first stackoverflow question as a new programmer, so I hope I'm not asking anything awfully dumb. I am building a rock, paper, scissors game and this piece of code should do two things:

  • return text indicating the winner
  • assign "humanIsWinner" variable with a boolean value.

the return statements are working, but the boolean is not and I can't figure out why. I've been testing it and I see that in the first "else if", "if" section, humanIsWinner evaluates to true even though I assign it false. Somehow my assigning is not sticking.

This is the specific part that I'm referring to:

let humanIsWinner;
const compareChoices = (humanChoice, computerChoice) => {

  if (humanChoice === computerChoice) {
    return "tie game!"
  } else if (humanChoice === "rock") {
    if (computerChoice === "paper") {
      humanIsWinner === false;
      console.log(humanIsWinner);
      return "paper covers rock. You lose :("
    }

The console.log(humanIsWinner) returns 'true' even though just above it, I assign 'false'. Can someone please help me here? Thank you!

Below is the full code for this section.

let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;
let humanIsWinner;
const compareChoices = (humanChoice, computerChoice) => {

  if (humanChoice === computerChoice) {
    return "tie game!"
  } else if (humanChoice === "rock") {
    if (computerChoice === "paper") {
      humanIsWinner === false;
      return "paper covers rock. You lose :("
    } else if (computerChoice === "scissors") {
      humanIsWinner === true;
      return "rock crushes scissors! You win :)"
    }
  } else if (humanChoice === "paper") {
    if (computerChoice === "rock") {
      humanIsWinner === true;
      return "paper covers rock! You win :)"
    } else if (computerChoice == "scissors") {
      humanIsWinner === false;
      return "scissors cut paper. You lose :("
    }
  } else if (humanChoice === "scissors") {
    if (computerChoice === "rock") {
      humanIsWinner === false;
      return "rock crushes scissors. You lose :("
    } else if (computerChoice === "paper") {
      humanIsWinner === true;
      return "scissors cut paper! You win :)"
    } else {
      return "something went wrong -___-"
    }
  }
};

const updateScore = () => {
  if (humanIsWinner = true) {
    humanScore++;
  } else if (humanIsWinner = false) {
    computerScore++;
  } else if (humanIsWinner = undefined) {
    console.log("its a tie")
  }
};



const advanceRound = () => currentRoundNumber++;

//test zone
humanChoice = "rock";
computerChoice = "paper";
console.log(compareChoices(humanChoice, computerChoice));
updateScore();
console.log("is human the winner?", humanIsWinner);
console.log(humanScore, computerScore);

Aucun commentaire:

Enregistrer un commentaire