JavaScript to implement the aircraft war game

JavaScript to implement the aircraft war game

This article shares with you how to use canvas and js to implement a simple airplane war for your reference. The specific content is as follows

Preview image:

Code:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        canvas {
            display: block;
            margin: 0 auto;
            border: 1px solid #000;
        }
    </style>
</head>

<body>
    <canvas></canvas>
    <script>
        // Get the canvas element var canvas = document.getElementsByTagName('canvas')[0];
        // Get the brush var ctx = canvas.getContext('2d');
        // Canvas information var canvasParam = {
            width: 480,
            height: 852
        }
        canvas.width = canvasParam.width;
        canvas.height = canvasParam.height;

        // Initialize game status var ready = 0; // Preparing var loading = 1; // Loading var running = 2; // In game var pause = 3; // Pause var gameOver = 4; // End // Determine the current game status var gameState = ready;

        // Initialize life value var life = 3;

        // Initialize game score var score = 0;

        // background/
        // Create background image var bgSrc = new Image();
        bgSrc.src = 'img/background.png';
        // Background image information var bgParam = {
            bgSrc: bgSrc,
            x: 0,
            y: 0,
            width: 480,
            height: 852
        }

        // Constructor: background function Bg(param) {
            this.bgSrc = param.bgSrc;
            this.x = param.x;
            this.y = param.y;
            this.y1 = param.y1;
            this.width = param.width;
            this.height = param.height;

            // Alternating image coordinates this.y1 = -this.height;

            // Draw the background image this.paint = function() {
                ctx.drawImage(this.bgSrc, this.x, this.y, this.width, this.height);
                ctx.drawImage(this.bgSrc, this.x, this.y1, this.width, this.height);
            }

            // The background image moves alternately this.sport = function() {
                this.y += 5;
                this.y1 += 5;
                if (this.y >= this.height) {
                    this.y = -this.height;
                }
                if (this.y1 >= this.height) {
                    this.y1 = -this.height;
                }
            }
        }
        // Instantiate background image var bgObj = new Bg(bgParam);

        // Create the logo 
        var logoSrc = new Image();
        logoSrc.src = 'img/start.png';
        //logo information var logoParam = {
            logoSrc: logoSrc,
            x: 0,
            y: 0,
            width: 480,
            height: 852
        }

        // Constructor Logo
        function Logo(param) {
            this.logoSrc = param.logoSrc;
            this.x = param.x;
            this.y = param.y;
            this.width = param.width;
            this.height = param.height;

            // Draw the logo
            this.paint = function() {
                ctx.drawImage(this.logoObj, this.x, this.y, this.width, this.height);
            }
        }
        // Instantiate the logo object var logoObj = new Logo(logoParam);


        // Click on the canvas to enter the next stage of loading
        canvas.onclick = function() {
            if (gameState === ready) {
                gameState = loading;
            }
        }


        // Game loading phase loading 
        // Aircraft approaching // Aircraft approaching picture var loadImgArr = ['img/game_loading1.png', 'img/game_loading2.png', 'img/game_loading3.png', 'img/game_loading4.png']
            // An empty array to store the pictures of the approaching aircraft var loadingImg = [];
        // Loop to create aircraft approach pictures and store them in the array loadingImg for (var i = 0; i < loadImgArr.length; i++) {
            loadingImg[i] = new Image();
            loadingImg[i].src = loadImgArr[i];
        }

        // Aircraft approach picture information var loadingParam = {
            loadingImg: loadingImg,
            x: 0,
            width: 186,
            height: 38
        }

        // Constructor: aircraft approach information function Loading(param) {
            this.loadingImg = loadingImg;
            this.width = param.width;
            this.height = param.height;
            this.x = param.x;
            this.y = canvasParam.height - param.height;

            // Define the loading image index this.index = 0;

            // Define num to determine the number of executions of the timer this.num = 0;

            // Draw the loading image this.paint = function() {
                ctx.drawImage(this.loadingImg[this.index], this.x, this.y, this.width, this.height);
            }

            // Change the loading image this.sport = function() {
                this.num++;
                if (this.num % 5 == 0) {
                    this.index++;
                    if (this.index === this.loadingImg.length) {
                        gameState = running;
                    }
                }
            }
        }

        //Instantiate the loading aircraft object var loadingObj = new Loading(loadingParam);


        //Our plane///
        // Pictures of our aircraft in various states var heroImgs = [
                'img/hero1.png',
                'img/hero2.png',
                'img/hero1.png',
                'img/hero_blowup_n1.png',
                'img/hero_blowup_n2.png',
                'img/hero_blowup_n3.png',
                'img/hero_blowup_n4.png'
            ]
            // Create an empty array to store pictures of our aircraft in various states var heroRunning = [];
        // Loop to create our aircraft images and store them in the array heroRunning for (var i = 0; i < heroImgs.length; i++) {
            heroRunning[i] = new Image();
            heroRunning[i].src = heroImgs[i];
        }

        // Our aircraft information var heroParam = {
            haroRunning: heroRunning,
            width: 99,
            height: 124
        }

        // Our aircraft constructor function Hero(param) {
            this.heroRunning = heroRunning;
            this.x = canvasParam.width / 2 - param.width / 2;
            this.y = canvasParam.height - param.height * 1.2;
            this.width = param.width;
            this.height = param.height;

            // Our aircraft image subscript this.index = 0;
            // Determine whether the plane is hit this.down = false;

            //Interval trigger this.num = 0;

            // Draw our plane this.paint = function() {
                    ctx.drawImage(this.heroRunning[this.index], this.x, this.y, this.width, this.height);
                }
                // Alternately draw pictures of our aircraft when executing this.sport = function() {
                if (!this.down) {
                    this.num++;
                    // Every time the timer executes 3 times, our plane's flight picture will alternate if (this.num % 3 === 0) {
                        if (this.index === 0) {
                            this.index = 1;
                        } else {
                            this.index = 0;
                        }
                    }
                } else {
                    // Our plane was hit this.index++; // Picture array index + 1, display the hit picture if (this.index === this.heroRunning.length) {
                        life--; // Life value -1
                        if (life == 0) {
                            // The game state changes to over gamerState = gameOver;
                            // After the game ends, let the plane stay in the smoking state this.index = this.heroRunning.length - 1;
                        } else {
                            // Create a new our plane heroObj = new Hero(heroParam);
                        }
                    }
                }

            }

            // Create bullet interval this.bulletTime = 0;
            // Create a bullet this.newBullet = function() {
                this.bulletTime++;
                // The timer executes 3 times to create a bullet if (this.bulletTime % 2 === 0) {
                    bullets.push(new Bullet(bulletParam));
                }
            }
        }

        // Instantiate our plane var heroObj = new Hero(heroParam);

        // Bind the canvas to the move event so that our plane moves with the mouse canvas.onmousemove = function(e) {
            if (gameState === running) {
                heroObj.x = e.offsetX - heroObj.width / 2;
                heroObj.y = e.offsetY - heroObj.height / 2;
            }

        }

        //Bullet//
        var bulletImg = new Image();
        bulletImg.src = 'img/bullet1.png';

        var bulletParam = {
            bulletImg: bulletImg,
            width: 9,
            height: 21
        }

        // Constructor: Bullet function Bullet(param) {
            this.bulletImg = param.bulletImg;
            this.x = heroObj.x + heroObj.width / 2 - param.width / 2;
            this.y = heroObj.y - param.height;
            this.width = param.width;
            this.height = param.height;

            // Draw the bullet this.paint = function() {
                ctx.drawImage(this.bulletImg, this.x, this.y, this.width, this.height);
            }

            // Determine whether the bullet hits the enemy plane this.down = false;

            // Bullet movement speed this.sport = function() {
                this.y -= 50;
            }
        }

        //Magazine var bullets = [];

        // Make bullets function bulletsPaint() {
            for (var i = 0; i < bullets.length; i++) {
                bullets[i].paint();
            }
        }

        // Fire bullets function bulletsSport() {
            for (var i = 0; i < bullets.length; i++) {
                bullets[i].sport();
            }
        }

        // The bullet flies out of the screen // The bullet collides with the enemy plane function bulletsDelete() {
            for (var i = 0; i < bullets.length; i++) {
                if (bullets[i].y < -this.height || bullets[i].down) {
                    bullets.splice(i, 1);
                }
            }
        }

        //Enemy aircraft//Small enemy aircraftvar enemy1Arr = [
            'img/enemy1.png',
            'img/enemy1_down1.png',
            'img/enemy1_down2.png',
            'img/enemy1_down3.png',
            'img/enemy1_down4.png'
        ];
        var enemy1Img = [];
        for (var i = 0; i < enemy1Arr.length; i++) {
            enemy1Img[i] = new Image();
            enemy1Img[i].src = enemy1Arr[i];
        }
        //Medium enemy aircraft var enemy2Arr = [
            'img/enemy2.png',
            'img/enemy2_down1.png',
            'img/enemy2_down2.png',
            'img/enemy2_down3.png',
            'img/enemy2_down4.png'
        ];
        var enemy2Img = [];
        for (var i = 0; i < enemy2Arr.length; i++) {
            enemy2Img[i] = new Image();
            enemy2Img[i].src = enemy2Arr[i];
        }
        // Large enemy aircraft var enemy3Arr = [
            'img/enemy3_n1.png',
            'img/enemy3_n2.png',
            'img/enemy3_hit.png',
            'img/enemy3_down1.png',
            'img/enemy3_down2.png',
            'img/enemy3_down3.png',
            'img/enemy3_down4.png',
            'img/enemy3_down5.png',
            'img/enemy3_down6.png'
        ];
        var enemy3Img = [];
        for (var i = 0; i < enemy3Arr.length; i++) {
            enemy3Img[i] = new Image();
            enemy3Img[i].src = enemy3Arr[i];
        }

        // Small enemy aircraft information var enemy1Param = {
                enemyImg: enemy1Img,
                width: 57,
                height: 51,
                life: 3,
                score: 1
            }
            // Medium enemy aircraft information var enemy2Param = {
                enemyImg: enemy2Img,
                width: 69,
                height: 95,
                life: 10,
                score: 3
            }
            // Large enemy aircraft information var enemy3Param = {
            enemyImg: enemy3Img,
            width: 169,
            height: 258,
            life: 20,
            score: 10
        }

        // Constructor: enemy function Enemy(param) {
            this.enemyImg = param.enemyImg;
            this.width = param.width;
            this.height = param.height;
            this.life = param.life;
            this.score = param.score;

            this.x = Math.random() * (canvasParam.width - this.width);
            this.y = -this.height;

            // Image subscript this.index = 0;
            // Determine whether the enemy aircraft collides this.down = false;
            // Is the explosion complete this.bang = false;

            // Draw the enemy this.paint = function() {
                ctx.drawImage(this.enemyImg[this.index], this.x, this.y, this.width, this.height);
            }

            // Enemy aircraft moves this.sport = function() {
                if (!this.down) {
                    // When the current enemy aircraft is not collided this.y += 3;
                } else {
                    // The enemy's health after collision -1
                    this.life--;
                    // After the health value is -1, the collision becomes false
                    this.down = false;
                    // When the health value becomes 0, it turns into an enemy explosion picture if (this.life <= 0) {
                        this.index++;
                        this.down = true;
                        if (this.index === this.enemyImg.length) {
                            this.index = this.enemyImg.length - 1;
                            this.bang = true;
                        }
                    }

                }
            }

            // Determine whether it has been hit this.hit = function(obj) {
                return obj.x + obj.width >= this.x && obj.x <= this.x + this.width &&
                    obj.y <= this.y + this.height && obj.y + obj.height >= this.y;
            }
        }

        // Create an empty array to store enemy planes var enemies = [];

        // Randomly create small, medium and large enemy aircraft function pushEnemy() {
            var random = Math.random();
            if (random < 0.65) {
                enemies.push(new Enemy(enemy1Param));
            } else if (random < 0.9) {
                // Medium-sized aircraft enemies.push(new Enemy(enemy2Param));
            } else {
                //Large airplane enemies.push(new Enemy(enemy3Param));
            }
        }

        // Draw and move enemy objects function enemyPaint() {
            for (var i = 0; i < enemies.length; i++) {
                enemies[i].paint();
                enemies[i].sport();
            }
        }
        //Draw the enemy plane when it is paused function enemyPaint1() {
            for (var i = 0; i < enemies.length; i++) {
                enemies[i].paint();
            }
        }
        // Delete enemy planes and increase score function enemyDelete() {
            for (var i = 0; i < enemies.length; i++) {
                if (enemies[i].bang) {
                    score += enemies[i].score;
                }
                if (enemies[i].y >= canvasParam.height || enemies[i].bang) {
                    enemies.splice(i, 1);
                    // score += enemies[i].score;
                }
            }
        }


        // How to detect whether each enemy plane is hit by a bullet or our plane function checkHit() {
            for (var i = 0; i < enemies.length; i++) {
                // Bullets collide with enemy planes for (var j = 0; j < bullets.length; j++) {
                    if (enemies[i].hit(bullets[j])) {
                        enemies[i].down = true;
                        bullets[j].down = true;
                    }
                }
                // Enemy and hero
                if (enemies[i].hit(heroObj)) {
                    enemies[i].down = true;
                    heroObj.down = true;
                }
            }
        }

        // score function scoreText() {
            ctx.font = '20px bold';
            ctx.fillText('Score: ' + score, 20, 30);
            ctx.fillText('Life value: ' + life, 360, 30)
        }

        // The game pauses when the mouse moves out canvas.onmouseout = function() {
            if (gameState === running) {
                gameState = pause;
            }
        };
        // Move the mouse to start the game canvas.onmouseover = function() {
            if (gameState === pause) {
                gameState = running;
            }
        };
        //Game pause interface function pausePanit() {
            var pauseImg = new Image()
            pauseImg.src = "img/game_pause_nor.png";
            heroObj.paint();
            // Draw bullets bulletsPaint();
            // Draw the enemy enemyPaint1();
            scoreText();
            ctx.drawImage(pauseImg, 220, 420);
        }
        // Game over function gameOverText() {
            ctx.font = '50px bold';
            ctx.fillText('game over', 120, 420);
            ctx.font = '30px bold';
            ctx.fillText('Click to restart', 160, 520);
        }

        // Click event to restart the game canvas.addEventListener("click", function(e) {
            if (gameState === gameOver) {
                gameState = ready;
                loadingObj.num = 0;
                loadingObj.index = 0;
                enemies = [];
                bullets = [];
                life = 3;
                score = 0;
                heroObj.down = false;

            }
        });

        //Time interval for creating enemy aircraft var enemyNum = 0;
        // Start the timer and draw the picture setInterval(function() {
            bgObj.paint();
            bgObj.sport();

            if (gameState === ready) {
                ctx.drawImage(logoSrc, 0, 0, 480, 852);
                // logoObj.paint();

            } else if (gameState === loading) {
                loadingObj.paint();
                loadingObj.sport();
            } else if (gameState === running) {
                canvas.style.cursor = 'none';
                heroObj.paint();
                heroObj.sport();
                heroObj.newBullet();

                // Draw bullets bulletsPaint();
                bulletsSport();
                // Delete bullets bulletsDelete();

                // Draw the enemy enemyNum++;
                if (enemyNum % 20 === 0) {
                    pushEnemy();
                }

                enemyPaint();
                checkHit();
                enemyDelete();
                scoreText();
                if (life === 0) {
                    gameState = gameOver;
                }

            } else if (gameState === pause) {
                pausePanit();
            } else if (gameState === gameOver) {
                canvas.style.cursor = 'pointer';
                gameOverText();
                heroObj.paint();
            }

        }, 60)
    </script>
</body>

</html>

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • js+canvas realizes the aircraft war
  • JavaScript implements the front-end aircraft war game
  • JavaScript to implement aircraft warfare
  • Using JS to implement a small game of aircraft war
  • Native JS to implement the aircraft war game
  • js to realize the aircraft war game
  • JS object-oriented implementation of aircraft war
  • js to realize the aircraft war game
  • A complete example of writing the game "Aircraft vs. Tank" in JavaScript
  • js+css to realize the aircraft war game

<<:  Installation of CUDA10.0 and problems in Ubuntu

>>:  In-depth understanding of MySQL long transactions

Recommend

When should a website place ads?

I recently discussed "advertising" with...

Solution to forgetting mysql database password

You may have set a MySQL password just now, but f...

HTML reuse techniques

HTML reuse is a term that is rarely mentioned. Tod...

Write your HTML like this to make your code more compatible

For example, users who need screen reading softwar...

Minio lightweight object storage service installation and browser usage tutorial

Table of contents Introduction Install 1. Create ...

MySQL series 9 MySQL query cache and index

Table of contents Tutorial Series 1. MySQL Archit...

MySQL database SELECT query expression analysis

A large part of data management is searching, and...

react+antd.3x implements ip input box

This article shares the specific code of react+an...

Specific use of Mysql prepare preprocessing

Table of contents 1. Preprocessing 2. Pretreatmen...

Use nginx to configure domain name-based virtual hosts

1. What is a virtual host? Virtual hosts use spec...

Detailed explanation of gcc command usage under Linux system

Table of contents 1. Preprocessing 2. Compilation...