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 code combines HTML, CSS, and JavaScript into a single HTML file. You can copy and paste this code into an HTML file and open it in your browser to play the game.
<!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(() => {
const obstaclePosition = parseInt(obstacle.style.left);
const dinoPosition = parseInt(window.getComputedStyle(dino).getPropertyValue('bottom'));
if (obstaclePosition < 50 && obstaclePosition > 30 && dinoPosition < 40) {
clearInterval(obstacleInterval);
gameOver = true;
alert('Game Over! Your score: ' + score);
location.reload(); // Reload the game
}
if (obstaclePosition < -20) {
clearInterval(obstacleInterval);
game.removeChild(obstacle);
} else {
obstacle.style.left = obstaclePosition - 5 + 'px';
}
}, 20);
}
function startGame() {
setInterval(() => {
if (!gameOver) {
createObstacle();
}
}, 2000);
}
startGame();
</script>
</body>
</html>
.html
extension (e.g., dinosaur_game.html
).Feel free to modify the styles and functionality to enhance the game!