search
HomeWeb Front-endFront-end Q&AHow to write a mini game in javascript

Nowadays, JavaScript has become an indispensable skill in front-end development. It can not only develop web page interactive effects, but also implement simple mini-games. This article will introduce how to write mini games in JavaScript.

1. Preparation

Create a new folder on the local computer and give it a suitable name. Create a new HTML file in the folder and add the following code at the head of the file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>JavaScript Game</title>
</head>
<body>
    
</body>
<script src="main.js"></script>
</html>

The main.js here is the JavaScript script file to be written. The one referenced here is the one that has been created. document. Create the main.js file and place it in the same folder as the HTML file. At this time we can start writing JavaScript code.

2. Write the game

  1. Create canvas

First, create a canvas element in the HTML file for rendering Game screen.

<body>
    <canvas id="myCanvas"></canvas>
</body>

In the JavaScript file, get the context of the element and save it in a variable.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

Now, we can draw graphics on the canvas canvas.

  1. Drawing the game background and other objects

Next, we need to draw the game background and other objects. Here, we can define different functions to draw different objects, such as backgrounds, balls, and baffles. Here, we first define a function to draw the background of the game.

function drawBackground() {
    ctx.fillStyle = "#3c3c3c";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
}

In this function, we first define a color value to fill the canvas background, and then use the fillRect() method to fill the entire canvas.

  1. Dynamicly update the game

Now that we have the functions for drawing various objects on the canvas, it’s time to start making the game “move”.

Here, we can use the recursive calling method of the function to continuously refresh the game screen. Here we define a function update(), and then use window.requestAnimationFrame() to call it to start refreshing the game.

function update() {
    drawBackground();

    requestAnimationFrame(update);
}

update(); // 调用 update() 函数以开始刷新游戏

In this function, we first call the drawBackground() function to draw the background of the game. Then, we used the requestAnimationFrame() function to call the update() function itself to achieve the effect of repeatedly updating the game screen.

  1. Control the moving direction of the ball

Now that we can draw objects on the canvas, we need to add operations to control the moving direction of the ball. First, we define a small ball to save to record its position information and direction information.

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

In this object, we define the starting position of the ball (that is, the center position of the canvas), dx and dy represent the initial movement direction of the ball, and radius is the radius of the ball.

In the update() function, we can add code for ball movement, collision detection and other operations.

function update() {
    drawBackground();

    // 移动球
    ball.x += ball.dx;
    ball.y += ball.dy;

    // 碰撞检测
    if(ball.x + ball.dx > canvas.width-ball.radius || ball.x + ball.dx < ball.radius) {
        ball.dx = -ball.dx;
    }
    if(ball.y + ball.dy > canvas.height-ball.radius || ball.y + ball.dy < ball.radius) {
        ball.dy = -ball.dy;
    }

    requestAnimationFrame(update);
}

update();

In this function, we first calculate the movement of the ball, and then use collision detection to detect whether the ball touches the edge of the canvas. If so, reverse the direction of the ball's movement and continue moving.

  1. Control the movement of the baffle

Now that we have controlled the direction and movement of the ball, we need to add the operation of controlling the movement of the baffle.

var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth) / 2;

function drawPaddle() {
    ctx.beginPath();
    ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();
}

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

var rightPressed = false;
var leftPressed = false;

function keyDownHandler(e) {
    if(e.keyCode == 39) {
        rightPressed = true;
    }
    else if(e.keyCode == 37) {
        leftPressed = true;
    }
}

function keyUpHandler(e) {
    if(e.keyCode == 39) {
        rightPressed = false;
    }
    else if(e.keyCode == 37) {
        leftPressed = false;
    }
}

function update() {
    drawBackground();
    drawPaddle();

    // 移动球
    ball.x += ball.dx;
    ball.y += ball.dy;

    // 控制挡板移动
    if(rightPressed && paddleX < canvas.width-paddleWidth) {
        paddleX += 7;
    }
    else if(leftPressed && paddleX > 0) {
        paddleX -= 7;
    }

    // 碰撞检测
    if(ball.x + ball.dx > canvas.width-ball.radius || ball.x + ball.dx < ball.radius) {
        ball.dx = -ball.dx;
    }
    if(ball.y + ball.dy < ball.radius) {
        ball.dy = -ball.dy;
    }
    else if(ball.y + ball.dy > canvas.height-ball.radius) {
        if(ball.x > paddleX && ball.x < paddleX + paddleWidth) {
            ball.dy = -ball.dy;
        }
        else {
            alert("游戏结束");
            document.location.reload();
            clearInterval(interval);
        }
    }

    requestAnimationFrame(update);
}

update();

Here, we first define the position of a baffle, its length and height. Then we draw the bezel through the drawPaddle() function, and then listen to the keydown and keyup events to detect whether the user presses the corresponding key to move the bezel .

At the same time, in this function, you also need to add code to detect the collision between the ball and the baffle. If the ball touches the baffle, the y direction of the ball will be directly reversed. By default, the ball will keep moving and cannot stop. The game ends when the ball completely hits the bottom of the canvas.

3. Summary

So far, we have completed the writing of a small JavaScript game. This is a simple small game example. We just completed a basic game using HTML5 canvas and JavaScript script.

Of course, these codes are just an example provided in this article and can be used as the basis for game writing. If we want to write large-scale games with more complex gameplay, we need to learn more in-depth JavaScript basics and game development skills.

If you have not been exposed to this field, then try to follow the introduction in this article and write a small game of your own!

The above is the detailed content of How to write a mini game in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is useEffect? How do you use it to perform side effects?What is useEffect? How do you use it to perform side effects?Mar 19, 2025 pm 03:58 PM

The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.

Explain the concept of lazy loading.Explain the concept of lazy loading.Mar 13, 2025 pm 07:47 PM

Lazy loading delays loading of content until needed, improving web performance and user experience by reducing initial load times and server load.

What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?Mar 18, 2025 pm 01:44 PM

Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.

How does currying work in JavaScript, and what are its benefits?How does currying work in JavaScript, and what are its benefits?Mar 18, 2025 pm 01:45 PM

The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read

How does the React reconciliation algorithm work?How does the React reconciliation algorithm work?Mar 18, 2025 pm 01:58 PM

The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159

How do you prevent default behavior in event handlers?How do you prevent default behavior in event handlers?Mar 19, 2025 pm 04:10 PM

Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.

What is useContext? How do you use it to share state between components?What is useContext? How do you use it to share state between components?Mar 19, 2025 pm 03:59 PM

The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.

What are the advantages and disadvantages of controlled and uncontrolled components?What are the advantages and disadvantages of controlled and uncontrolled components?Mar 19, 2025 pm 04:16 PM

The article discusses the advantages and disadvantages of controlled and uncontrolled components in React, focusing on aspects like predictability, performance, and use cases. It advises on factors to consider when choosing between them.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools