2015-04-05 42 views
-4

我正在試圖製作一款遊戲,讓你有機會獲得重擊,正常命中或擊中某些東西。現在我認爲它與if/else中的變量有關。這是我的代碼:爲什麼我的While循環不工作?

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; 
    } 
} 
+1

重擊敵人'hpDummy -0'做什麼? – 2015-04-05 19:01:02

+0

嘗試解釋更多目前該功能的功能,以及您期望它做什麼? – shunya 2015-04-05 19:02:05

+0

也許,您應該在每次迭代時生成一個新的隨機數。否則它將永遠是一樣的。 – Oriol 2015-04-05 19:02:11

回答

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 Demo

0
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代替警報東西。按F12>控制檯查看結果。 有Math.round來真正地圓整隨機數。必須在while循環中每次隨機重新計算var chance

+0

非常感謝@CoR – 2015-04-05 19:30:07