0% found this document useful (0 votes)
16 views2 pages

js game

The document describes a simple 'Guess the Number' game where a random number between 1 and 10 is generated. The player has three attempts to guess the number, receiving feedback on whether their guess is too low, too high, or correct. If the player fails to guess within the attempts, the game reveals the secret number and ends.

Uploaded by

Chanchal Dey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views2 pages

js game

The document describes a simple 'Guess the Number' game where a random number between 1 and 10 is generated. The player has three attempts to guess the number, receiving feedback on whether their guess is too low, too high, or correct. If the player fails to guess within the attempts, the game reveals the secret number and ends.

Uploaded by

Chanchal Dey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

// --- Guess the Number Game ---

// 1. Generate a random number between 1 and 10


const secretNumber = Math.floor(Math.random() * 10) + 1;
let attempts = 0;
let guess = 0;

console.log("I'm thinking of a number between 1 and 10. Can you guess it?");

// 2. Loop until the user guesses correctly or runs out of attempts (e.g., 3 attempts)
while (guess !== secretNumber && attempts < 3) {
attempts++;
// Use prompt for browser, or simulate with console.log for Node.js
// For Node.js, you'd need a package like 'readline-sync' or a more complex setup.
// For simplicity, this example assumes a browser environment or a "manual" input for
Node.js.

// In a browser, you would use:


// guess = parseInt(prompt(`Attempt ${attempts}: Enter your guess:`));

// For this "short game" example, let's simulate input or assume you run it in a browser:

// Simulating input for demonstration purposes (you'd replace this with actual user input)
if (attempts === 1) guess = 5; // Example 1st guess
else if (attempts === 2) guess = 2; // Example 2nd guess
else if (attempts === 3) guess = 8; // Example 3rd guess

console.log(`Your guess (Attempt ${attempts}): ${guess}`);

if (guess < secretNumber) {


console.log("Too low! Try again.");
} else if (guess > secretNumber) {
console.log("Too high! Try again.");
} else if (guess === secretNumber) {
console.log(`Congratulations! You guessed the number ${secretNumber} in ${attempts}
attempts!`);
} else {
console.log("That's not a valid number. Please enter a number.");
}
}

if (guess !== secretNumber) {


console.log(`Sorry, you ran out of attempts. The secret number was ${secretNumber}.`);
}
console.log("Game Over!");

You might also like