Creating an advanced clone of Chrome's Dinosaur game involves using HTML5 Canvas for rendering graphics, CSS for styling, and JavaScript for game logic and physics. Below is a complete example that includes enhanced graphics and physics to create a more engaging and polished game experience.
Project Structure
index.html: The main HTML file that sets up the canvas and includes the necessary scripts and styles.
styles.css: Contains styles for the canvas and overall page layout.
script.js: Contains all the game logic, including rendering, physics, collision detection, and game loop.
- Assets: Images for the dinosaur, obstacles, and background. You can replace the placeholder URLs with your own assets for better graphics.
Step 1: Setting Up the HTML
Create an index.html file with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Dinosaur Game Clone</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script src="script.js"></script>
</body>
</html>
Step 2: Styling with CSS
Create a styles.css file to style the canvas and ensure it's centered on the page:
/* styles.css */
body {
margin: 0;
padding: 0;
background-color: #f0f0f0;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#gameCanvas {
background-color: #ffffff;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
}
Step 3: Implementing Game Logic with JavaScript
Create a script.js file and add the following code. This script sets up the game canvas, loads assets, defines game objects (like the dinosaur and obstacles), handles user input, and runs the game loop with physics and collision detection.
// script.js
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const GAME_WIDTH = 800;
const GAME_HEIGHT = 400;
canvas.width = GAME_WIDTH;
canvas.height = GAME_HEIGHT;
// Game Variables
let gameSpeed = 6;
let gravity = 0.6;
let score = 0;
let gameOver = false;
// Load Images
const dinoImg = new Image();
dinoImg.src = 'https://i.imgur.com/OdL0XPt.png'; // Placeholder Dinosaur Image
const cactusImg = new Image();
cactusImg.src = 'https://i.imgur.com/DSyV3YZ.png'; // Placeholder Cactus Image
const birdImg = new Image();
birdImg.src = 'https://i.imgur.com/6M7thvH.png'; // Placeholder Bird Image
const bgImg = new Image();
bgImg.src = 'https://i.imgur.com/3eJqVbN.png'; // Placeholder Background Image
// Classes
class Dino {
constructor() {
this.x = 50;
this.y = GAME_HEIGHT - 100;
this.width = 50;
this.height = 50;
this.velocityY = 0;
this.gravity = gravity;
this.jumpStrength = 15;
this.isJumping = false;
this.isDuck = false;
}
draw() {
if (this.isDuck) {
// Draw ducking dinosaur, replace with duck image if available
ctx.drawImage(dinoImg, this.x, this.y + 20, this.width, this.height - 20);
} else {
ctx.drawImage(dinoImg, this.x, this.y, this.width, this.height);
}
}
update() {
// Apply gravity
if (this.isJumping) {
this.velocityY -= this.gravity;
this.y -= this.velocityY;
// Check if dinosaur has landed
if (this.y >= GAME_HEIGHT - 100) {
this.y = GAME_HEIGHT - 100;
this.isJumping = false;
this.velocityY = 0;
}
}
// Reduce gravity over time for smoother jump
if (this.velocityY > 0) {
this.velocityY *= 0.9;
}
}
jump() {
if (!this.isJumping) {
this.isJumping = true;
this.velocityY = this.jumpStrength;
}
}
duck() {
this.isDuck = true;
}
standUp() {
this.isDuck = false;
}
getBounds() {
return {
left: this.x,
right: this.x + this.width,
top: this.y,
bottom: this.y + this.height
};
}
}
class Cactus {
constructor() {
this.x = GAME_WIDTH;
this.y = GAME_HEIGHT - 100;
this.width = 40;
this.height = 60;
this.speed = gameSpeed;
}
draw() {
ctx.drawImage(cactusImg, this.x, this.y, this.width, this.height);
}
update() {
this.x -= this.speed;
}
offScreen() {
return this.x + this.width < 0;
}
getBounds() {
return {
left: this.x,
right: this.x + this.width,
top: this.y,
bottom: this.y + this.height
};
}
}
class Bird {
constructor() {
this.x = GAME_WIDTH;
this.y = Math.random() * (GAME_HEIGHT - 200) + 50;
this.width = 50;
this.height = 40;
this.speed = gameSpeed + 2;
this.direction = 1; // 1: right wing up, -1: left wing up
this.angle = 0;
}
draw() {
ctx.save();
ctx.translate(this.x + this.width / 2, this.y + this.height / 2);
ctx.rotate(this.angle);
ctx.drawImage(birdImg, -this.width / 2, -this.height / 2, this.width, this.height);
ctx.restore();
}
update() {
this.x -= this.speed;
// Wing flapping
this.angle += 0.1 * this.direction;
if (this.angle > 0.3 || this.angle < -0.3) {
this.direction *= -1;
}
}
offScreen() {
return this.x + this.width < 0;
}
getBounds() {
return {
left: this.x,
right: this.x + this.width,
top: this.y,
bottom: this.y + this.height
};
}
}
class ObstacleManager {
constructor() {
this.obstacles = [];
this.timer = 0;
this.interval = 150; // Controls how often obstacles spawn
}
update() {
this.timer++;
if (this.timer > this.interval) {
const random = Math.random();
if (random < 0.7) {
this.obstacles.push(new Cactus());
} else {
this.obstacles.push(new Bird());
}
this.timer = 0;
// Optionally randomize interval
this.interval = 100 + Math.random() * 200;
}
this.obstacles.forEach((obstacle, index) => {
obstacle.update();
if (obstacle.offScreen()) {
this.obstacles.splice(index, 1);
score += 10;
}
});
}
draw() {
this.obstacles.forEach(obstacle => obstacle.draw());
}
checkCollision(dino) {
for (let obstacle of this.obstacles) {
const d = dino.getBounds();
const o = obstacle.getBounds();
if (
d.right > o.left &&
d.left < o.right &&
d.bottom > o.top &&
d.top < o.bottom
) {
return true;
}
}
return false;
}
}
class Background {
constructor() {
this.x = 0;
this.y = 0;
this.speed = gameSpeed;
}
draw() {
ctx.drawImage(bgImg, this.x, this.y, GAME_WIDTH, GAME_HEIGHT);
ctx.drawImage(bgImg, this.x + GAME_WIDTH, this.y, GAME_WIDTH, GAME_HEIGHT);
}
update() {
this.x -= this.speed;
if (this.x <= -GAME_WIDTH) {
this.x = 0;
}
}
}
const dino = new Dino();
const obstacleManager = new ObstacleManager();
const background = new Background();
// Input Handling
document.addEventListener('keydown', function(e) {
if (e.code === 'Space' || e.code === 'ArrowUp') {
dino.jump();
}
if (e.code === 'ArrowDown') {
dino.duck();
}
});
document.addEventListener('keyup', function(e) {
if (e.code === 'ArrowDown') {
dino.standUp();
}
});
// Scoring
function drawScore() {
ctx.fillStyle = '#000';
ctx.font = '20px Arial';
ctx.fillText(`Score: ${score}`, GAME_WIDTH - 150, 50);
}
// Game Over Screen
function displayGameOver() {
ctx.fillStyle = 'rgba(0,0,0,0.5)';
ctx.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
ctx.fillStyle = '#fff';
ctx.font = '40px Arial';
ctx.textAlign = 'center';
ctx.fillText('Game Over', GAME_WIDTH / 2, GAME_HEIGHT / 2 - 20);
ctx.font = '20px Arial';
ctx.fillText(`Score: ${score}`, GAME_WIDTH / 2, GAME_HEIGHT / 2 + 20);
ctx.font = '16px Arial';
ctx.fillText('Press F5 to Restart', GAME_WIDTH / 2, GAME_HEIGHT / 2 + 50);
}
// Game Loop
function gameLoop() {
if (gameOver) {
displayGameOver();
return;
}
ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
// Update and draw background
background.update();
background.draw();
// Update and draw dinosaur
dino.update();
dino.draw();
// Update and draw obstacles
obstacleManager.update();
obstacleManager.draw();
// Check for collisions
if (obstacleManager.checkCollision(dino)) {
gameOver = true;
}
// Draw score
drawScore();
requestAnimationFrame(gameLoop);
}
// Start the game once images are loaded
window.onload = function() {
Promise.all([
new Promise(resolve => dinoImg.onload = resolve),
new Promise(resolve => cactusImg.onload = resolve),
new Promise(resolve => birdImg.onload = resolve),
new Promise(resolve => bgImg.onload = resolve)
]).then(() => {
gameLoop();
});
};
Step 4: Enhancing Graphics and Physics
-
Advanced Graphics:
- Sprite Animations: Replace static images with sprite sheets to animate the dinosaur and obstacles (e.g., flapping wings for birds, running motion for the dinosaur).
- Parallax Scrolling: Implement multiple background layers moving at different speeds to create a depth effect.
- Particle Effects: Add particles for dust when the dinosaur jumps or lands, or when obstacles are hit.
-
Improved Physics:
- Variable Jump Heights: Make the jump height depend on how long the jump key is pressed.
- Collision Precision: Use more precise collision detection (e.g., pixel-perfect or bounding circles).
- Gravity Variations: Adjust gravity for different game states or power-ups.
-
Additional Features:
- Power-ups: Introduce items that grant temporary abilities like invincibility, speed boosts, or double points.
- Multiple Obstacles: Include a variety of obstacles with different behaviors and patterns.
- Sound Effects and Music: Add background music and sound effects for jumping, collisions, and scoring.
Example Enhancement: Parallax Background
To implement a parallax background, you can create multiple background instances moving at different speeds.
class BackgroundLayer {
constructor(image, speedModifier) {
this.x = 0;
this.y = 0;
this.width = GAME_WIDTH;
this.height = GAME_HEIGHT;
this.image = image;
this.speedModifier = speedModifier;
this.speed = gameSpeed * this.speedModifier;
}
draw() {
ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
ctx.drawImage(this.image, this.x + this.width, this.y, this.width, this.height);
}
update() {
this.speed = gameSpeed * this.speedModifier;
this.x -= this.speed;
if (this.x <= -this.width) {
this.x = 0;
}
}
}
// Load additional background layers
const bgLayer1 = new Image();
bgLayer1.src = 'https://i.imgur.com/3eJqVbN.png'; // Foreground layer
const bgLayer2 = new Image();
bgLayer2.src = 'https://i.imgur.com/3eJqVbN.png'; // Midground layer, replace with different image
const bgLayer3 = new Image();
bgLayer3.src = 'https://i.imgur.com/3eJqVbN.png'; // Background layer, replace with different image
const backgroundLayers = [];
bgLayer1.onload = () => {
backgroundLayers.push(new BackgroundLayer(bgLayer1, 1));
bgLayer2.onload = () => {
backgroundLayers.push(new BackgroundLayer(bgLayer2, 0.5));
bgLayer3.onload = () => {
backgroundLayers.push(new BackgroundLayer(bgLayer3, 0.2));
gameLoop();
};
};
};
// Update and draw background layers in the game loop
function gameLoop() {
if (gameOver) {
displayGameOver();
return;
}
ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
// Update and draw background layers
backgroundLayers.forEach(layer => {
layer.update();
layer.draw();
});
// Update and draw dinosaur
dino.update();
dino.draw();
// Update and draw obstacles
obstacleManager.update();
obstacleManager.draw();
// Check for collisions
if (obstacleManager.checkCollision(dino)) {
gameOver = true;
}
// Draw score
drawScore();
requestAnimationFrame(gameLoop);
}
Note: Replace the placeholder image URLs with distinct images for each background layer to achieve a true parallax effect.
Final Notes
- Asset Optimization: Ensure that all images are optimized for web use to reduce loading times and improve performance.
- Responsive Design: To make the game responsive, adjust the canvas size based on the viewport and scale game elements accordingly.
- Testing: Test the game across different browsers and devices to ensure compatibility and smooth performance.
- Enhancements: Consider integrating game frameworks like Phaser.js for more advanced features and easier management of game states and assets.
This implementation provides a solid foundation for an advanced Dinosaur game clone. You can further enhance it by adding more features, improving graphics, and refining the physics to create a truly polished game experience.