Skip to content

Instantly share code, notes, and snippets.

@SH20RAJ
Created June 3, 2024 18:53
Show Gist options
  • Save SH20RAJ/da8d7e35a686a5b8b764e130c777c505 to your computer and use it in GitHub Desktop.
Save SH20RAJ/da8d7e35a686a5b8b764e130c777c505 to your computer and use it in GitHub Desktop.
Dino game
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chrome Dino Game</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f7f7f7;
}
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="200"></canvas>
<script src="game.js"></script>
</body>
</html>
// game.js
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let dino = {
x: 50,
y: 150,
width: 20,
height: 20,
dy: 0,
gravity: 0.5,
jumpHeight: -10,
grounded: true
};
let obstacles = [];
let gameSpeed = 3;
let score = 0;
let gameOver = false;
document.addEventListener('keydown', (e) => {
if (e.code === 'Space' && dino.grounded) {
dino.dy = dino.jumpHeight;
dino.grounded = false;
}
});
function spawnObstacle() {
let obstacle = {
x: canvas.width,
y: 150,
width: 20,
height: 20
};
obstacles.push(obstacle);
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Dino logic
dino.dy += dino.gravity;
dino.y += dino.dy;
if (dino.y >= 150) {
dino.y = 150;
dino.dy = 0;
dino.grounded = true;
}
ctx.fillStyle = 'black';
ctx.fillRect(dino.x, dino.y, dino.width, dino.height);
// Obstacle logic
if (Math.random() < 0.01) {
spawnObstacle();
}
for (let i = 0; i < obstacles.length; i++) {
let obs = obstacles[i];
obs.x -= gameSpeed;
if (obs.x + obs.width < 0) {
obstacles.splice(i, 1);
score++;
}
ctx.fillRect(obs.x, obs.y, obs.width, obs.height);
// Collision detection
if (
dino.x < obs.x + obs.width &&
dino.x + dino.width > obs.x &&
dino.y < obs.y + obs.height &&
dino.y + dino.height > obs.y
) {
gameOver = true;
}
}
// Score display
ctx.fillStyle = 'black';
ctx.font = '20px Arial';
ctx.fillText('Score: ' + score, 10, 20);
if (!gameOver) {
requestAnimationFrame(update);
} else {
ctx.fillStyle = 'red';
ctx.fillText('Game Over', canvas.width / 2 - 50, canvas.height / 2);
}
}
update();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment