Javascript:如何集中所有其他对象的对象?

时间:2013-10-18 02:18:01

标签: javascript html css dom

我将尝试以最佳方式解释这一点,所以这里就是这样。在我的项目中,我正在制作视频游戏,此刻,我正在编写玩家将要使用的技能。但是,我看到了一个巨大的,明显的问题。也就是说,我正在设置技能,所以当玩家与龙战斗时,玩家将会取消一些龙的HP,等等。但是当玩家使用相同的技能而不是地精或其他某些技能时会发生什么生物?它将无法正常工作,因为技能与龙特别相关,因为我目前在我的代码中有它。

我决定使用包含所有怪物的物体,但是我不知道如何集中它以便我只能引用一个目标代码,然后它将寻找我正在战斗的怪物。这样,技能是流线型的,我不需要为每场比赛写一个新技能。我该怎么设置呢?

// 1. CHARACTER OBJECTS

function player(hp, hpcap, mana, manacap, energy, energycap, atb) {
    this.hp = hp;
    this.hpcap = hpcap;
    this.mana = mana;
    this.manacap = manacap;
    this.energy = energy;
    this.energycap = energycap;
    this.atb = atb;
}

function playerStats(strength, armor, magicdamage, magicresistance, precision, parry, critical, manaregen, energyregen) {
    this.strength = strength;
    this.armor = armor;
    this.magicdamage = magicdamage;
    this.magicresistance = magicresistance;
    this.precision = precision;
    this.parry = parry;
    this.critical = critical;
    this.manaregen = manaregen;
    this.energyregen = energyregen;
}

function npc(hp, mana, energy, atb) {
    this.hp = hp;
    this.mana = mana;
    this.energy = energy;
    this.atb = atb;
}

function npcStats(strength, armor, magicdamage, magicresistance, precision, parry, critical, manaregen, energyregen) {
    this.strength = strength;
    this.armor = armor;
    this.magicdamage = magicdamage;
    this.magicresistance = magicresistance;
    this.precision = precision;
    this.parry = parry;
    this.critical = critical;
    this.manaregen = manaregen;
    this.energyregen = energyregen;
}

// 2. GLOBAL PLAYER/NPC VARIABLES

var character = new player(1, 100, 50, 50, 75, 75, 6);
var cs = new playerStats(20, 1, 10, 1, 30, 10, 10, 1, 1);
var dragon = new npc(250, 80, 75, 6);
var dragonstats = new npcStats(15, 3, 15, 5, 40, 10, 10, 2, 2);

1 个答案:

答案 0 :(得分:2)

您可以创建全局可用的命名空间:

var yourNameSpace = {};

创建monsters属性:

yourNameSpace.monsters = {};

然后添加怪物的键值对:

yourNameSpace.monsters.dragon = new npc(250, 80, 75, 6);
yourNameSpace.monsters.threeToedMegaSloth = new npc(350, 60, 15, 6);
//etc..

然后你可以这样引用你的怪物:

yourNameSpace.monsters["dragon"];

yourNameSpace.monsters.dragon;