Home > Back-end >  I want to increment after each guess, but it always says I am on the first try
I want to increment after each guess, but it always says I am on the first try

Time:01-01

I am attempting to make the number of tries go up by one for each incorrect guess. That number would then be shown in the alert. For some reason no matter how many attempts I do it always says one. Any tips?

function checkGuess(guess, target) {
    let correct = false;
    let numTries = 0;
        
    do {
        if (!COLORS_ARRAY.includes(guess))  {
            numTries   ;
            alert('You must select one of the colors listed. Press ok to retry.');
        } else if (guess < target) {
            numTries   ;
            alert('Incorrect. You are on try '   numTries   '.'   '\n\nAlphabetically to high');
        } else if (guess > target) {
            numTries   ;
            alert('Incorrect. You are on try '   numTries   '.'   '\n\nAlphabetically to low');
        } else {
            correct = true;
            document.body.style.background = guess;
        } 
        return correct;
    } while (!correct);
}

CodePudding user response:

numTries is a variable local to the function checkGuess, so every time you execute the function it sets numTries to 0. What you can do is create the variable outside of the checkGuess function.

let numTries = 0;

function checkGuess(guess, target) {
let correct = false;
  
if (!COLORS_ARRAY.includes(guess))  {
    numTries   ;
    alert('You must select one of the colors listed. Press ok to retry.');
} else if (guess < target) {
    numTries   ;
    alert('Incorrect. You are on try '   numTries   '.'   '\n\nAlphabetically to high');
} else if (guess > target) {
    numTries   ;
    alert('Incorrect. You are on try '   numTries   '.'   '\n\nAlphabetically to low');
} else {
    correct = true;
    document.body.style.background = guess;
} 
return correct;

CodePudding user response:

I don't think you need to use a do-while loop here. You could do something like the following. I'm choosing the number of tries here as 3.

function checkGuess(guess, target) {
  let tries = 3;
  
  while (tries > 0) {
    alert("Guess the colour - you have "   tries   " tries left.");
    if (guess === target) {
      return true;
    } else {
      tries--;
    }
  }
}

This code will continuously prompt the user to guess the colour using a loop that runs until the user either guesses the correct colour or runs out of tries. This may not satisfy your requirements thoroughly, but you can extract the logic from it.

  • Related