我正在尝试在我正在构建的 Angular 色扮演游戏中制作一个回合制战斗系统。我希望玩家能够(通过 CSS)看到自己和敌人的生命在整个战斗中是如何降低的。 这是我当前的代码:
// Defining the variables globally for accessibility.
var enemy_max_hp = 0;
var enemy_hp = 0;
var enemy_atk_dmg = 0;
var enemy_def_pwr = 0;
var enemy_crit_chance = 0;
var enemy_crit_pwr = 0.0;
function battle() {
while(current_hp > 0 || enemy_current_hp <= 0){
//setTimeout(function(){
current_hp -= enemy_atk_dmg*enemy_crit_pwr*crit_chance/100 + def_pwr/2;
enemy_hp -= attack_dmg*crit_power*crit_chance/100 - enemy_def_pwr/2;
if(current_hp < 0){ current_hp = 0; }
if(enemy_hp < 0){ enemy_hp = 0; }
if (current_hp == 0){
// Die
}
if (enemy_current_hp == 0){
// Win battle, proceed.
spawnenemy();
}
//}, 1000);
}
}
function spawnenemy() {
enemy_max_hp = 150;
enemy_hp = 150;
enemy_atk_dmg = 5;
enemy_def_pwr = 3;
enemy_crit_chance = 0;
enemy_crit_pwr = 0;
}
我正在通过另一个脚本更新用户的数据:
var max_hp = 100;
var current_hp = 100;
var attack_dmg = 5;
var defense_power = 4;
var crit_chance = 0;
var crit_power = 0.0;
function showStats(){
document.getElementById("max_hp").innerHTML = max_hp;
document.getElementById("current_hp").innerHTML = current_hp;
document.getElementById("attack_dmg").innerHTML = attack_dmg;
document.getElementById("defense_power").innerHTML = defense_power;
document.getElementById("crit_chance").innerHTML = crit_chance + '%';
document.getElementById("crit_power").innerHTML = crit_power;
}
setInterval(showStats, 5);
如果我按原样运行代码,战斗眨眼间就会结束,并且生命值会在一个实例中从 100 变为 0。我认为添加 setTimeout() 函数会起作用,但它只会使网页崩溃。我该怎么办?
此外,战斗函数是通过按钮 onclick 调用(现在)调用的。我尝试制作一个turn()函数,但我惨败了。
顺便说一句,我尽量避免使用任何外部包。我从未接触过 jQuery 或 Angular2,现在我也不会使用它们。不过,如果你们中有人知道使用它的解决方案,请随时分享。说实话,我也不太关心向后兼容性。
最佳答案
SetTimeout (kindof) 产生一个单独的进程,该进程开始它自己的生命。调用此函数的代码不会停止。
你应该这样做:
function battle(){
if(current_hp > 0 || enemy_current_hp <= 0){
// do your win thing
} else {
// do your fight thing
// next round in 1 second
setTimeout(battle, 1000);
}
}
出于此类目的使用 setTimeout 比 setInterval 更好,因为您不必清除它们,并且它们不会变得拥挤 - 如果您的战斗花费的时间比 period 长,那么这不会进入下一场战斗。
关于 jQuery,而不是像这样的长 js 选择器:
document.getElementById("max_hp").innerHTML = max_hp;
在 jQuery 中你可以这样写:
$('#max_hp').html(max_hp);
此外,周期为 5 毫秒的 setInterval 有点危险,尤其是在速度较慢的计算机上。至少使用 17 ms 间隔,甚至 100 ms。无论如何,正常人都不会看到少于 100 毫秒的更新。
关于轮次之间的 JavaScript 延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47315985/