Search code examples
javascripthtmlbootstrap-5do-while

Javascript guess game using do while loop not working


I have created a guessing game in Javascript and HTML but it's not working it has the following specifications

  1. Takes input from the user (three attempts)
  2. Check guessed number with a random generated number(on button click)
  3. If the User input is less than a random number it shows (You entered a smaller number)
  4. If the User input is large than the random number it shows (You entered a larger number)
  5. if all three attempts have been used then it shows (You have used all attempts) and the program terminates. Note: Do while loop must be used (mandatory) I want it to work with HTML tags, not console.log or Prompt

When I enter the Number it shows (You have used all attempts) While it should show output according to entered number and it also does not stop after three attempts Here's the code:

function checkans(){
      const ans=Math.random()*100+1;
      let attempts = 3;
      do{
      const userans = Number.parseInt(document.getElementById("number").value); 
        if(userans===ans){
        document.getElementById("result").innerHTML= "Result : Hooray! You won " +ans+ " is the correct answere"; 
        break;
      } else if(userans < ans){
          document.getElementById("result").innerHTML= "Hint : You entered small value than answer. <br> Try again";
      }else {
        document.getElementById("result").innerHTML= "Hint : You entered large value than answer. <br> Try again";
      }
      attempts--;
      if(attempts=== 0){
        document.getElementById("result").innerHTML= "Sorry! You have used all attempts to guess";
      }
    }
      while(attempts>0);         
    }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
     <title>Document</title>
</head>
<body>
  <div class="container-fixed px-5 mx-5 mt-5 pt-5">
    <div class="card align-items-center"> 
      <div class="card-header">
        <h1>
          Welcome to Guess Game
        </h1>
      </div>
      <h3>
        In this game you will have three (3) attempts to find the correct answere!
      </h3>
      <div class="card-body">
        <div class="input-group">
          <span class="input-group-text">Enter Your Answere: </span>
          <input type="number" name="" class="form-control" id="number">
        </div>
        <div class="btn d-grid gap-2 d-md-block">
          <button type="submit" class="btn btn-outline-success mx-auto" id="lock" onclick="checkans()">
            <span>
              Lock Answer
            </span>
          </button>
        </div>
        <span id="result"></span>
      </div>
    </div>
  </div>
</body>
</html>


Solution

  • You have a few issues:

    First, you don't need a loop. Your loop was basically taking the same answering and checking it over and over again until the attempts ran out. Also, your random number generator was generating a long decimal number and I doubt that is what you wanted.

    I cleaned up your code a bit:

    I moved the variable declarations outside of the function as they don't need to be redeclared each time.

    I also created a function out of your random number generator and I'm using parseInt to create an integer.

    const randomNumber = () =>Number.parseInt(Math.random() * 100 + 1);
    const ansField = document.getElementById("number")
    const result = document.getElementById("result")
    let userans = 0;
    
    let attempts = 3;
    
    let ans = randomNumber();
    
    function checkans() {
       userans = Number.parseInt(ansField.value);
       attempts--;
       result.innerHTML = "";
      if (userans === ans) {
        result.innerHTML = "Result : Hooray! You won " + ans + " is the correct answer";
        attempts = 3;
        ans = randomNumber();
      } else if (userans < ans) {
        result.innerHTML = "Hint : You entered small value than answer. <br> Try again";
      } else if (userans > ans) {
        result.innerHTML = "Hint : You entered large value than answer. <br> Try again";
      }
      
      if (attempts === 0) {
        result.innerHTML += "<br>Sorry! You have used all attempts to guess (" + ans + " was the correct number)";
        ans = randomNumber();
        attempts = 3;
      }
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
      <title>Document</title>
    </head>
    
    <body>
      <div class="container-fixed px-5 mx-5 mt-5 pt-5">
        <div class="card align-items-center">
          <div class="card-header">
            <h1>
              Welcome to Guess Game
            </h1>
          </div>
          <h3>
            In this game you will have three (3) attempts to find the correct answere!
          </h3>
          <div class="card-body">
            <div class="input-group">
              <span class="input-group-text">Enter Your Answere: </span>
              <input type="number" name="" class="form-control" id="number">
            </div>
            <div class="btn d-grid gap-2 d-md-block">
              <button type="submit" class="btn btn-outline-success mx-auto" id="lock" onclick="checkans()">
                <span>
                  Lock Answer
                </span>
              </button>
            </div>
            <span id="result"></span>
          </div>
        </div>
      </div>
    </body>
    
    </html>