The task is as follows:

Write the game "Guess the number." When the page loads, a random number is generated from 0 to 10. The user is given three attempts to guess the number (the number is entered into the input). At each check the hint is given: more or less. When guessing the completion of the number of attempts, an alert is issued. The number of attempts displayed on the screen.

Everything is ok, but I can’t figure out how to implement a retry count. There is a thought to limit them with a cycle, but I don’t understand what to put in a variable.

var prNum, tempOut; prNum = Math.round(Math.random() * 10); function guessNum() { var num, out; num = document.getElementById('mynum').value; out = document.getElementById('out'); if (num == prNum) { out.innerHTML = 'вы угадали!' } else if (num > 10 || num < 0) { out.innerHTML = 'Введите число от 0 до 10' } else if (num > prNum) { out.innerHTML = 'Вы ввели число больше!' } else if (num < prNum) { out.innerHTML = 'Вы ввели число меньше!' } } 
  • as an option to increment with each attempt - ishidex2

2 answers 2

Alas, I do not see any options for how to do this in a cycle. I suggest simply making the counter:

 var prNum, tempOut; prNum = Math.round(Math.random() * 10); var count = 3; function guessNum() { var out = document.getElementById('out'); if (count == 0) { out.innerHTML = 'Попытки кончились :(' return; } var num = document.getElementById('mynum').value; if (num == prNum) { out.innerHTML = 'вы угадали!' } else if (num > 10 || num < 0) { out.innerHTML = 'Введите число от 0 до 10' } else if (num > prNum) { out.innerHTML = 'Вы ввели число больше!' } else if (num < prNum) { out.innerHTML = 'Вы ввели число меньше!' } count--; } 
 <input id="mynum" type="number" /><input type="button" onclick="guessNum();" value="guess"> <hr/> <p id="out"></p> 

    And what prevents to do so

     var prNum, tempOut, attempts = 3; prNum = Math.round(Math.random() * 10); function guessNum() { var num, out; num = document.getElementById('mynum').value; out = document.getElementById('out'); if(attempts == 0) { out.innerHTML = 'Вы исчерпали все попытки' return; } attempts--; if (num == prNum) { out.innerHTML = 'вы угадали! ' } else if (num > 10 || num < 0) { out.innerHTML = 'Введите число от 0 до 10. Осталось попыток:' + attempts } else if (num > prNum) { out.innerHTML = 'Вы ввели число больше! Осталось попыток:' + attempts } else if (num < prNum) { out.innerHTML = 'Вы ввели число меньше!Осталось попыток:' + attempts } }