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 :
List of articles
- Tanks war js Small game source HTML5 Tank war game code (HTML+CSS+JavaScript )
- Introduction to the game
- The design idea of the game
- One 、 Game demo
- Two 、 Code directory
- 3、 ... and 、 Code implementation
- Four 、web Front end entry to advanced ( video + Source code + Information + interview ) a full set of ( course )
- 5、 ... and 、 The source code for
- 6、 ... and 、 more HTML Final homework ( Download the finished product )
One 、 Game demo
Two 、 Code directory
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
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 !
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 !
copyright notice
author[@. code out the future],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210822224640679B.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich