-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
62 lines (53 loc) · 1.58 KB
/
script.js
File metadata and controls
62 lines (53 loc) · 1.58 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
const startBtn = document.getElementById("start-btn");
const target = document.getElementById("target");
const scoreDisplay = document.getElementById("score");
let score = 0;
let gameInterval;
// Generate a random position within the game container
function randomPosition() {
const container = document.getElementById("game-container");
const containerRect = container.getBoundingClientRect();
const size = target.offsetWidth; // Get the target size dynamically
const x = Math.random() * (containerRect.width - size);
const y = Math.random() * (containerRect.height - size);
return { x, y };
}
// Move the target to a random position
function moveTarget() {
const position = randomPosition();
target.style.left = `${position.x}px`;
target.style.top = `${position.y}px`;
}
// Start the game
function startGame() {
score = 0;
scoreDisplay.textContent = `Score: ${score}`;
target.style.display = "block";
moveTarget();
gameInterval = setInterval(() => {
moveTarget();
}, 1000);
}
// End the game
function endGame() {
clearInterval(gameInterval);
target.style.display = "none";
alert(`Game over! Your score: ${score}`);
}
// Add click and touch events for the target
target.addEventListener("click", () => {
score++;
scoreDisplay.textContent = `Score: ${score}`;
});
target.addEventListener("touchstart", () => {
score++;
scoreDisplay.textContent = `Score: ${score}`;
});
// Start the game when the button is clicked
startBtn.addEventListener("click", () => {
startGame();
// End game after 15 seconds
setTimeout(() => {
endGame();
}, 15000);
});