0

Can anyone help me on my issue, it seems that my loop doesn't work. I created a random number guessing game, and I wanted to have only 5 tries. And once it hits the 5th try, it will display a message. But it seems that I was able to do it countless time.

function RandomNumber()
        {    
            //get value from random number textbox
            var lol=document.getElementById("guess").value;
            //get new value from user 
            var ass=document.getElementById("textbox").value;
            var maxtries=5;
            for(var i=0;i<=maxtries;i++)
            { 
                if(ass == lol)//if user guess correctly
                    {
                        document.getElementById("correct").innerHTML="Correct"
                    }
                else if(ass!=lol)//if user guess wrongly
                    {
                        document.getElementById("correct").innerHTML="Not correct"

                    }
                else if (i==maxtries)
                    {
                        document.getElementById("correct").innerHTML="No more tries"
                    }
            }
        }

This is my <form> codes

<td style="text-align:center">
            Lowest number: 
            <input id="digit" type="text" name="lowestnumber" onchange="validate()"><br/>
            <br/><span id="numbers"></span>
            </td>
        </tr>
        <tr>
            <td style="text-align:center">
            Highest number:
            <input id="digit1" type="text" name="highestnumber" onchange="validate()"><br/>
            <br/><span id="numbers1"></span>    
            </td>
        </tr>
        <tr>
            <td style="text-align:center">
            <br/><input id="rand" type="submit" value="submit" onclick="Random()" disabled><br/>
            <input id="guess" type="text" value="Random Number Generator">
            </td>
        </tr>
        <tr>
            <td style="text-align:center">
            <br/>Enter your number<br/>
            <input id="textbox" type="text"><br/>
            <input id="guessing" type="button" value="Random" onclick="RandomNumber()"><br/>
            <br/><span id="correct"></span>
            </td>

2 Answers2

0

There's a couple problems here. The first and biggest (maybe) is that your loop counts down right away and doesn't give the guesser a chance to make another guess. The second problem is that the 3rd if statement that checks for the number of guesses can never be reached. I have refactored this check to the beginning on the function.

You should call RandomNumber when the user submits a new guess

You can fix this like:

function RandomNumber()
        {
        if (!this.guesses) {
          this.guesses = 1;
        } else {
          this.guesses++;
          if (this.guesses > 5) {
            document.getElementById("correct").innerHTML="No more tries";
            return; // max guesses exceeded
          }
        }    
            //get value from random number textbox
            var lol=document.getElementById("guess").value;
            //get new value from user 
            var ass=document.getElementById("textbox").value;
                if(ass == lol)//if user guess correctly
                    {
                        document.getElementById("correct").innerHTML="Correct"
                    }
                else if(ass!=lol)//if user guess wrongly
                    {
                        document.getElementById("correct").innerHTML="Not correct"

                    }
        }
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • it doesn't work, it won't even allow me to generate a random number – Ng Leng Poh Oct 20 '20 at 14:33
  • It does work, but how does it work? I don't understand the functionality of this, what if you were to use a while or for loop? – Ng Leng Poh Oct 20 '20 at 14:38
  • setting `this.guesses` sets a variable that is maintained by the function (it enters a name-value pair in the function JS Object). Then every time you enter the function (with each new guess), it increments the value. When it gets to the max number of guesses (5), it checks that you have no more guesses, and then does a quick return. – ControlAltDel Oct 20 '20 at 14:48
  • The problem with a loop (while or for) is that it doesn't give the user time to enter another guess. In the loop you were using, you were repeatedly checking *the same guess against the answer*. So basically, change in your thinking to a user-driven perspective: Not "Use a loop to allow 5 guesses", but instead "After the 5th user (guess submission) event, say no more submissions allowed" – ControlAltDel Oct 20 '20 at 14:52
0

Right now, your loop runs 6 times in a row. What you want is no loop at all, but a simple counter that can keep track of how many guesses have been made and when the count reaches the max, the guessing is over.

Other Notes:

  • You seem to have an excessive amount of input elements and since this is just a game and you are not actually submitting the data anywhere, you shouldn't be using submit buttons and adding name attributes to the form fields.
  • You should not be using tables for page layout - - that's the job of CSS.
  • Don't use .innerHTML when you aren't working with strings that contain HTML as .innerHTML has security and performance implications. Use .textContent instead.
  • Don't use inline HTML event attributes. Do you JavaScript separately from your HTML.
  • Don't use self-terminating syntax.

const checkAnswer=document.getElementById("guessing");
const d1= document.getElementById("digit1");
const d2= document.getElementById("digit2");
const guess = document.getElementById("guess");
const rand = document.getElementById("rand");
const result = document.getElementById("correct");

const maxtries=5;
let count = 1;
let answer = null;

d2.addEventListener("blur", function(){
 rand.removeAttribute("disabled");
});

rand.addEventListener("click", function(){
console.log(d1.value, d2.value);
  answer = Math.floor(Math.random() * (d2.value - d1.value + 1) + d1.value);;
  console.log(answer);
});
  
checkAnswer.addEventListener("click", randomNumber)
function randomNumber() { 
  if(count < maxtries){
    if(guess.value == answer){
      result.textContent="Correct";
    } else {
      result.textContent="Guess " + count + " Not correct";
    } 
    count++;      // Increase the counter
  } else {
    result.textContent="No more tries";
  }
}
<div>
 Lowest number: <input id="digit1" type="text">
                <br><span id="numbers"></span>
</div>
<div>
 Highest number: <input id="digit2" type="text">
                 <br><span id="numbers1"></span>    
</div>
<div>
  <input id="rand" type="button" value="Generate Random" disabled><br>
</div>
<div>
  Enter your number<br>
  <input id="guess" type="text"><br>
  <input id="guessing" type="button" value="Check Answer"><br>
  <span id="correct"></span>
</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71