-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcardrop.html
94 lines (82 loc) · 2.04 KB
/
cardrop.html
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
83
84
85
86
87
88
89
90
91
92
93
94
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Block Car Game</title>
<style>
canvas {
display: block;
margin: 0 auto;
background-color: skyblue;
border: 2px solid black;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let car = {
x: 100,
y: 400,
width: 50,
height: 30,
velocityX: 1
};
let platforms = [];
canvas.addEventListener('click', (event) => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
platforms.push({ x, y, width: 100, height: 10 });
});
function drawCar() {
ctx.fillStyle = 'black';
ctx.fillRect(car.x, car.y, car.width, car.height);
}
function drawPlatforms() {
ctx.fillStyle = 'brown';
for (let platform of platforms) {
ctx.fillRect(platform.x, platform.y, platform.width, platform.height);
}
}
function collision(car, platform) {
return (
car.x < platform.x + platform.width &&
car.x + car.width > platform.x &&
car.y < platform.y + platform.height &&
car.y + car.height > platform.y
);
}
function updateCar() {
car.x += car.velocityX;
for (let platform of platforms) {
if (collision(car, platform)) {
car.y = platform.y - car.height;
break;
} else {
car.y += 1;
}
}
if (car.y > canvas.height) {
resetGame();
}
}
function resetGame() {
car.x = 100;
car.y = 400;
platforms = [];
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlatforms();
drawCar();
updateCar();
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>