Home Web Front-end JS Tutorial Creating a full record of tank battles with javascript (2)_javascript skills

Creating a full record of tank battles with javascript (2)_javascript skills

May 16, 2016 pm 04:30 PM
javascript object-oriented

2. Improve the map

Our map has obstacles such as open spaces, walls, steel, grass, water, and headquarters. We can design all of these as objects.

2.1 Create obstacle object group

The object group stores objects on various maps. We use the properties of the objects to determine whether the objects can be passed through or attacked.

Barrier.js:

Copy code The code is as follows:

// Obstacle base class object, inherited from TankObject
Barrier = function () {
This.DefenVal = 1; // Defense power
This.CanBeAttacked = true; // Whether it can be attacked
}
Barrier.prototype = new TankObject();
// Wall
WallB = function () { }
WallB.prototype = new Barrier();
// Open space
EmptyB = function () {
This.CanAcross = true; // Can be passed through
}
EmptyB.prototype = new Barrier();
// River
RiverB = function () {
This.DefenVal = 0;
This.CanBeAttacked = false; // The members of the object are taken first, and those inherited from the parent class will be overwritten.
}
RiverB.prototype = new Barrier();
// Steel
SteelB = function () {
This.DefenVal = 3;
}
SteelB.prototype = new Barrier();
// Grass object
TodB = function () {
This.CanBeAttacked = false;
This.DefenVal = 0;
This.CanAcross = true;
}
TodB.prototype = new Barrier();
//Headquarters
PodiumB = function () {
This.DefenVal = 5;
}
PodiumB.prototype = new Barrier();

2.2 Data written to the map.

Add the following code in Common.js:

Copy code The code is as follows:

//Map element type enumeration
/*
0: Open space
1: Wall
2: Steel
3: Bushes
4:River
5: Headquarters
*/
var EnumMapCellType = {
Empty: "0"
, Wall: "1"
, Steel: "2"
, Tod: "3"
, River: "4"
, Podium: "5"
};
//The style name corresponding to each terrain
var ArrayCss = ['empty', 'wall', 'steel', 'tod', 'river', 'podium'];
// Level map
/*Level*/
var str = '0000000000000';
str = ',0011100111010';
str = ',1000010000200';
str = ',1200333310101';
str = ',0000444400001';
str = ',3313300001011';
str = ',3011331022011';
str = ',3311031011011';
str = ',0101011102010';
str = ',0101011010010';
str = ',0100000000110';
str = ',0100012101101';
str = ',0010015100000';
//Storage level map 0,1,2,3... are 1-n respectively...Level
var Top_MapLevel = [str];

2.3 Draw a map

Now that the preparations are done, let’s start serving the dishes and drawing the map. As mentioned earlier, our map is a 13 * 13 table. So we add row and column attributes to the game loading object, and add an initialization map method.

Frame.js:

Copy code The code is as follows:

// Game loading object The core object of the entire game
GameLoader = function () {
This._mapContainer = document.getElementById("divMap"); // The div
that stores the game map This._selfTank = null; // Player tank
This._gameListener = null; // Game main loop timer id
/*New attributes added in v2.0*/
This._level = 1;
This._rowCount = 13;
This._colCount = 13;
This._battleField = []; // Store the two-dimensional array of map objects
}
//Load map method
Load: function () {
                // Initialize the map according to the level
        var map = Top_MapLevel[this._level - 1].split(",");
        var mapBorder = UtilityClass.CreateE("div", "", "mapBorder", this._mapContainer);
// Traverse each cell in the map table
for (var i = 0; i < this._rowCount; i ) {
                                   // Create a div, and the map of each row is saved in this div
            var divRow = UtilityClass.CreateE("div", "", "", mapBorder);
//Create another array in the one-dimensional array
This._battleField[i] = [];
for (var j = 0; j < this._colCount; j ) {
// Read map data, default value: 0
              var v = (map[i] && map[i].charAt(j)) || 0;
// Insert span element, a span element is a map unit
              var spanCol = UtilityClass.CreateE("span", "", "", divRow);
                      spanCol.className = ArrayCss[v];
                               // Put the map object into a two-dimensional array to facilitate subsequent collision detection.
              var to = null;
switch (v) {
case EnumMapCellType.Empty:
                               to = new EmptyB();
                              break;
case EnumMapCellType.Wall:
                                 to = new WallB();
                              break;
case EnumMapCellType.Steel:
                                  to = new SteelB();
                              break;
case EnumMapCellType.Tod:
                                 to = new TodB();
                              break;
case EnumMapCellType.River:
                              to = new RiverB();
                              break;
case EnumMapCellType.Podium:
                               to = new PodiumB();
                              break;
                                                                                                                                                                                                                                                                  default:
throw new Error("The map number is out of bounds!");
                              break;
                 }
                     to.UI = spanCol;
                         // j here is X, because the inner loop is horizontal, x is the abscissa
                          to.XPosition = j;
                        to.YPosition = i;
                                           // Store the current map object into a two-dimensional array, obj is the obstacle object, and occupier is the occupying object
This._battleField[i][j] = { obj: to, occupier: null, lock: false };
                                             //end for
                                   // end for
                                            // Put into window global variable
            window.BattleField = this._battleField;
}

ok, our map is done here. The comments here are very detailed. If you still don't understand something, download the source code and debug it yourself. It will be easy to understand.

Here we mainly load map data and insert each map into the html document as a span element. And store the map object in a two-dimensional array. In the future, when we do collision detection, we can directly get the corresponding array object through the coordinates of the object, which is very convenient.

Attached is the source code: http://xiazai.jb51.net/201411/yuanma/jstankedazhan(jb51.net).rar

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

PHP Advanced Features: Best Practices in Object-Oriented Programming PHP Advanced Features: Best Practices in Object-Oriented Programming Jun 05, 2024 pm 09:39 PM

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

Explore object-oriented programming in Go Explore object-oriented programming in Go Apr 04, 2024 am 10:39 AM

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Analysis of object-oriented features of Go language Analysis of object-oriented features of Go language Apr 04, 2024 am 11:18 AM

The Go language supports object-oriented programming, defining objects through structs, defining methods using pointer receivers, and implementing polymorphism through interfaces. The object-oriented features provide code reuse, maintainability and encapsulation in the Go language, but there are also limitations such as the lack of traditional concepts of classes and inheritance and method signature casts.

In-depth understanding of PHP object-oriented programming: Debugging techniques for object-oriented programming In-depth understanding of PHP object-oriented programming: Debugging techniques for object-oriented programming Jun 05, 2024 pm 08:50 PM

By mastering tracking object status, setting breakpoints, tracking exceptions and utilizing the xdebug extension, you can effectively debug PHP object-oriented programming code. 1. Track object status: Use var_dump() and print_r() to view object attributes and method values. 2. Set a breakpoint: Set a breakpoint in the development environment, and the debugger will pause when execution reaches the breakpoint, making it easier to check the object status. 3. Trace exceptions: Use try-catch blocks and getTraceAsString() to get the stack trace and message when the exception occurs. 4. Use the debugger: The xdebug_var_dump() function can inspect the contents of variables during code execution.

JavaScript and WebSocket: Building an efficient real-time search engine JavaScript and WebSocket: Building an efficient real-time search engine Dec 17, 2023 pm 10:13 PM

JavaScript and WebSocket: Building an efficient real-time search engine Introduction: With the development of the Internet, users have higher and higher requirements for real-time search engines. When searching with traditional search engines, users need to click the search button to get results. This method cannot meet users' needs for real-time search results. Therefore, using JavaScript and WebSocket technology to implement real-time search engines has become a hot topic. This article will introduce in detail the use of JavaScript

See all articles