0

我有一个编程问题,不太高级。出于某种原因,当我执行以下代码时, setTimeout 方法仅在第一次调用时创建暂停。当再次调用它时, setTimeout 在执行它的函数之前不会创建暂停。有谁知道为什么会这样以及如何解决这个问题?

附带说明一下,是否可以创建一个在每次执行之前暂停的 while 循环?我的代码如下。

var slaying = true;
var youHit = Math.floor(Math.random()*4 + 1);
var damageThisRound = Math.floor(Math.random()*5 + 1);
var totalDamage = 0;
var timer1 = null;


function swing(percentOfMiss) {

此 if 语句采用参数除以 25。由于 youHit 最初生成一个介于 1 和 4 之间的整数,如果我们将参数设置为 25,我们将有 1 比 4 (25%) 的机会错过龙。如果设置为 50,我们将有四分之二(50%)的机会错过龙,等等......

要增加丢失的机会,只需在调用函数时提高参数编号。*/

if (youHit <= parseFloat(percentOfMiss) / 25) {     
    //youHit is set to 0, or false
    youHit = 0;
} else {

如果 youHit 生成的随机数大于等号右边的数字,则将 youHit 设置为 1,或者为 true。

    youHit = 1;
}

}

该功能的目的:发起战斗回合。检查我们是否击中了龙,我们造成了多少伤害,以及龙是否死亡。每 2 秒开始一个新的战斗回合。在最后一个战斗回合中,将“Game Over”记录到控制台。

function attack(roundTime) {
if (slaying) {
    if (youHit) {
        console.log("You hit the dragon!");
        totalDamage += damageThisRound;
        console.log("You did " + damageThisRound + " damage this round.");
        if (totalDamage >= 4) {
            console.log("You slew the dragon! Congrats!");
             //If you killed the dragon, stop slaying by breaking the while loop...
            slaying = false;
            //...and call the next combat turn. This will log "Game Over".
            timer1 = setTimeout(attack, roundTime);
        } else {
            //Otherwise if the dragon's still alive, set new damage for this round...
            damageThisRound = Math.floor(Math.random()*5 + 1);
            //...see if you hit the dragon...
            youHit = Math.floor(Math.random()*4 + 1); 

...并召回攻击()。在 roundTime 指定的时间后将调用攻击。这会在程序中造成延迟,给人一种战斗轮流的错觉。*/

            timer1 = setTimeout(attack, roundTime);
        }    
    } else {
        //If you miss, the dragon kills you...
        console.log("You missed... and the dragon killed you. Sorry.");
        //... and we break the while loop by setting slaying to false...
        slaying = false;
        //...and call next combat turn. This will log "Game Over".
        timer1 = setTimeout(attack, roundTime);
    }
} else {

将 slaying 设置为 false,我们现在在下一个(也是最后一个)回合打印 Game Over。

    console.log("Game Over");
}

}

射击摆动和攻击功能

swing(25);
attack(1500);
4

0 回答 0