Malv
Malv

Reputation: 29

Javascript guess number game not working

Hello I am creating a simple game where the program generates a random number between 1-1000 and then the user inputs a number. If it is smaller it generates too low if it is larger it generates too high and congratulations if it is correct. The problem is my program always generates too high.Can you help me? Thank you!

<!DOCTYPE html>
 <html>
 <head>
<script type="text/javascript">
    var numri=gjenero();
    function gjenero(){
        return Math.floor(1000*Math.random())+1;
    }
    function kontrollo(){
     pergjigja=parseInt(document.getElementById("pergjigja").value);
        if (numri<pergjigja){
           alert("Too low!");
           document.getElementById("pergjigja").value="";

        }
        else if (numri>pergjigja){
            alert("Too high!");
            document.getElementById("pergjigja").value="";
        }
        else {
             alert("Congratulations.Continue the game with another 
        number!");
            gjenero();
        }
    }
   </script>
    </head>
       <body>

   <input type="text" id="pergjigja" >
   <button onclick="kontrollo();">Check</button>
  </body>
   </html>

Upvotes: 0

Views: 89

Answers (1)

Chris
Chris

Reputation: 3338

You have your logic backwards:

numri is the random number, and pergjigja is the input. If you type in 1001, then you'll see the Too low error message.

You should update the < and > operators like so to have the desired behavior:

if (numri>pergjigja){
   alert("Too low!");
   document.getElementById("pergjigja").value="";

}
else if (numri<pergjigja){
    alert("Too high!");
    document.getElementById("pergjigja").value="";
}
else {
    alert("Congratulations.Continue the game with another number!");
    numri=gjenero();
}

Upvotes: 1

Related Questions