Meta Description" name="description" />
<!DOCTYPE html>
<html>
<head>
<title>Car Game Images</title>
<style>
body {
margin: 0;
overflow: hidden;
background: #222;
}
canvas {
display: block;
margin: auto;
background: #555;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="600"></canvas>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
// Load images
const carImg = new Image();
carImg.src = "https://i.imgur.com/7QZ7Q9T.png"; // car image
const enemyImg = new Image();
enemyImg.src = "https://i.imgur.com/7QZ7Q9T.png"; // enemy car
const coinImg = new Image();
coinImg.src = "https://i.imgur.com/6X12R9F.png"; // coin image
// Player
let car = {
x: 180,
y: 500,
width: 40,
height: 80,
speed: 5
};
// Enemy
let obstacle = {
x: Math.random() * 360,
y: -100,
width: 40,
height: 80,
speed: 4
};
// Coin
let coin = {
x: Math.random() * 360,
y: -50,
size: 25,
speed: 3
};
let score = 0;
let coins = 0;
let gameOver = false;
// Controls
let keys = {};
document.addEventListener("keydown", e => keys[e.key] = true);
document.addEventListener("keyup", e => keys[e.key] = false);
function update() {
if (gameOver) return;
// Move car
if (keys["ArrowLeft"] && car.x > 0) car.x -= car.speed;
if (keys["ArrowRight"] && car.x < canvas.width - car.width) car.x += car.speed;
// Move enemy
obstacle.y += obstacle.speed;
if (obstacle.y > canvas.height) {
obstacle.y = -100;
obstacle.x = Math.random() * 360;
score++;
}
// Move coin
coin.y += coin.speed;
if (coin.y > canvas.height) {
coin.y = -50;
coin.x = Math.random() * 360;
}
// Coin collision
if (
car.x < coin.x + coin.size &&
car.x + car.width > coin.x &&
car.y < coin.y + coin.size &&
car.y + car.height > coin.y
) {
coins++;
coin.y = -50;
coin.x = Math.random() * 360;
}
// Crash collision
if (
car.x < obstacle.x + obstacle.width &&
car.x + car.width > obstacle.x &&
car.y < obstacle.y + obstacle.height &&
car.y + car.height > obstacle.y
) {
gameOver = true;
alert("π₯ Game Over!\nScore: " + score + "\nCoins: " + coins);
location.reload();
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Road line
ctx.fillStyle = "white";
for (let i = 0; i < canvas.height; i += 40) {
ctx.fillRect(195, i, 10, 20);
}
// Draw images
ctx.drawImage(carImg, car.x, car.y, car.width, car.height);
ctx.drawImage(enemyImg, obstacle.x, obstacle.y, obstacle.width, obstacle.height);
ctx.drawImage(coinImg, coin.x, coin.y, coin.size, coin.size);
// Text
ctx.fillStyle = "white";
ctx.font = "20px Arial";
ctx.fillText("Score: " + score, 10, 30);
ctx.fillText("Coins: " + coins, 10, 60);
}
function gameLoop() {
update();
draw();
requestAnimationFrame(gameLoop);
}
gameLoop();
</script>
</body>
</html>5
2
3KB
4KB
99.0ms
116.0ms
197.0ms