-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfinal.js
More file actions
82 lines (59 loc) · 1.87 KB
/
final.js
File metadata and controls
82 lines (59 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// ==========================
// Number Guessing Game
// ==========================
// Game variables set
let min, max, target;
let attemptsLeft;
let maxAttempts = 10;
let score = 0;
// Fetch HTML elements
const form = document.querySelector("form");
const input = document.getElementById("userinput");
const answerDiv = document.getElementById("answer");
// Create restart button dynamically
const restartBtn = document.createElement("button");
restartBtn.textContent = "Restart Game";
document.body.appendChild(restartBtn);
// Initialize Game
function initGame() {
min = Math.floor(Math.random() * 50) + 1;
max = min + Math.floor(Math.random() * 50) + 10;
target = Math.floor(Math.random() * (max - min + 1)) + min;
attemptsLeft = maxAttempts;
answerDiv.textContent = `Guess a number between ${min} and ${max}. Attempts left: ${attemptsLeft}`;
console.log(`Debug: target = ${target}`);
}
// Handle Guess
function handleGuess(guess) {
if (attemptsLeft <= 0) {
answerDiv.textContent = "No attempts left! Click restart for a new game.";
return;
}
attemptsLeft--;
if (guess < target) {
answerDiv.textContent = `Too small! Attempts left: ${attemptsLeft}`;
} else if (guess > target) {
answerDiv.textContent = `Too big! Attempts left: ${attemptsLeft}`;
} else {
score += attemptsLeft + 1; // reward efficiency
answerDiv.textContent = `🎉 Correct! The number was ${target}. Score: ${score}`;
attemptsLeft = 0;
return;
}
if (attemptsLeft === 0) {
answerDiv.textContent = `Game over! The number was ${target}. Final score: ${score}`;
}
}
// Event Listeners
form.addEventListener("submit", function(event) {
event.preventDefault();
const guess = Number(input.value);
if (isNaN(guess)) {
answerDiv.textContent = "Please enter a valid number!";
return;
}
handleGuess(guess);
input.value = "";
});
restartBtn.addEventListener("click", initGame);
initGame();