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

  1. HTML Structure:
    • The HTML sets up a simple page with a centered canvas element where the game will be drawn.
  1. Game Setup:
    • The setup function initializes the player's position and starts the game loop using requestAnimationFrame.
  1. Drawing Functions:
    • drawPlayer renders the player's character.
    • drawBlocks handles rendering falling blocks and checking for collisions with the player.
  1. 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.
  1. Game Loop:
    • The main loop clears the canvas and redraws everything at each frame while updating scores and handling gameplay mechanics.
  1. 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

  1. For more information on setting up games in JavaScript using HTML5 Canvas and related techniques. [Code Wizards HQ]
  2. 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 →

Web Results

Create a game with JavaScript in 5 minutes!!
https//medium.com › geekculture › create-a-game-with-javascript-in-5-minutes-35f69c3b66e3
Create a game with JavaScript in 5 minutes!!
The game applies events driven programming hence it is easy to understand and quick to build. The game captures the speed of a player when typing and outputs ...
Basic Snake HTML and JavaScript Game
https//gist.github.com › straker › ff00b4b49669ad3dec890306d348adc4
Basic Snake HTML and JavaScript Game
Snake is a fun game to make as it doesn't require a lot of code (less than 100 lines with all comments removed). This is a basic implementation of the snake ...
I would like to make a game using javascript
https//www.sitepoint.com › community › t › i-would-like-to-make-a-game-using-javascript › 325069
I would like to make a game using javascript
Hi im incredibly new to the coding scene I just started learning this year.I need help making a game using java. Some requirements are
Ultimate Guide to JavaScript Game Development
https//www.codewizardshq.com › javascript-games
Ultimate Guide to JavaScript Game Development
How to Code a Game in JavaScript · Step 1 – Select a Code Editor · Step 2 – Build a Game Canvas · Step 3 – Code Your Player, The Hopper · Step 4 – Add Gravity to ...
How to create a game in JavaScript
https//www.quora.com › How-do-I-create-a-game-in-JavaScript
How to create a game in JavaScript
Yes! You can absolutely create games using HTML, CSS, and JavaScript. These technologies allow you to build web-based games that can run ...