Generate code for a basic dinosaur game, the dinosaur game should be similar to google chrome's offline dinosaur game. Whereby, the dino jumps over blocks or cactus. After each successful jump the score increases, if it collides with the blocks, the game ends, then it displays the score upto the point of collision. Use html, css and javascript, then share the full code having combined all files in the html file.
Sure! Below is a simple implementation of a dinosaur game similar to the Google Chrome offline dinosaur game. The game is created using HTML, CSS, and JavaScript, all combined into a single HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dinosaur Game</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #f7f7f7;
}
#game {
position: relative;
width: 100%;
height: 150px;
background-color: #fff;
border: 2px solid #000;
overflow: hidden;
}
#dino {
position: absolute;
bottom: 0;
left: 50px;
width: 40px;
height: 40px;
background-color: green;
}
.obstacle {
position: absolute;
bottom: 0;
width: 20px;
height: 40px;
background-color: red;
}
#score {
position: absolute;
top: 10px;
left: 10px;
font-size: 20px;
}
</style>
</head>
<body>
<div id="game">
<div id="dino"></div>
<div id="score">Score: 0</div>
</div>
<script>
const dino = document.getElementById('dino');
const game = document.getElementById('game');
const scoreDisplay = document.getElementById('score');
let score = 0;
let isJumping = false;
let gameOver = false;
document.addEventListener('keydown', jump);
function jump() {
if (isJumping || gameOver) return;
isJumping = true;
dino.style.bottom = '80px';
setTimeout(() => {
dino.style.bottom = '0';
isJumping = false;
score++;
scoreDisplay.innerText = `Score: ${score}`;
}, 300);
}
function createObstacle() {
const obstacle = document.createElement('div');
obstacle.classList.add('obstacle');
obstacle.style.left = '100%';
game.appendChild(obstacle);
moveObstacle(obstacle);
}
function moveObstacle(obstacle) {
let obstacleInterval = setInterval(() => {
if (gameOver) {
clearInterval(obstacleInterval);
return;
}
let obstaclePosition = parseInt(window.getComputedStyle(obstacle).getPropertyValue('left'));
if (obstaclePosition < -20) {
clearInterval(obstacleInterval);
obstacle.remove();
} else {
obstacle.style.left = obstaclePosition - 5 + 'px';
}
if (obstaclePosition < 90 && obstaclePosition > 50 && !isJumping) {
gameOver = true;
clearInterval(obstacleInterval);
alert(`Game Over! Your score: ${score}`);
resetGame();
}
}, 20);
}
function resetGame() {
score = 0;
scoreDisplay.innerText = `Score: ${score}`;
gameOver = false;
const obstacles = document.querySelectorAll('.obstacle');
obstacles.forEach(obstacle => obstacle.remove());
}
setInterval(() => {
if (!gameOver) {
createObstacle();
}
}, 2000);
</script>
</body>
</html>
.html
extension (e.g., dinosaur_game.html
).