如何使用Javascript OOP制作循环,直到玩家击败敌人?
var character = {};
character.health = 5;
character.damage = 1;
var npc = {};
npc.health = 5;
do {
npc.health = npc.health -= character.damage;
document.write(npc.health + "<br>");
}
while (npc.health != 0);
if (npc.health == 0) {
document.write("Player wins.");
}
当角色伤害设置为1时可以正常工作,但一旦它超过1,它就会永远循环并且浏览器会崩溃吗?我很困惑。另外我如何让它显示0而不是像-1等那样进入负数?
答案 0 :(得分:5)
如果character.damage
为2,请考虑循环的迭代。
第一次迭代后,npc.health
将为3。
第二次迭代后,npc.health
将为1。
第三次迭代后,npc.health
将为-1。
由于您的while
条件为npc.health != 0
,您的循环将永远持续,因为npc.health
永远不会为0,它将继续变得越来越负面。
将while
条件更改为npc.health > 0
可以解决您的问题。
在您减去npc
后,为了不显示character.damage
的负面运行状况,只需添加if
语句,然后再使用document.write()
来显示npc.health
}。
if (npc.health < 0) {
npc.health = 0;
}
答案 1 :(得分:0)
首先让我们调整循环以适应“胜利”的情况,因为健康状况已变为负面,
do {
npc.health -= character.damage;
document.write(npc.health + "<br>");
} while (npc.health > 0);
if (npc.health <= 0) {
document.write("Player wins.");
}
现在,因为你不想显示底片,所以我建议在循环内移动if
并break
离开它而不是使用条件。这使您可以更好地控制离开循环的位置以及确切发生的情况。
while (true) {
npc.health -= character.damage;
if (npc.health <= 0) { // player won
// fix the health value to what you want
npc.health = 0;
// create output as desired
document.write(npc.health + "<br>");
document.write("Player wins.");
// leave the loop
break;
}
document.write(npc.health + "<br>");
}
在进入此循环之前,您可能还希望检查character.damage
是否为正,
if (character.damage > 0) while (true) // etc..
最后,这个模式可以很容易地扩展到 NPC 攻击播放器
if (character.damage > 0 || npc.damage > 0) // the loop will ultimately end
while (true) {
// chatacter attacks NPC
npc.health -= character.damage;
if (npc.health <= 0) { // player won
// fix the health value to what you want
npc.health = 0;
// create output as desired
document.write('Them: ' + npc.health + "<br>");
document.write("Player wins.");
// leave the loop
break;
}
document.write('Them: ' + npc.health + "<br>");
// NPC attacks character
character.health -= npc.damage;
if (character.health <= 0) { // npc won
// fix the health value to what you want
character.health = 0;
// create output as desired
document.write('You: ' + character.health + "<br>");
document.write("NPC wins.");
// leave the loop
break;
}
document.write('You: ' + character.health + "<br>");
}
如果您希望进一步扩展这一点,您可能会发现循环变得过于复杂。您可以选择将其移动到函数中,以便更清楚地阅读。
答案 2 :(得分:0)
根据我的说法,程序中的逻辑存在一些问题。所以我把更改的程序放在这里,试试你的运气。我还没有测试过这段代码,但我认为它会起作用。
var character = {};
character.health = 5;
character.damage = 1;
var npc = {};
npc.health = 5;
do {
npc.health -= character.damage;
if(npc.health>0)document.write(npc.health + "<br>");
else break;
}while (npc.health > 0);
if (npc.health <= 0) {
document.write("Player wins.");
}
如果您多次放置character.damage
,那么您的循环也将被终止。