<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Dino Game</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
body {
margin: 0;
background-color: #f7f7f7;
overflow: hidden;
font-family: sans-serif;
text-align: center;
}
canvas {
background: #fff;
display: block;
margin: 50px auto;
border: 2px solid #000;
max-width: 100%;
height: auto;
}
h1 {
margin-top: 20px;
}
</style>
<link href="/style.css" rel="stylesheet" type="text/css" media="all">
</head>
<body>
<canvas id="game" width="800" height="200"></canvas>
<script>
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
let dino = { x: 50, y: 150, width: 40, height: 40, vy: 0, jumping: false };
let gravity = 1.5;
let obstacles = [];
let gameSpeed = 6;
let score = 0;
let gameOver = false;
let spawnCooldown = 0; // Cooldown counter for obstacle spawn
function drawDino() {
ctx.fillStyle = 'black';
ctx.fillRect(dino.x, dino.y, dino.width, dino.height);
}
function drawObstacle(obstacle) {
ctx.fillStyle = 'green';
ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
}
function update() {
if (gameOver) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Dino physics
dino.vy += gravity;
dino.y += dino.vy;
if (dino.y >= 150) {
dino.y = 150;
dino.vy = 0;
dino.jumping = false;
}
drawDino();
// Obstacles
spawnCooldown--;
if (spawnCooldown <= 0) {
if (Math.random() < 0.02) {
obstacles.push({ x: canvas.width, y: 150, width: 20 + Math.random() * 30, height: 40 });
spawnCooldown = 60 + Math.random() * 40;
}
}
obstacles.forEach((obstacle, index) => {
obstacle.x -= gameSpeed;
drawObstacle(obstacle);
// Collision detection
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;
alert('Game Over! Score: ' + score);
document.location.reload();
}
// Remove passed obstacles
if (obstacle.x + obstacle.width < 0) {
obstacles.splice(index, 1);
score++;
}
});
// Score display
ctx.fillStyle = 'black';
ctx.font = '20px Arial';
ctx.fillText('Score: ' + score, 10, 30);
requestAnimationFrame(update);
}
// Keyboard controls
document.addEventListener('keydown', (e) => {
if (e.code === 'Space' || e.code === 'ArrowUp') {
if (!dino.jumping) {
dino.vy = -20;
dino.jumping = true;
}
}
});
// Mobile tap controls
document.addEventListener('touchstart', () => {
if (!dino.jumping) {
dino.vy = -20;
dino.jumping = true;
}
});
update();
</script>
</body>
</html>
1 comment