Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.1 kB
1
Indexable
Never
// Step 2: Generate a random number between 1 and 100
let randomNumber = Math.floor(Math.random() * 100) + 1;

// Step 3: Initialize variables
let guess;
let attempts = 0;
let maxAttempts = 5;

// Step 4: Create a While Loop for the Game
while (attempts < maxAttempts) {
  // Step 4.1: Get the Player's Guess
  guess = parseInt(prompt("Guess the number between 1 and 100:"));

  // Step 6: Check if the Guess is Valid
  if (!isNaN(guess)) {
    // Step 6.1: Compare the Guess with the Random Number
    attempts++;
    if (guess === randomNumber) {
      alert(
        "Congratulations! You guessed the number " +
          randomNumber +
          " correctly in " +
          attempts +
          " attempts."
      );
      break;
    } else if (guess < randomNumber) {
      alert("Too low! Try again.");
    } else {
      alert("Too high! Try again.");
    }
  } else {
    alert("Please enter a valid number.");
  }
}

// Step 8: End the Game
if (attempts === maxAttempts) {
  alert(
    "Sorry, you've used all your attempts. The number was " + randomNumber + "."
  );
}

Leave a Comment