current position:Home>100 lines of JS code to achieve tank war JS game source code HTML5 tank war game code (HTML + CSS + JavaScript)

100 lines of JS code to achieve tank war JS game source code HTML5 tank war game code (HTML + CSS + JavaScript)

2021-08-22 22:46:42 @. code out the future

Tanks war js Small game source HTML5 Tank war game code (HTML+CSS+JavaScript )

HTML5 Tank war webpage games , Perfectly restore the effect of bully learning machine , With the theme of tank fighting and defending the base , It belongs to strategic games .

Introduction to the game

Operation instructions : : The player 1:wasd Top left bottom right ,space Shooting ; The player 2: Direction key ,enter Shooting .n The next level ,p Last pass .

The design idea of the game

1、 There must be an operational area , There are canvas Can help us solve it .
2、 Have tanks , Include your own 、 Of the enemy .
3、 To have bullets , Include your own 、 Of the enemy .
4、 There must be a bomb .
5、 My tank needs to be able to fire bullets with the push of a button , Enemy tanks should be able to fire bullets continuously and automatically .
6、 My bullet will disappear when it hits the enemy , At the same time, the enemy exploded and disappeared , No more bullets .
The above is a simple idea of game design , This is the preliminary design , Next, analyze the detailed design process with code :

One 、 Game demo

 Insert picture description here
 Insert picture description here

Two 、 Code directory

 Insert picture description here

3、 ... and 、 Code implementation

<!-- * @Author: your name * @Date: 2021-08-09 13:54:49 * @LastEditTime: 2021-08-09 13:55:38 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: \04a1814eae5f272fc467de30f227ca6d\index.html -->
<!DOCTYPE html>
<html lang="zh" class="no-js demo-1">

<head>
    <title> Tanks war js Small game source  HTML5 Tank war game code  </title>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="js/jquery.min.js"></script>
    <script src="js/Helper.js"></script>
    <script src="js/keyboard.js"></script>
    <script src="js/const.js"></script>
    <script src="js/level.js"></script>
    <script src="js/crackAnimation.js"></script>
    <script src="js/prop.js"></script>
    <script src="js/bullet.js"></script>
    <script src="js/tank.js"></script>
    <script src="js/num.js"></script>
    <script src="js/menu.js"></script>
    <script src="js/map.js"></script>
    <script src="js/Collision.js"></script>
    <script src="js/stage.js"></script>
    <script src="js/main.js"></script>
    <style type="text/css"> #canvasDiv canvas {
       position: absolute; } #canvasDiv {
       position: absolute; left: 30%; } </style>
</head>
<body>
    <div class="container">
        <center>

            <head>
                <h3> Operation instructions : The player 1:wasd Top left bottom right ,space Shooting ; The player 2: Direction key ,enter Shooting .n The next level ,p Last pass .</h3>
            </head>
        </center>
        <div class="main clearfix">
            <div id="canvasDiv">
                <canvas id="wallCanvas"></canvas>
                <canvas id="tankCanvas"></canvas>
                <canvas id="grassCanvas"></canvas>
                <canvas id="overCanvas"></canvas>
                <canvas id="stageCanvas"></canvas>
            </div>
        </div>
    </div>
</body>
</html>

1. Draw a bullet

1. collision detection ,
2. Critical detection ,
3. Determine whether the bullet has collided with other bullets
4. Whether to hit the tank

var Bullet = function(context, owner, type, dir) {
    
    this.ctx = context;
    this.x = 0;
    this.y = 0;
    this.owner = owner; // The owner of the bullet 
    this.type = type; //1、 The player  2、 The enemy 
    /** *  collision detection  */
    this.isHit = function() {
    
        if (this.isDestroyed) {
    
            return;
        }
        // Critical detection 
        if (this.x < map.offsetX) {
    
            this.x = map.offsetX;
            this.hit = true;
        } else if (this.x > map.offsetX + map.mapWidth - this.size) {
    
            this.x = map.offsetX + map.mapWidth - this.size;
            this.hit = true;
        }
        if (this.y < map.offsetY) {
    
            this.y = map.offsetY;
            this.hit = true;
        } else if (this.y > map.offsetY + map.mapHeight - this.size) {
    
            this.y = map.offsetY + map.mapHeight - this.size;
            this.hit = true;
        }
        // Whether the bullet collided with other bullets 
        if (!this.hit) {
    
            if (bulletArray != null && bulletArray.length > 0) {
    
                for (var i = 0; i < bulletArray.length; i++) {
    
                    if (bulletArray[i] != this && this.owner.isAI != bulletArray[i].owner.isAI && bulletArray[i].hit == false && CheckIntersect(bulletArray[i], this, 0)) {
    
                        this.hit = true;
                        bulletArray[i].hit = true;
                        break;
                    }
                }
            }
        }

        if (!this.hit) {
    
            // Map detection 
            if (bulletMapCollision(this, map)) {
    
                this.hit = true;
            }
            // Whether to hit the tank 
            if (this.type == BULLET_TYPE_PLAYER) {
    
                if (enemyArray != null || enemyArray.length > 0) {
    
                    for (var i = 0; i < enemyArray.length; i++) {
    
                        var enemyObj = enemyArray[i];
                        if (!enemyObj.isDestroyed && CheckIntersect(this, enemyObj, 0)) {
    
                            CheckIntersect(this, enemyObj, 0);
                            if (enemyObj.lives > 1) {
    
                                enemyObj.lives--;
                            } else {
    
                                enemyObj.distroy();
                            }
                            this.hit = true;
                            break;
                        }
                    }
                }
            }

2. Detect collision

1. testing 2 Whether an object collides
2. The tank collided with the map block
3. The collision between the bullet and the map block

/** *  testing 2 Whether an object collides  * @param object1  object 1 * @param object2  object 2 * @param overlap  Allowed overlap size  * @returns {Boolean}  If there's a collision , return true */
function CheckIntersect(object1, object2, overlap) {
    
    // x- Axis  x- Axis 
    // A1------>B1 C1 A2------>B2 C2
    // +--------+ ^ +--------+ ^
    // | object1| | y- Axis  | object2| | y- Axis 
    // | | | | | |
    // +--------+ D1 +--------+ D2
    //
    //overlap Are overlapping area values 
    A1 = object1.x + overlap;
    B1 = object1.x + object1.size - overlap;
    C1 = object1.y + overlap;
    D1 = object1.y + object1.size - overlap;

    A2 = object2.x + overlap;
    B2 = object2.x + object2.size - overlap;
    C2 = object2.y + overlap;
    D2 = object2.y + object2.size - overlap;

    // If they were x- The axes overlap 
    if (A1 >= A2 && A1 <= B2 ||
        B1 >= A2 && B1 <= B2) {
    
        // Judge y- The axes overlap 
        if (C1 >= C2 && C1 <= D2 || D1 >= C2 && D1 <= D2) {
    
            return true;
        }
    }
    return false;
}

/** *  The tank collided with the map block  * @param tank  Tank object  * @param mapobj  Map object  * @returns {Boolean}  If there is a collision , return true */
function tankMapCollision(tank, mapobj) {
    
    // Movement detection , Record the last movement direction , Judge by direction +-overlap,
    var tileNum = 0; // Need to be tested tile Count 
    var rowIndex = 0; //map Row index in 
    var colIndex = 0; //map The column index in 
    var overlap = 3; // Allowed overlap size 
    // according to tank Of x、y To calculate the map Medium row and col
    if (tank.dir == UP) {
    
        rowIndex = parseInt((tank.tempY + overlap - mapobj.offsetY) / mapobj.tileSize);
        colIndex = parseInt((tank.tempX + overlap - mapobj.offsetX) / mapobj.tileSize);
    } else if (tank.dir == DOWN) {
    
        // Down , namely dir==1 When , The calculation of the row index requires +tank.Height
        rowIndex = parseInt((tank.tempY - overlap - mapobj.offsetY + tank.size) / mapobj.tileSize);
        colIndex = parseInt((tank.tempX + overlap - mapobj.offsetX) / mapobj.tileSize);
    } else if (tank.dir == LEFT) {
    
        rowIndex = parseInt((tank.tempY + overlap - mapobj.offsetY) / mapobj.tileSize);
        colIndex = parseInt((tank.tempX + overlap - mapobj.offsetX) / mapobj.tileSize);
    } else if (tank.dir == RIGHT) {
    
        rowIndex = parseInt((tank.tempY + overlap - mapobj.offsetY) / mapobj.tileSize);
        // towards the right , namely dir==3 When , The calculation of column index requires +tank.Height
        colIndex = parseInt((tank.tempX - overlap - mapobj.offsetX + tank.size) / mapobj.tileSize);
    }
    if (rowIndex >= mapobj.HTileCount || rowIndex < 0 || colIndex >= mapobj.wTileCount || colIndex < 0) {
    
        return true;
    }
    if (tank.dir == UP || tank.dir == DOWN) {
    
        var tempWidth = parseInt(tank.tempX - map.offsetX - (colIndex) * mapobj.tileSize + tank.size - overlap); // Remove the overlap 
        if (tempWidth % mapobj.tileSize == 0) {
    
            tileNum = parseInt(tempWidth / mapobj.tileSize);
        } else {
    
            tileNum = parseInt(tempWidth / mapobj.tileSize) + 1;
        }
        for (var i = 0; i < tileNum && colIndex + i < mapobj.wTileCount; i++) {
    
            var mapContent = mapobj.mapLevel[rowIndex][colIndex + i];
            if (mapContent == WALL || mapContent == GRID || mapContent == WATER || mapContent == HOME || mapContent == ANOTHREHOME) {
    
                if (tank.dir == UP) {
    
                    tank.y = mapobj.offsetY + rowIndex * mapobj.tileSize + mapobj.tileSize - overlap;
                } else if (tank.dir == DOWN) {
    
                    tank.y = mapobj.offsetY + rowIndex * mapobj.tileSize - tank.size + overlap;
                }
                return true;
            }
        }
    }

/** *  The collision between the bullet and the map block  * @param bullet  The target of the bullet  * @param mapobj  Map object  */
function bulletMapCollision(bullet, mapobj) {
    
    var tileNum = 0; // Need to be tested tile Count 
    var rowIndex = 0; //map Row index in 
    var colIndex = 0; //map The column index in 
    var mapChangeIndex = []; //map Index array to be updated in 
    var result = false; // Collision or not 
    // according to bullet Of x、y To calculate the map Medium row and col
    if (bullet.dir == UP) {
    
        rowIndex = parseInt((bullet.y - mapobj.offsetY) / mapobj.tileSize);
        colIndex = parseInt((bullet.x - mapobj.offsetX) / mapobj.tileSize);
    } else if (bullet.dir == DOWN) {
    
        // Down , namely dir==1 When , The calculation of the row index requires +bullet.Height
        rowIndex = parseInt((bullet.y - mapobj.offsetY + bullet.size) / mapobj.tileSize);
        colIndex = parseInt((bullet.x - mapobj.offsetX) / mapobj.tileSize);
    } else if (bullet.dir == LEFT) {
    
        rowIndex = parseInt((bullet.y - mapobj.offsetY) / mapobj.tileSize);
        colIndex = parseInt((bullet.x - mapobj.offsetX) / mapobj.tileSize);
    } else if (bullet.dir == RIGHT) {
    
        rowIndex = parseInt((bullet.y - mapobj.offsetY) / mapobj.tileSize);
        // towards the right , namely dir==3 When , The calculation of column index requires +bullet.Height
        colIndex = parseInt((bullet.x - mapobj.offsetX + bullet.size) / mapobj.tileSize);
    }
    if (rowIndex >= mapobj.HTileCount || rowIndex < 0 || colIndex >= mapobj.wTileCount || colIndex < 0) {
    
        return true;
    }

    if (bullet.dir == UP || bullet.dir == DOWN) {
    
        var tempWidth = parseInt(bullet.x - map.offsetX - (colIndex) * mapobj.tileSize + bullet.size);
        if (tempWidth % mapobj.tileSize == 0) {
    
            tileNum = parseInt(tempWidth / mapobj.tileSize);
        } else {
    
            tileNum = parseInt(tempWidth / mapobj.tileSize) + 1;
        }
        for (var i = 0; i < tileNum && colIndex + i < mapobj.wTileCount; i++) {
    
            var mapContent = mapobj.mapLevel[rowIndex][colIndex + i];
            if (mapContent == WALL || mapContent == GRID || mapContent == HOME || mapContent == ANOTHREHOME) {
    
                //bullet.distroy();
                result = true;
                if (mapContent == WALL) {
    
                    // The wall was knocked down 
                    mapChangeIndex.push([rowIndex, colIndex + i]);
                } else if (mapContent == GRID) {
    

                } else {
    
                    isGameOver = true;
                    break;
                }
            }
        }
    }
    // Update map 
    map.updateMap(mapChangeIndex, 0);
    return result;
}

3. Draw menu

1. Draw menu
2. Draw a selection of tanks
3. Painting background
4. Draw a selection of tanks

/** *  Game start menu  **/

var Menu = function(context) {
    
    this.ctx = context;
    this.x = 0;
    this.y = SCREEN_HEIGHT;
    this.selectTank = new SelectTank();
    this.playNum = 1;
    this.times = 0;

    /** *  Draw menu  */
    this.draw = function() {
    
        this.times++;
        var temp = 0;
        if (parseInt(this.times / 6) % 2 == 0) {
    
            temp = 0;
        } else {
    
            temp = this.selectTank.size;
        }
        if (this.y <= 0) {
    
            this.y = 0;
        } else {
    
            this.y -= 5;
        }
        this.ctx.clearRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        this.ctx.save();
        // Painting background 
        this.ctx.drawImage(MENU_IMAGE, this.x, this.y);
        // Draw a selection of tanks 
        this.ctx.drawImage(RESOURCE_IMAGE, POS["selectTank"][0], POS["selectTank"][1] + temp, this.selectTank.size, this.selectTank.size,
            this.selectTank.x, this.y + this.selectTank.ys[this.playNum - 1], this.selectTank.size, this.selectTank.size);
        this.ctx.restore();
    };

    /** *  Select the tank to move up and down  */
    this.next = function(n) {
    
        this.playNum += n;
        if (this.playNum > 2) {
    
            this.playNum = 1;
        } else if (this.playNum < 1) {
    
            this.playNum = 2;
        }
    };
};

4. Drawing tanks

1. Tank base class
2. Critical detection
3. collision detection
4. Map detection

/** *  Tank base class  * @returns */
var Tank = function() {
    
    this.x = 0;
    this.y = 0;
    this.size = 32; // The size of the tank 
    this.dir = UP; // Direction 0: On  1: Next  2: Left 3: Right 
    this.speed = 1; // The speed of the tank 
    this.frame = 0; // Control the time when enemy tanks change direction 
    this.hit = false; // Whether they hit a wall or a tank 
    this.isAI = false; // Whether to automatically 
    this.isShooting = false; // Whether the bullet is running 
    this.bullet = null; // The bullet 
    this.shootRate = 0.6; // The probability of shooting 
    this.isDestroyed = false;
    this.tempX = 0;
    this.tempY = 0;
    /** *  collision detection  */
    this.isHit = function() {
    
        // Critical detection 
        if (this.dir == LEFT) {
    
            if (this.x <= map.offsetX) {
    
                this.x = map.offsetX;
                this.hit = true;
            }
        } else if (this.dir == RIGHT) {
    
            if (this.x >= map.offsetX + map.mapWidth - this.size) {
    
                this.x = map.offsetX + map.mapWidth - this.size;
                this.hit = true;
            }
        } else if (this.dir == UP) {
    
            if (this.y <= map.offsetY) {
    
                this.y = map.offsetY;
                this.hit = true;
            }
        } else if (this.dir == DOWN) {
    
            if (this.y >= map.offsetY + map.mapHeight - this.size) {
    
                this.y = map.offsetY + map.mapHeight - this.size;
                this.hit = true;
            }
        }
        if (!this.hit) {
    
            // Map detection 
            if (tankMapCollision(this, map)) {
    
                this.hit = true;
            }
        }
    
    /** *  Shooting  */
    this.shoot = function(type) {
    
        if (this.isAI && emenyStopTime > 0) {
    
            return;
        }
        if (this.isShooting) {
    
            return;
        } else {
    
            var tempX = this.x;
            var tempY = this.y;
            this.bullet = new Bullet(this.ctx, this, type, this.dir);
            if (this.dir == UP) {
    
                tempX = this.x + parseInt(this.size / 2) - parseInt(this.bullet.size / 2);
                tempY = this.y - this.bullet.size;
            } else if (this.dir == DOWN) {
    
                tempX = this.x + parseInt(this.size / 2) - parseInt(this.bullet.size / 2);
                tempY = this.y + this.size;
            } else if (this.dir == LEFT) {
    
                tempX = this.x - this.bullet.size;
                tempY = this.y + parseInt(this.size / 2) - parseInt(this.bullet.size / 2);
            } else if (this.dir == RIGHT) {
    
                tempX = this.x + this.size;
                tempY = this.y + parseInt(this.size / 2) - parseInt(this.bullet.size / 2);
            }
    };

    /** *  The tank was destroyed  */
    this.distroy = function() {
    
        this.isDestroyed = true;
        crackArray.push(new CrackAnimation(CRACK_TYPE_TANK, this.ctx, this));
        TANK_DESTROY_AUDIO.play();
    };
};

/** *  Player tank  * @param context  Draw the canvas of the tank  * @returns */
var PlayTank = function(context) {
    
    this.ctx = context;
    this.lives = 3; // Health value 
    this.isProtected = true; // Is it protected 
    this.protectedTime = 500; // Protection time 
    this.offsetX = 0; // tanks 2 With tanks 1 Distance of 
    this.speed = 2; // The speed of the tank 

    this.draw = function() {
    
        this.hit = false;
        this.ctx.drawImage(RESOURCE_IMAGE, POS["player"][0] + this.offsetX + this.dir * this.size, POS["player"][1], this.size, this.size, this.x, this.y, this.size, this.size);
        if (this.isProtected) {
    
            var temp = parseInt((500 - this.protectedTime) / 5) % 2;
            this.ctx.drawImage(RESOURCE_IMAGE, POS["protected"][0], POS["protected"][1] + 32 * temp, 32, 32, this.x, this.y, 32, 32);
            this.protectedTime--;
            if (this.protectedTime == 0) {
    
                this.isProtected = false;
            }
        }

    };

};
EnemyOne.prototype = new Tank();

Four 、web Front end entry to advanced ( video + Source code + Information + interview ) a full set of ( course )

web front end Zero basis - Entry to advanced ( video + Source code + Development software + Learning materials + Interview questions ) a full set of ( course )
Suitable for children's shoes from entry to advanced ~ send 1000 set HTML+CSS+JavaScript Template website
 Insert picture description here


5、 ... and 、 The source code for

* ~ Pay attention to me , Like the blog ~ Every day brings you knowledge !

*1. See here, just [ give the thumbs-up + Praise + Collection ] Three even Support me , Yours 「 give the thumbs-up , Praise , Collection 」 It's the driving force of my creation .

* 2. Pay attention to me ~ Take you to study every day : Various front-end plug-ins 、3D Cool effect 、 Pictures show 、 Text effect 、 And the whole station template 、 College graduates HTML Templates 、 Final assignment template 、 etc. ! 「 There are a lot of front end developer , To discuss front end Node knowledge , learn from each other 」!

*3. We can learn from each other about the above technical issues , can Focus on ↓ Male Z Number Get more source code !

 Insert picture description here

6、 ... and 、 more HTML Final homework ( Download the finished product )

>>> Poke me >>> Click to enter 200 For example, the final assignment

200 Multiple cases HTML5 Final assessment big homework source code contain personal 、 food 、 company 、 School 、 tourism 、 Online retailers 、 Pets 、 Electrical appliances 、 The tea 、 Home Furnishing 、 The hotel 、 dance 、 Comic 、 star 、 clothing 、 sports 、 cosmetics 、 logistics 、 Environmental protection 、 Books 、 Wedding dress 、 military 、 game 、 festival 、 To give up smoking 、 The movie 、 Photography 、 Culture 、 hometown 、 flower 、 gift 、 automobile 、 other It can meet the web design needs of College Students' Web homework , You can download what you like !
 Insert picture description here
 Insert picture description here

copyright notice
author[@. code out the future],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210822224640679B.html

Random recommended