为什么我的While循环不起作用
Why is my While loop not working?
我正在努力制作一款游戏,让你有机会获得暴击、普通命中或命中某些东西。现在我认为这与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
。
相关文章:
- 我的javascript for循环不起作用
- javascript for循环不起作用
- 循环通过数组的If语句不起作用
- 为什么我的While循环不起作用
- JS(node.js)而循环不起作用
- 来自MDN的循环示例的JavaScript不起作用
- Mustache.js每个循环都不起作用
- for循环中的jquery.load()不起作用
- For循环与数组不起作用
- JavaScript For循环与For in不起作用
- 为什么我所有的循环都不起作用
- JavaScript 数组/循环不起作用
- Javascript if-else循环不起作用
- 循环浏览页面上所有选中的复选框并将id拉入数组不起作用
- JavaScript的循环问题,将值插入数组将不起作用
- Javascript getElementsByName在PHP循环中不起作用
- Javascript循环数组无限不起作用
- 如果循环停止并且不起作用
- if-else循环和jquery在热应用程序或冷应用程序中不起作用
- 循环变量的Javascript不起作用