A simple sport car racing game where players can control a car using arrow keys to navigate through a track while avoiding obstacles.
Prompt
create sport car racing game
HTML
<canvas id="racingGame" width="800" height="400"></canvas><div class="controls">Use arrow keys to move the car</div>
CSS
body { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; margin: 0; background-color: #333; color: #fff; font-family: Arial, sans-serif; } canvas { border: 2px solid #fff; background-color: #444; } .controls { margin-top: 10px; font-size: 18px; }JS
(function() {
const canvas = document.getElementById('racingGame');
const ctx = canvas.getContext('2d');
const car = { x: canvas.width / 2 - 15, y: canvas.height - 60, width: 30, height: 60, speed: 5 };
const obstacles = [];
let keys = {};
function drawCar() {
ctx.fillStyle = '#FF0000';
ctx.fillRect(car.x, car.y, car.width, car.height);
}
function update() {
if (keys['ArrowUp']) car.y -= car.speed;
if (keys['ArrowDown']) car.y += car.speed;
if (keys['ArrowLeft']) car.x -= car.speed;
if (keys['ArrowRight']) car.x += car.speed;
car.x = Math.max(0, Math.min(car.x, canvas.width - car.width));
car.y = Math.max(0, Math.min(car.y, canvas.height - car.height));
}
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawCar();
update();
requestAnimationFrame(gameLoop);
}
window.addEventListener('keydown', function(event) {
keys[event.key] = true;
});
window.addEventListener('keyup', function(event) {
keys[event.key] = false;
});
gameLoop();
})();Comments (0)
Log in to comment.
Working...