
Creating a Simple JavaScript Game
Here's a step-by-step guide to creating a simple JavaScript game called "Block Hopper." This game will allow players to control a character that jumps over blocks falling from the top of the screen. The player scores points by avoiding collisions with these blocks.
Step 1: Setting Up the HTML
First, create an HTML file named index.html
. This file will contain the canvas where our game will be rendered.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Block Hopper Game</title>
<style>
body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
canvas { border: 1px solid black; }
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script src="game.js"></script>
</body>
</html>
Step 2: Creating the Game Logic in JavaScript
Next, create a JavaScript file named game.js
. This file will contain all the logic for our game.
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let player; let blocks = []; let score = 0; let isJumping = false; let jumpHeight = 100; let gravity = 5;
function setup() { player = { x: 50, y: canvas.height - 60, width: 30, height: 30 }; requestAnimationFrame(gameLoop); }
function drawPlayer() { ctx.fillStyle = 'green'; ctx.fillRect(player.x, player.y, player.width, player.height); }
function createBlock() { const blockWidth = Math.random() * (100 - 20) + 20; const blockX = Math.random() * (canvas.width - blockWidth); blocks.push({ x: blockX, y: -20, width: blockWidth, height: 20 }); }
function drawBlocks() { ctx.fillStyle = 'red'; for (const block of blocks) { ctx.fillRect(block.x, block.y, block.width, block.height); block.y += gravity;
// Check for collision
if (
player.x < block.x + block.width &&
player.x + player.width > block.x &&
player.y < block.y + block.height &&
player.y + player.height > block.y
) {
alert(`Game Over! Your score was ${score}`);
document.location.reload();
}
// Remove off-screen blocks and increase score
if (block.y > canvas.height) {
score++;
blocks.splice(blocks.indexOf(block), 1);
}
}
}
function jump() { if (!isJumping) { isJumping = true; let jumpCount = jumpHeight;
const jumpInterval = setInterval(() => {
if (jumpCount > 0) {
player.y -= gravity;
jumpCount -= gravity;
} else {
clearInterval(jumpInterval);
fall();
}
}, 20);
}
}
function fall() { const fallInterval = setInterval(() => { if (player.y < canvas.height - 60) { player.y += gravity; } else { clearInterval(fallInterval); isJumping = false; } }, 20); }
function gameLoop() { ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlayer();
if (Math.random() < 0.02) createBlock(); // Create new blocks randomly
drawBlocks();
ctx.fillStyle = 'black';
ctx.font = '20px Arial';
ctx.fillText(`Score: ${score}`, canvas.width - 150, 30);
requestAnimationFrame(gameLoop);
}
// Event listener for jumping document.addEventListener('keydown', function(event) { if (event.code === 'Space') jump(); });
// Start the game setup();
Explanation of Key Components
- HTML Structure:
- The HTML sets up a simple page with a centered canvas element where the game will be drawn.
- Game Setup:
- The
setup
function initializes the player's position and starts the game loop usingrequestAnimationFrame
.
- The
- Drawing Functions:
drawPlayer
renders the player's character.drawBlocks
handles rendering falling blocks and checking for collisions with the player.
- Game Mechanics:
- The
createBlock
function generates new blocks at random positions. - The
jump
function allows the player to jump when they press the spacebar. - Collision detection checks if the player's rectangle intersects with any falling blocks.
- The
- Game Loop:
- The main loop clears the canvas and redraws everything at each frame while updating scores and handling gameplay mechanics.
- Event Handling:
- An event listener listens for key presses to trigger jumps.
This code provides a basic framework for a simple jumping game using JavaScript and HTML5 Canvas. You can expand upon this by adding features like levels or different types of obstacles as you become more comfortable with coding games in JavaScript.
Here’s your simple JavaScript game!
Authoritative Sources
- For more information on setting up games in JavaScript using HTML5 Canvas and related techniques. [Code Wizards HQ]↩
- Additional insights into building basic game engines in JavaScript can be found here. [Beng's Fort]↩


Answer Provided by www.iAsk.ai – Ask AI.
Sign up for free to save this answer and access it later
Sign up →