Guess number code

 avatar
user_0856540
plain_text
a month ago
967 B
2
Indexable
Never
// write your code // Generate a random number between 1 and 100
const secretNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;

// Function to check if the guess is correct
function checkGuess(guess) {
    attempts++;
    if (guess < secretNumber) {
        return "Too low! Try again.";
    } else if (guess > secretNumber) {
        return "Too high! Try again.";
    } else {
        return `Congratulations! You've guessed the number ${secretNumber} in ${attempts} attempts!`;
    }
}

// Main function to play the game
function playGame() {
    while (true) {
        const guess = parseInt(prompt("Enter your guess (between 1 and 100):"));
        if (isNaN(guess)) {
            alert("Please enter a valid number.");
            continue;
        }
        const result = checkGuess(guess);
        alert(result);
        if (guess === secretNumber) {
            break;
        }
    }
}

// Call the main function to start the game
playGame();