// Importing necessary libraries const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); document.body.appendChild(canvas); canvas.width = 800; canvas.height = 400; let dino = { x: 50, y: 300, width: 20, height: 20, gravity: 0.5, jumpPower: 10, velocityY: 0, isJumping: false }; let obstacles = []; let score = 0; let gameOver = false; function drawDino() { ctx.fillStyle = 'green'; ctx.fillRect(dino.x, dino.y, dino.width, dino.height); } function drawObstacles() { ctx.fillStyle = 'red'; obstacles.forEach(obstacle => { ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height); }); } function updateObstacles() { if (Math.random() < 0.02) { obstacles.push({ x: canvas.width, y: 300, width: 20, height: 20 }); } obstacles.forEach(obstacle => { obstacle.x -= 5; }); obstacles = obstacles.filter(obstacle => obstacle.x + obstacle.width > 0); } function checkCollision() { obstacles.forEach(obstacle => { if (dino.x < obstacle.x + obstacle.width && dino.x + dino.width > obstacle.x && dino.y < obstacle.y + obstacle.height && dino.y + dino.height > obstacle.y) { gameOver = true; } }); } function jump() { if (!dino.isJumping) { dino.isJumping = true; dino.velocityY = -dino.jumpPower; } } function update() { if (gameOver) return; dino.y += dino.velocityY; dino.velocityY += dino.gravity; if (dino.y >= 300) { dino.y = 300; dino.isJumping = false; } updateObstacles(); checkCollision(); score++; } function drawScore() { ctx.fillStyle = 'black'; ctx.font = '20px Arial'; ctx.fillText('Score: ' + score, 10, 20); } function gameLoop() { ctx.clearRect(0, 0, canvas.width, canvas.height); update(); drawDino(); drawObstacles(); drawScore(); if (!gameOver) { requestAnimationFrame(gameLoop); } else { ctx.fillText('Game Over', canvas.width / 2 - 40, canvas.height / 2); } } document.addEventListener('keydown', (event) => { if (event.code === 'Space') { jump(); } }); gameLoop();