jeudi 4 mars 2021

Evaluate if statements in javascript

So I'm following the modern JavaScript from the beginning by brad traversy, and in the guess number project the app ignores all the conditions in the first if statement and continue. I checked the code in the project file and it's the same, I tried switch statement, I put each condition in a separate if statement, and still doesn't work

let min = 1,
  max = 10,
  winningGuess = 2,
  guessesNum = 3;

// Grab on UI Elements 

const game = document.querySelector('#game'),
  minNum = document.querySelector('.min-num'),
  maxNum = document.querySelector('.max-num'),
  guessInput = document.querySelector('#guess-input'),
  guessBtn = document.querySelector('#guess-btn'),
  message = document.querySelector('.message');

// Assign UI to min and Max

minNum.textContent = min;
maxNum.textContent = max;

// Add an EventListener
guessBtn.addEventListener('click', function() {

  let guess = parseInt(guessInput.value);
  if (isNaN(guess) || guess < min || guess > max) {
    setMessage(`Please enter a Number between ${min} and ${max}`);
  }

  if (guess === winningGuess) {

    gameOver(true, `Great Job ${winningGuess} is the Correct guess, You Won!`)

  } else {

    guessesNum -= 1;

    if (guessesNum === 0) {

      gameOver(false, `Sorry you lost, The correct guess was ${winningGuess}`)

    } else {

      guessInput.style.borderColor = 'red';

      setMessage(`${guess} is not the correct number, You have ${guessesNum} guesses left. Please try again`, 'red');

      guessInput = '';

    }
  }
});

function gameOver(won, msg) {

  let color;

  won === true ? color = 'green' : color = 'red';

  guessInput.disabled = true;

  guessInput.style.borderColor = color;

  message.style.color = color;

  setMessage(msg);

}

function setMessage(msg, color) {

  message.textContent = msg;
  message.style.color = color;
};
<div class="container">
  <h1>The Number Guesser Game</h1>
  <div id="game">
    <p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
    <input type="number" id="guess-input" placeholder="Enter Your Guess">
    <input type="submit" value="Submit" id="guess-btn">
    <p class="message"></p>
  </div>

</div>

Aucun commentaire:

Enregistrer un commentaire