DEV Community

Cover image for How to Create a Simple Game Using JavaScript
Sanjay Naker
Sanjay Naker

Posted on

How to Create a Simple Game Using JavaScript

JavaScript isn’t just for adding interactivity to web pages — it’s also a powerful tool for building games. From simple browser-based games to more complex 2D or 3D experiences, JavaScript allows developers to bring their creative ideas to life. In this blog, we’ll guide you through the process of creating a basic game using JavaScript.

Why Use JavaScript for Game Development?

Browser Compatibility: Runs directly in any modern web browser — no extra installation required.

Easy to Learn: Beginner-friendly syntax, ideal for newcomers to programming.

Rich Libraries and Frameworks: Tools like Phaser, Three.js, and Babylon.js make game development faster and more efficient.

Cross-Platform: Games can run on desktop, mobile, or tablet without modification.

Step 1: Plan Your Game

Before coding, you should decide:

Game Type: For beginners, simple games like Snake, Tic-Tac-Toe, or Clicker Games are ideal.

Rules and Objectives: Define how players will interact with the game and how they can win or lose.

Assets: Prepare graphics, sounds, and any other media your game will need.

Step 2: Set Up the HTML Structure

Every JavaScript game starts with a basic HTML structure. For example:

<!DOCTYPE html>
<html>
<head>
    <title>Simple JavaScript Game</title>
    <style>
        canvas {
            border: 2px solid black;
            display: block;
            margin: 20px auto;
            background-color: #f0f0f0;
        }
    </style>
</head>
<body>
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    <script src="game.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Here, the element is where the game will be drawn.

Step 3: Initialize the Game in JavaScript

Create a game.js file and start with basic setup:

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

let player = { x: 50, y: 50, size: 20, color: 'blue' };

// Draw the player
function drawPlayer() {
    ctx.fillStyle = player.color;
    ctx.fillRect(player.x, player.y, player.size, player.size);
}

// Clear the canvas
function clearCanvas() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}

// Game loop
function gameLoop() {
    clearCanvas();
    drawPlayer();
    requestAnimationFrame(gameLoop);
}

gameLoop();
Enter fullscreen mode Exit fullscreen mode

This code draws a blue square on the canvas and continuously refreshes it.

Step 4: Add Player Controls

You can let players move the square using the keyboard:

document.addEventListener('keydown', function(event) {
    const step = 5;
    if (event.key === 'ArrowUp') player.y -= step;
    if (event.key === 'ArrowDown') player.y += step;
    if (event.key === 'ArrowLeft') player.x -= step;
    if (event.key === 'ArrowRight') player.x += step;
});

Enter fullscreen mode Exit fullscreen mode

Now, the player can move the square around the canvas using arrow keys.

Step 5: Add Obstacles or Enemies

To make the game challenging, you can add moving obstacles:

let enemy = { x: 200, y: 200, size: 20, color: 'red' };

function drawEnemy() {
    ctx.fillStyle = enemy.color;
    ctx.fillRect(enemy.x, enemy.y, enemy.size, enemy.size);
}

// Update game loop
function gameLoop() {
    clearCanvas();
    drawPlayer();
    drawEnemy();
    requestAnimationFrame(gameLoop);
}

Enter fullscreen mode Exit fullscreen mode

Step 6: Add Score and Game Over Logic

let score = 0;

function checkCollision() {
    if (player.x < enemy.x + enemy.size &&
        player.x + player.size > enemy.x &&
        player.y < enemy.y + enemy.size &&
        player.y + player.size > enemy.y) {
        alert('Game Over! Your score: ' + score);
        score = 0;
        player.x = 50;
        player.y = 50;
    }
}

function gameLoop() {
    clearCanvas();
    drawPlayer();
    drawEnemy();
    checkCollision();
    score++;
    requestAnimationFrame(gameLoop);
}

This code tracks the score and ends the game when the player collides with the enemy.

Step 7: Enhance Your Game

Once the basics are working, you can:

Add multiple enemies or obstacles.

Include power-ups or collectibles.

Add sound effects and background music.

Improve graphics using images instead of colored squares.

Use game frameworks like Phaser.js to simplify development.

## FAQs About JavaScript Game Development

**Q1: Can I make 3D games in JavaScript?**
Yes, using libraries like Three.js or Babylon.js.

**Q2: Is JavaScript good for mobile games?**
Yes, you can create browser-based games playable on mobile, or use frameworks like Phaser with Cordova or React Native for native apps.

**Q3: Do I need to know HTML and CSS?**
Yes, because JavaScript interacts with web elements for rendering and layout.

**_Conclusion_**

Creating a game in JavaScript is both fun and educational. You learn programming logic, event handling, and graphics rendering while making something interactive. Starting with a simple 2D game allows you to understand the core concepts, after which you can explore advanced libraries and frameworks to create complex, professional-quality games.

JavaScript makes game development accessible to anyone with a browser and a bit of creativity — the possibilities are endless!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)