javascript游戏我应该如何减少实体与主窗口的耦合?

标签 javascript

我在游戏中有一个实体,它有一个更新方法,它需要定位最近的僵尸,目前僵尸列表只是我访问的全局对象,但这似乎是错误的,我可以将列表传递到更新中方法,但我不确定这是否是最好的方法?

这是我的更新方法的简化版本:

this.update = function () {
                var targetedZombie = null;
                //TODO: should not be using the zombies object - tight coupling should be removed
                var alivezombies = [];
                for (var zombie in zombies) {
                    if (zombies[zombie].Alive) {
                        alivezombies.push(zombies[zombie]);
                    }
                }

                targetedZombie = this.GetClosestEntity(alivezombies);
                if (targetedZombie) {
                    Fire(this, targetedZombie);
                }
});

最佳答案

使用闭包 //初始化你的API

    (function(global) {
      var zombies = []; // accessible only to you

      function zombieManager() { 
         this.addZombie = function() {  zombies.push() }
         this.killHalfZombies = function() { 
                  zombies = zombies.filter(function(item,i) { return i % 2 == 0});
         }
      }
      global.zombieManager = new zombieManager();

      function hero() {

      };

      hero.prototype.update = function() {
        //dig zombies[]
        //do whatever state change
      };
      global.hero = hero;
    })(window); //<-- you pass in whatever rootlevel object we have. window in a browser.

//use api
    var myhero = new hero();
    hero.update() //<-- this can access zombies

    zombieManager.addZombie(); //<-- zombieManager is a singleton and is responsible for zombification

关于javascript游戏我应该如何减少实体与主窗口的耦合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10287665/

相关文章:

javascript - 用PHP加载音频文件并用JS播放

javascript - 函数前的感叹号有什么作用?

javascript - SyntaxHighlighter v3.0.83 源码

javascript - 谷歌地图 API 无法使用变量

javascript - 鼠标悬停时在 jQuery 中更改数据属性的背景图像。

javascript - 使用 JQuery 更改整体列布局使表格行可见

javascript - 动态创建单选按钮 Jquery

javascript - 快速 Javascript 表单查询

javascript - 参数 'ContactsCtrl' 不是函数,未定义

javascript - jQuery ajax使用成功事件,如何获取json属性