const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Player car const carWidth = 50; const carHeight = 100; const car = { x: canvas.width / 2 - carWidth / 2, y: canvas.height - carHeight, width: carWidth, height: carHeight, speed: 5, color: "red" }; // Enemy cars let enemies = []; const enemyWidth = 50; const enemyHeight = 100; const maxEnemies = 10; const enemySpeed = 5; const spawnRate = 1000; // Spawn an enemy every 1 second let lastSpawn = 0; // Keyboard controls const keys = {}; document.addEventListener("keydown", (event) => { keys[event.code] = true; }); document.addEventListener("keyup", (event) => { keys[event.code] = false; }); function update() { // Move player 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 cars enemies.forEach((enemy) => { enemy.y += enemySpeed; }); // Spawn new enemy cars if (Date.now() - lastSpawn > spawnRate && enemies.length < maxEnemies) { const enemy = { x: Math.random() * (canvas.width - enemyWidth), y: -enemyHeight, width: enemyWidth, height: enemyHeight, color: "blue" }; enemies.push(enemy); lastSpawn = Date.now(); } // Check for collision enemies.forEach((enemy, index) => { if (car.x < enemy.x + enemy.width && car.x + car.width > enemy.x && car.y < enemy.y + enemy.height && car.y + car.height > enemy.y) { // Game over alert("Game over!"); location.reload(); } // Remove enemy if it's offscreen if (enemy.y > canvas.height) { enemies.splice(index, 1); } }); // Clear canvas and draw cars ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = car.color; ctx.fillRect(car.x, car.y, car.width, car.height); enemies.forEach((enemy) => { ctx.fillStyle = enemy.color; ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height); }); // Call update function again requestAnimationFrame(update); } // Start game u