// Game variables let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); document.body.appendChild(canvas); canvas.width = 800; canvas.height = 600; let carWidth = 50; let carHeight = 100; let carX = canvas.width / 2 - carWidth / 2; let carY = canvas.height - carHeight - 20; let carSpeed = 5; let carImg = new Image(); carImg.src = 'car.png'; // Use your car image URL here let obstacles = []; let obstacleWidth = 50; let obstacleHeight = 100; let obstacleSpeed = 2; let score = 0; let leftArrow = false; let rightArrow = false; // Handling user input document.addEventListener('keydown', (e) => { if (e.key === 'ArrowLeft') { leftArrow = true; } if (e.key === 'ArrowRight') { rightArrow = true; } }); document.addEventListener('keyup', (e) => { if (e.key === 'ArrowLeft') { leftArrow = false; } if (e.key === 'ArrowRight') { rightArrow = false; } }); // Game loop function gameLoop() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Move car based on user input if (leftArrow && carX > 0) { carX -= carSpeed; } if (rightArrow && carX + carWidth < canvas.width) { carX += carSpeed; } // Create new obstacle if (Math.random() < 0.02) { let obstacleX = Math.random() * (canvas.width - obstacleWidth); obstacles.push({ x: obstacleX, y: -obstacleHeight }); } // Move obstacles down and check for collisions for (let i = 0; i < obstacles.length; i++) { obstacles[i].y += obstacleSpeed; // Check for collision with car if ( obstacles[i].y + obstacleHeight > carY && obstacles[i].y < carY + carHeight && obstacles[i].x + obstacleWidth > carX && obstacles[i].x < carX + carWidth ) { // Game over alert('Game Over! Your score: ' + score); resetGame(); return; } // Remove obstacles that are off the screen if (obstacles[i].y > canvas.height) { obstacles.splice(i, 1); i--; score++; } } // Draw obstacles for (let i = 0; i < obstacles.length; i++) { ctx.fillStyle = 'red'; ctx.fillRect(obstacles[i].x, obstacles[i].y, obstacleWidth, obstacleHeight); } // Draw car ctx.drawImage(carImg, carX, carY, carWidth, carHeight); // Draw score ctx.font = '20px Arial'; ctx.fillStyle = 'black'; ctx.fillText('Score: ' + score, 10, 30); // Request next frame requestAnimationFrame(gameLoop); } // Reset game state function resetGame() { carX = canvas.width / 2 - carWidth / 2; carY = canvas.height - carHeight - 20; obstacles = []; score = 0; } // Start the game gameLoop();