-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcar.js
More file actions
65 lines (56 loc) · 1.87 KB
/
car.js
File metadata and controls
65 lines (56 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
const car = document.getElementById('car');
const obstacles = document.querySelectorAll('.obstacle');
const road = document.getElementById('road');
let carPosition = 50;
let obstacleSpeed = 2;
let score = 0;
function moveCar(event) {
if (event.key === 'ArrowLeft' && carPosition > 10) {
carPosition -= 10;
}
if (event.key === 'ArrowRight' && carPosition < 260) {
carPosition += 10;
}
car.style.left = `${carPosition}px`;
}
function moveObstacles() {
obstacles.forEach(obstacle => {
let obstacleTop = parseInt(window.getComputedStyle(obstacle).getPropertyValue('top'));
if (obstacleTop > 600) {
obstacleTop = -80;
score++;
obstacle.style.left = `${Math.random() * (road.clientWidth - 40)}px`;
}
obstacle.style.top = `${obstacleTop + obstacleSpeed}px`;
obstacle.style.left = `${obstacle.style.left}`;
});
if (checkCollision()) {
alert(`Game Over! Your score: ${score}`);
resetGame();
}
requestAnimationFrame(moveObstacles);
}
function checkCollision() {
const carRect = car.getBoundingClientRect();
let collision = false;
obstacles.forEach(obstacle => {
const obstacleRect = obstacle.getBoundingClientRect();
if (
carRect.x < obstacleRect.x + obstacleRect.width &&
carRect.x + carRect.width > obstacleRect.x &&
carRect.y < obstacleRect.y + obstacleRect.height &&
carRect.y + carRect.height > obstacleRect.y
) {
collision = true;
}
});
return collision;
}
function resetGame() {
score = 0;
obstacles.forEach(obstacle => {
obstacle.style.top = `${Math.random() * -600}px`;
});
}
document.addEventListener('keydown', moveCar);
requestAnimationFrame(moveObstacles);