为什么我的While循环不起作用

Why is my While loop not working?

本文关键字:不起作用 循环 While 我的 为什么      更新时间:2023-09-26

我正在努力制作一款游戏,让你有机会获得暴击、普通命中或命中某些东西。现在我认为这与if/else中的变量有关。这是我的代码:

    var chance =  parseInt(Math.random() * 10);    
    var hpDummy = 10;
while ( hpDummy >=1)
{
    if(chance >= 5 && chance <7)
     {   
    alert("You throw a punch at the dummy! You graze it's nose dealing 1 damage");
    var hpDummy = hpDummy -1;
     }
    else if (chance >=7)
    {
    alert("You throw a punch at the dummy! You directly hit its jaw dealing 2 damage ! AMAZING shot ! ");
    var hpDummy = hpDummy -2;
    }
    else 
    {
    alert("You completely miss the dummy almost hitting Welt !");
    var hpDummy = hpDummy -0;
    }
}

只需将chance变量放入函数中即可。如果chance变量的值小于5,那么它将变成无限循环。所以试试这个

 var hpDummy = 10;
 while (hpDummy >= 1) {
     var chance = parseInt(Math.random() * 10);
     if (chance >= 5 && chance < 7) {
         alert("You throw a punch at the dummy! You graze it's nose dealing 1 damage");
         var hpDummy = hpDummy - 1;
     } else if (chance >= 7) {
         alert("You throw a punch at the dummy! You directly hit its jaw dealing 2 damage ! AMAZING shot ! ");
         var hpDummy = hpDummy - 2;
     } else {
         alert("You completely miss the dummy almost hitting Welt !");
     }
 }

JS Fiddle演示

   var hpDummy = 10;
while ( hpDummy >=1){
  var chance =  Math.round(Math.random() * 10);    

    if(chance >= 5 && chance <7)
     {   
    console.log("You throw a punch at the dummy! You graze it's nose dealing 1 damage");
    var hpDummy = hpDummy -1;
     }
    else if (chance >=7)
    {
    console.log("You throw a punch at the dummy! You directly hit its jaw dealing 2 damage ! AMAZING shot ! ");
    var hpDummy = hpDummy -2;
    }
    else 
    {
    console.log("You completely miss the dummy almost hitting Welt !");
    }
}

我正在使用console.log而不是alert。按F12>控制台查看结果。有Math.round可以真正对随机数进行四舍五入。在while循环中,每次都必须随机重新计算var chance