const canvas = document.getElementById(’gameCanvas’); const ctx = canvas.getContext(’2d’); canvas.width = window.innerWidth; canvas.height = window.innerHeight; let car = { x: canvas.width / 2 – 25, y: canvas.height – 120, width: 50, height: 100, dx: 0, speed: 5 }; let obstacles = []; let gameSpeed = 3; let score = 0; let gameOver = false; function drawCar() { ctx.fillStyle = ’blue’; ctx.fillRect(car.x, car.y, car.width, car.height); } function createObstacle() { const width = Math.random() * 100 + 50; const x = Math.random() * (canvas.width – width); obstacles.push({ x: x, y: 0, width: width, height: 20 }); } function drawObstacles() { ctx.fillStyle = ’red’; obstacles.forEach(obstacle => { ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height); }); } function moveObstacles() { obstacles.forEach(obstacle => { obstacle.y += gameSpeed; }); } function removeOffscreenObstacles() { obstacles = obstacles.filter(obstacle => obstacle.y < canvas.height); } function detectCollision() { obstacles.forEach(obstacle => { 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; } }); } function updateScore() { score++; } function clearCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); } function update() { if (gameOver) { ctx.font = ’48px sans-serif’; ctx.fillStyle = ’white’; ctx.fillText(’Game Over’, canvas.width / 2 – 120, canvas.height / 2); return; } clearCanvas(); drawCar(); drawObstacles(); moveObstacles(); removeOffscreenObstacles(); detectCollision(); updateScore(); ctx.font = ’24px sans-serif’; ctx.fillStyle = ’white’; ctx.fillText(’Score: ’ + score, 10, 30); car.x += car.dx; requestAnimationFrame(update); } function keyDown(e) { if (e.key === ’ArrowLeft’) { car.dx = -car.speed; } else if (e.key === ’ArrowRight’) { car.dx = car.speed; } } function keyUp(e) { if (e.key === ’ArrowLeft’ || e.key === ’ArrowRight’) { car.dx = 0; } } document.addEventListener(’keydown’, keyDown); document.addEventListener(’keyup’, keyUp); setInterval(createObstacle, 2000); update();


Publicerat

i

av

Etiketter:

Kommentarer

Lämna ett svar

Din e-postadress kommer inte publiceras. Obligatoriska fält är märkta *