Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to code a game in JavaScript

Getting Started with Game Development in JavaScript

Welcome to the exciting world of game development! In this blog post, we will take a baby's step and create a simple classic game - Pong. Pong is a table tennis-themed arcade video game, which is a perfect starting point for beginners. You will learn the basics of how a game works and how to code one in JavaScript.

What is JavaScript?

JavaScript is a high-level, interpreted programming language that is primarily used to enhance web pages to provide for a more user-friendly experience. In simpler terms, JavaScript is like the magic wand that adds interactivity and dynamism to your websites.

Breaking Down Pong

Before we dive into coding, let's first understand the game we're about to build. Pong is a 2D game that involves two paddles and a ball. The players control the paddles, trying to hit the ball back and forth. The goal is simple: don't let the ball pass your paddle, or your opponent scores a point.

Setting Up the Game Environment

The first thing we need to do is to set up the game environment. We'll be using the HTML canvas element for rendering our game. Think of the canvas as our game's playground – it's where all the actions will take place. Here's a basic setup for our game:

<!DOCTYPE html>
<html>
<body>
    <canvas id="pongGame" width="800" height="400"></canvas>
    <script src="pong.js"></script>
</body>
</html>

In the above code, we've set the width of the canvas to 800 pixels and the height to 400 pixels, and linked it to our JavaScript file, pong.js.

Drawing on the Canvas

In Pong, we have two paddles and a ball. Let's start by drawing these on the canvas. We'll use the fillRect function, which is like a paintbrush for our canvas. This function takes four parameters: the x position, the y position, the width, and the height.

let canvas = document.getElementById("pongGame");
let context = canvas.getContext("2d");

// Draw the paddles
context.fillRect(50, 100, 10, 100);
context.fillRect(750, 100, 10, 100);

// Draw the ball
context.fillRect(400, 200, 10, 10);

Making the Paddles Move

Next, we want to make our paddles move. We can do this by redrawing the paddles at a new position every time an arrow key is pressed. For this, we'll use the keydown event and update the y position of the paddle accordingly.

let paddleSpeed = 5;
let paddle1Y = 100;
let paddle2Y = 100;

document.addEventListener('keydown', function(event) {
    switch(event.keyCode) {
        case 38:
            // Up arrow key pressed
            paddle1Y -= paddleSpeed;
            break;
        case 40:
            // Down arrow key pressed
            paddle1Y += paddleSpeed;
            break;
    }
});

Adding Ball Movement

Just like we did with the paddles, we want our ball to move as well. However, the ball movement will be automatic and it will bounce off the paddles and the top and bottom of the canvas.

let ball = {
    x: canvas.width / 2,
    y: canvas.height / 2,
    dx: 2,
    dy: 2,
    radius: 10,
};

function drawBall() {
    context.beginPath();
    context.arc(ball.x, ball.y, ball.radius, 0, Math.PI*2);
    context.fillStyle = "#0095DD";
    context.fill();
    context.closePath();
}

function updateBall() {
    ball.x += ball.dx;
    ball.y += ball.dy;

    if(ball.y + ball.dy > canvas.height-ball.radius || ball.y + ball.dy < ball.radius) {
        ball.dy = -ball.dy;
    }

    // Bounce off the paddles
    if(ball.y > paddle1Y && ball.y < paddle1Y + paddleHeight && ball.dx < 0) {
        if(ball.x - ball.radius < paddleWidth) {
            ball.dx = -ball.dx;
        }
    }
    else if(ball.y > paddle2Y && ball.y < paddle2Y + paddleHeight && ball.dx > 0) {
        if(ball.x + ball.radius > canvas.width - paddleWidth) {
            ball.dx = -ball.dx;
        }
    }
}

Wrapping Up the Game

We are almost done. We just need a way to continuously update the position of the ball and the paddles, and redraw them. We'll use the requestAnimationFrame function for this. It's like a loop that executes about 60 times per second, giving us a smooth animation.

function gameLoop() {
    // Clear the canvas
    context.clearRect(0, 0, canvas.width, canvas.height);

    // Draw the paddles and the ball
    drawPaddles();
    drawBall();

    // Move the paddles and the ball
    movePaddles();
    updateBall();

    // Call gameLoop again on the next frame
    requestAnimationFrame(gameLoop);
}

// Start the game loop
gameLoop();

The Final Thoughts

Congratulations! You just created your first game in JavaScript. This is just the beginning, there's still so much to explore and learn. You can add scores, sound effects, improve the AI for the second paddle, and so on. The sky's the limit when it comes to game development. Remember, the best way to learn programming is by doing. So keep coding, keep experimenting, and most importantly, have fun in the process.