gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 22:24:42 24 4
gpt4 key购买 nike

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

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com