1
resposta

Estou com dúvidas para encerrar o jogo da adivinhação quando se acerta o número gerado e restando mais chances para adivinhar.

E ae pessoal, blz? Estou com dúvida para encerrar o jogo quando o usuário acerta o número gerado. Eu sei que o "break" interrompe, mas usando o "while" e não o "if". Quando o usuário erra da certo haha (inclusive nas 3 x e mostrando a msg final). Alguém poderia me dar uma ajuda? Valeu Obs: Programei em inglês para afiar o idioma :)

<meta charset="UTF-8">

<input/>

<button>Click here to show the number created randomly by this computer</button>

<script>

    alert("Let's try to guess the number created by this computer? The game is simple, you'll have 3 guesses to get the number created from 0 to 10. Insert your guess on the left box and click on the right to see if you got it! Good luck my friend!");

    var numberCreated = Math.round(Math.random() * 10);

    var input = document.querySelector("input");
    input.focus();

    var guess = 1;

    function check() {
        if(guess <= 3) {
            if(input.value == numberCreated) {
                alert("Yes, you got it! The number created was " + numberCreated);
            }
        }        

        if(input.value < numberCreated) {
            alert("No, you got it wrong! Your guess was lower than the number created!");
        } else {
            alert("No, you got it wrong! Your guess was bigger than the number created!");
        }
        guess++

        if(guess == 2) {
            alert("You have 2 more guesses!");
        }

        if(guess == 3) {
            alert("Your last guess!");
        }

        if(guess >= 4) {
            alert("What a shame, you didn't get it. The number created was " + numberCreated + "! Refresh the page and try it again.");
        }

        input.value = " ";
        input.focus();

    }

    var button = document.querySelector("button");

    button.onclick = check;

</script>
1 resposta

Perceba que o var guess = 1; começa com 1, se ele acertar, ainda terá o valor 1, daí vai incrementar no guess++ virando 2.

Dessa forma ele vai sempre entrar nos blocos do if (guess == 2).

O que você pode tentar é colocar o incremento guess++ dentro dessa parte para que ele só incremente caso input.value < numberCreated:

if(input.value < numberCreated) {
            alert("No, you got it wrong! Your guess was lower than the number created!");
        } else {
            alert("No, you got it wrong! Your guess was bigger than the number created!");
        }
        guess++

Ficando assim:

if(input.value < numberCreated) {
            alert("No, you got it wrong! Your guess was lower than the number created!");

            guess++
        } else {
            alert("No, you got it wrong! Your guess was bigger than the number created!");

            guess++
        }