🎯 JavaScript Number Guessing Game

🎯 JavaScript Number Guessing Game

“The computer picks a number… and you pick the logic.” 😅

In this project, you’ll learn step by step:

  • How JavaScript thinks
  • How it talks to the user
  • How it handles mistakes

And yes… lots of humor, lots of tips, and plenty of ‘aha!’ moments 😄


🧠 What Will You Learn in This Project? (Real Gains)

✔️ Generating random numbers (the right way)
✔️ Safely getting user input
✔️ Game logic (a mini version of state management)
✔️ Writing live feedback to the screen with the DOM
✔️ Listening to the user with events
✔️ Thinking “I can use this in React too”


📦 The General Game Logic (Thinking Like JS)

First, let’s build the brain of the game:

1️⃣ The computer picks a random number between 1–100
2️⃣ The user has a limited number of attempts
3️⃣ On each guess:
    Correct → 🎉 you win
    Wrong → you get a hint
4️⃣ Attempts run out → 😵 game over

📌 Golden rule:
Build the logic before writing code.
JavaScript is not a wizard — if you don’t think, neither will it 😄


🎲 1. Generating a Random Number (The Heart of the Game ❤️)

const randomNumber = Math.floor(Math.random() * 100) + 1;

🧠 What’s Happening Here? (Piece by Piece)

Math.random()
👉 Generates a random decimal between 0 and 1
Example: 0.374829

Math.random() * 100
👉 Becomes a number between 0 – 99.999

Math.floor(…)
👉 Removes the decimal
56.87 → 56

+ 1
👉 Shifts the range to 1–100 (very important!)

📌 Tip:
Math.floor(Math.random() * max) + min
This pattern will save you in many projects.


❤️ 2. Attempt Count (The Player’s Life)

let attemptsLeft = 5;

🧠 This variable is:

  • The game’s state
  • Decreases after every wrong guess
  • Ends the game at 0

“No attempts, no hope.” 😅

📌 Practical tip:
Later, this can be used for:

  • Difficulty levels
  • User settings

🖥️ 3. HTML Side (Setting the Stage 🎭)

Minimal but functional HTML:

<input type="number" id="guessInput" placeholder="Enter a number between 1-100" />
<button id="guessBtn">Guess</button>

<p id="message"></p>
<p id="attempts"></p>

🧠 Here:

  • input → talks to the user
  • button → triggers the game
  • p → gives feedback

🔗 4. Connecting DOM Elements to JS

const guessInput = document.getElementById("guessInput");
const guessBtn = document.getElementById("guessBtn");
const message = document.getElementById("message");
const attempts = document.getElementById("attempts");

attempts.textContent = `Attempts left: ${attemptsLeft}`;

🧠 Logic:

  • HTML → connected to JS
  • JS → controls HTML
  • User → just enjoys the show 😄

📌 Pro tip:
Grab DOM elements at the top — cleaner code, happier dev.


🎮 5. Let the Game Begin! (Event Listener)

guessBtn.addEventListener("click", () => {
  const userGuess = Number(guessInput.value);

🧠 Here:

  • Button is clicked
  • Value is taken from input
  • Number() converts string → number

📌 Why it matters:
"10" === 10
Number("10") === 10


🚧 6. Invalid Input Check (Save the User)

if (!userGuess) {
  message.textContent = "⚠️ Please enter a valid number!";
  return;
}

🧠 This prevents:

  • Empty input
  • 0
  • NaN

📌 Real-life lesson:
Never trust the user 😄
…but always be polite.


🎯 7. Correct Guess Check (Victory Moment 🎉)

if (userGuess === randomNumber) {
  message.textContent = "🎉 Congratulations! Correct guess!";
  guessBtn.disabled = true;
}

🧠 Here:

  • Game is won
  • Button is disabled
  • User is happy 😊

📌 UX tip:
Disabling inputs after winning = great experience.


🔽 8. Wrong Guess & Attempt Management

else {
  attemptsLeft--;

😬 Oops… wrong guess

  • Attempts decrease
  • Tension rises

😵 9. Are Attempts Over? (Game Over)

if (attemptsLeft === 0) {
  message.textContent = `😵 Game over! The number was: ${randomNumber}`;
  guessBtn.disabled = true;
}

🧠 Here:

  • Game ends
  • Correct number is revealed
  • User goes “ahhh…” 😅

🔼🔽 10. Higher / Lower Hint

message.textContent =
  userGuess < randomNumber
    ? "🔼 Try a higher number"
    : "🔽 Try a lower number";

attempts.textContent = `Attempts left: ${attemptsLeft}`;

🧠 With the ternary operator:

  • Cleaner code
  • Fewer if statements
  • Better readability

📌 Pro tip:
This often earns bonus points in interviews 😉


🧹 11. Clear the Input (Small but Important)

guessInput.value = "";

🎯 User is ready for the next guess!


🧪 12. What Does This Project Really Teach You?

✔️ JavaScript mindset
✔️ Game & application logic
✔️ DOM + state + event relationship
✔️ “I can move this into a framework” awareness


🚀 13. Level Up Ideas (Path to Mastery)

You can take this project further with:

🔁 Restart button
🎚️ Difficulty levels
🧠 Guess history
🎨 Colorful feedback
🔊 Sound effects
📱 Mobile responsiveness


🎯 Final Words

This game may be small, but it teaches a big lesson:

“JavaScript is not just syntax — it’s a way of thinking.” 😄

Comments

No comments yet. Why don’t you start the discussion?

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir