"BLADE04" uses object-oriented methods to write JavaScript tank Wars

Source: Internet
Author: User

Objective

JavaScript is not the same as the language of the program, such as C # or Java, he does not have the concept of "class", although the newest ECMAScript put forward the concept of class, we do not use

In the case of C # and Java alone, it takes a bit of effort to really understand the object-oriented level, especially when beginners tend to be unaware of the object-oriented benefits, because the process of coding is like this

① Process-oriented

This time, we have to think of something, often with a large code snippet completed

② Method Reuse

We can never stand the repetition of the code in one place, so this time we will abstract the same logic into a method

③ when the code reaches a certain amount, we find that another module seems to implement similar functions, and when this happens more and more, we turn it into a "class"

The emergence of the ④ class brings inheritance and other characteristics, and this is what we call object-oriented.

process-oriented vs object-oriented

Process-oriented code is efficient, the code is clear, and does not even happen to be coupled, but this is only applicable to systems with small or low-level code.

The system is slightly larger, the process-oriented code becomes difficult to maintain and is difficult to scale

Object-oriented code natural efficiency is slightly lower, at least the complexity of the code to rise, not very good for beginners to understand, plus the module after the method of the East one West

If there is no good design, the code will affect each other, the system level is chaotic, but the good object-oriented design will make the system code elegant and the basis

For example, there is no object-oriented class, what observer, Factory mode is not playing

So the process-oriented and object-oriented design is not obvious good or bad points, to see the use of the scene, the system is more complex words do not go to the process, because many people maintain a file than the above so the problem is complicated

In this paper, a small tank war game to introduce the "object-oriented" in the front-end JavaScript in the use of some of the scenarios, I hope you understand the object-oriented programming to help

Due to my limited level, the text of the idea is wrong, please put forward

Game IntroductionGame Source

Https://github.com/yexiaochai/blade/tree/master (see the Tank folder)

Http://yexiaochai.github.io/blade/tank/index.html (Demo address)

As the saying goes, no figure you say a JB, I am of course there is a map!

Game Description

The purpose of this game is to verify that the design of the blade framework Ui.abstract.view is reasonable, because I am ready to use him in the actual work, so it took the weekend two days to do this game

PS: In-game pictures are all "steal" , to now even steal who do not know, the code completely write their own , here no plagiarism

This is said to be a tank war, it is not, because of the red and white machine tank war to achieve or more complex, to achieve that degree of two days is even delusional

So here is the simple version of the realization, said is a simple version, in fact, his prototype is our childhood playing the game console tank war, I do not know you still remember

function Play

Gameplay is the fight with NPC tanks constantly fighting, fighting process hero tank will not stop upgrading, the overall performance will be upgraded, but with the series increase the number of NPC tanks will continue to increase

So generally 20 multilevel I hung up, hung after also did not do what to deal with, the main reason is that these two days write too tired!!!

Game Extensions

In fact this game is extensible, although I do not have to expand here

First, bullets can be expanded, such as a hero's bullets turning into lasers or shotguns.

Next NPCs are extensible, and when extended NPCs can be set to run with Heroes

None of the above:), this is because the game itself is implemented in an object-oriented way, so even if I want to achieve the above functions can be very convenient

Code Defects

The initial idea is good, write object-oriented programs, but there are still some lack of "object-oriented" in the process of real code, if there is time to refactor him later, this is the main thing to do

In addition, after the code has been written only after a simple test, there is a bug should not be a stranger, you can leave a message

Code Implementation

In fact, the implementation of the game, the first to have a global controller, I here the global controller for the app

 This. App = {  //Hero Upgrade ParametersLevelparameter: [{speed:1, Bulletspeed:4, Maxbulletsize:1, init:0}, {speed:1, Bulletspeed:4, Maxbulletsize:1, init:0}, {speed:2, Bulletspeed:6, Maxbulletsize:1, init:0}, {speed:2, Bulletspeed:6, Maxbulletsize:2, init:32}, {speed:2, Bulletspeed:6, Maxbulletsize:2, init:32}, {speed:2, Bulletspeed:6, Maxbulletsize:3, init:64}, {speed:2, Bulletspeed:6, Maxbulletsize:4, init:64}, {speed:2, Bulletspeed:6, Maxbulletsize:4, init:96}, {speed:2, Bulletspeed:7, Maxbulletsize:5, init:96}], Npcobj: {NO1: {dirobj: {init:32 * 4}}, NO2: {dirobj: {init:32 * (4 + 2)}, Datamodel: {speed:2}}, NO3: {dirobj: {init:32 * (4 + 4)}, Datamodel: {bulletspeed:6}}, NO4: {dirobj: {init:32 * (4 + 6)}, HP:4}}, Maxnpcsize:2, Npcsize:0, GameStatus:false, Gameobj: {hero: [],//There's only one hero for the time being, so let 's not focusNPC: [], Herobullet: [], Npcbullet: [], Boom: []}, tick: $.proxy (function () {    if( This. Me.status = = ' Destroy ') {       This. App.gamestatus =false; } $.each ( This. App. Gameobj, $.proxy (function(k, v) {//first do the screening       This. App. Gameobj[k] = _.filter ( This. App. Gameobj[k],function(item) {returnItem.status!== ' Destroy ';      });  for(vari = 0, Len = This. App. Gameobj[k].length; i < Len; i++) {         This. App.      Gameobj[k][i].move (); }    },  This));  This. CREATENPC ();  This. DataChange ();  This. LevelUp (); if( This. App.gamestatus) {RAF ($.proxy ( This. App.tick, This)); }  },  This),  //Create an NPC tankCREATENPC: $.proxy (function(opts) {opts=$.extend ({gamerule:' NPC ', wrapper: This. $el. Find (' #map '), App: This. App}, opts,true); varFlag = parseint (Math.random () * 4); if(parseint (Math.random () * 5) = = 4) {opts.speciality= ' HP '; } opts= $.extend (opts, This. app.npcobj[' NO ' + (flag + 1)],true); Console.log (opts)varNPC =NewNpctank (opts); varI, Len, bullet;    Npc.show (); /*here Heroes each move will have an impact on NPC, the same NPC will affect the impact of NPC only need to pay attention to heroes and heroes sent Bullets, hero processing to more complex*/     This. Me.registerobserver (NPC); Npc.registerobserver ( This. Me); //defects, NPC temporarily not concerned about NPC, can penetrate each other    //$.each (THIS.APP.GAMEOBJ.NPC, function (I, item) {    //npc.registerobserver (item);    //          });    //record the last NPC for testing     This. NPC =NPC;  This. App.  GAMEOBJ.npc.push (NPC); },  This),  //Create our hero tankCreatehero: $.proxy (function () {     This. Me =NewTank ({datamodel: {x:192, y:192}, Gamerule:' Hero ', wrapper: This. $el. Find (' #map '), App: This. App});  This. Me.Show (); Window.me= This. Me;  This. App. GAMEOBJ.hero.push ( This. Me); },  This), Createbullet: $.proxy (function(opts) {//bullets are created to distinguish between hero and NPCs.opts =$.extend ({wrapper: This. $el. Find (' #map '), App: This. App}, opts,true); varGamerule =Opts.gamerule; varBullet =NewBullet (opts);    Bullet.show (); //depending on the role of the bullet, there will be different objects of observation, NPC bullets corresponding to heroes, Hero bullet Objects npc!     //hero bullets need to be watched by NPC tanks and bullets .    if(Gamerule = = ' Herobullet ') {$.each ( This. App. GAMEOBJ.NPC,function(I, item) {Bullet.registerobserver (item);      }); $.each ( This. App. Gameobj.npcbullet,function(I, item) {Bullet.registerobserver (item);    }); } Else if(Gamerule = = ' Npcbullet ') {      //NPC Bullets are coming, heroes are going to be careful.$.each ( This. App. Gameobj.hero,function(I, item) {Bullet.registerobserver (item);      }); $.each ( This. App. Gameobj.herobullet,function(I, item) {Bullet.registerobserver (item);    }); }     This. App.    Gameobj[gamerule].push (bullet); returnBullet; },  This), Createboom: $.proxy (function(opts) {opts=$.extend ({wrapper: This. $el. Find (' #map '), App: This. App}, opts,true); varBoom =NewBoom (opts);    Boom.show ();  This. App.    GAMEOBJ.boom.push (Boom); returnboom; },  This)};
View Code

This global controller plays the role of the game clock.

1TICK: $.proxy (function () {2   if( This. Me.status = = ' Destroy ') {3      This. App.gamestatus =false;4   }5 6$.each ( This. App. Gameobj, $.proxy (function(k, v) {7     //first do the screening8      This. App. Gameobj[k] = _.filter ( This. App. Gameobj[k],function(item) {9       returnItem.status!== ' Destroy ';Ten     }); One      for(vari = 0, Len = This. App. Gameobj[k].length; i < Len; i++) { A        This. App. Gameobj[k][i].move (); -     } -}, This)); the  -    This. CREATENPC (); -    This. DataChange (); -    This. LevelUp (); +  -   if( This. App.gamestatus) { +RAF ($.proxy ( This. App.tick, This)); A   } at  -}, This),

Every once in a while he informs the game object to exercise, and then according to each other's motion triggers the game event, this is a typical release subscription model

The game clock changes, then notifies all other object movements and needs to do object destruction work

The game object is completely inherited from an object "Moveobj" moving object, the inheritance relationship is:

Conclusion

Originally wanted to say a few more words, but the last two days coding a little tired, you go to see the source bar, I can't carry it here ...

"BLADE04" uses object-oriented methods to write JavaScript tank Wars

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.