我正在尝试创建一个“选择你自己冒险”类型的游戏,而我正在尝试编写一个“战斗”脚本。到目前为止我得到的是:
var name = "Anon";
var health = 100;
var youAttack = [name + " hits the " + opp + " with his sword", name + " uses magic!", name + " is too scared to fight!"];
var youBattle = function() {
var youBattle = youAttack[Math.floor(Math.random() * 3)];
return youBattle;
};
var opp = "Orc";
var oppHealth = 100;
var oppAttack = ["The " + opp + " hits you with his hammer!", "The " + opp + " does nothing!", "The " + opp + " back hands you!"];
var oppBattle = function() {
var oppBattle = oppAttack[Math.floor(Math.random() * 3)];
return oppBattle;
};
oppBattle();
youBattle();
我这样做了所以可以很容易地改变对手和球员的名字。
我正在努力弄清楚的是我如何根据使用的攻击来增加/消除对手和玩家的健康状况。显然,如果对手/球员什么都不做,就不会有健康消除。
有没有办法可以在没有一堆凌乱的if / else语句的情况下做到这一点?
我希望像name + " hits the " + opp + " with his sword" + health = health - 10;
一样容易,但显然不起作用。
提前致谢!
答案 0 :(得分:2)
希望这不是太多代码:
var Attack = function(hero,opp,damageReceived,damageGiven,message){
this.message = message;
this.damageGiven = damageGiven;
this.damageReceived = damageReceived;
this.opp = opp;
this.hero = hero;
this.attack = function(opp){
this.hero.health -= damageReceived;
this.opp.health -= damageGiven;
return this.message;
};
};
var Character = function(name,health){
this.name = name;
this.health = health;
};
hero = new Character('Anon',100);
orc = new Character('Orc',150);
attack1 = new Attack(hero,orc,5,0,"The " + orc.name + " back hands you!");
attack2 = new Attack(hero,orc,0,0,hero.name + " is too scared to fight!");
attack3 = new Attack(hero,orc,15,0,"The " + orc.name + " hits you with his hammer!");
attack4 = new Attack(hero,orc,0,25,hero.name + " uses magic!");
attacks = [attack1,attack2,attack3,attack4];
while(hero.health > 0 && orc.health > 0){
console.log(attacks[Math.floor(Math.random() * 4)].attack());
console.log('Hero Health: '+ hero.health);
console.log('Orc Health: '+ orc.health);
}
if(hero.health > 0 ){
console.log(hero.name + ' won');
} else {
console.log('The ' + orc.name + ' won');
}
答案 1 :(得分:1)
我可以直接告诉你,尝试编写这种类型的代码会使用很多if / else和更多语句,而不管你使用的语言是什么。您可以使用数组来保存攻击模式的值:
var attackName = ["Punch", "Sword", "Magic"]
var attackDamage = [3, 5, 4]
function youAttack(ATK, PHit) {
if(playerHit) {
playerDamage = ATK + PHit;
oppHealth = oppHealth - playerDamage;
return oppHeath;
} else {
alert("You missed!");
}
}
但是,如果没有看到你正在做什么,我就不能说你应该如何进行攻击和损害。我只能假设。您将需要一个评估攻击,未命中等的系统,该系统至少在某处使用IF / ELSE语句。