Home  >  Article  >  Web Front-end  >  How to write a mini game in javascript

How to write a mini game in javascript

WBOY
WBOYOriginal
2023-05-15 21:31:382662browse

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:




    
    JavaScript Game

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.


    

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