我试图制作一款游戏,让你有机会获得重击,正常击中或击中某些东西。现在我认为它与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;
}
}
答案 0 :(得分: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 !");
}
}
答案 1 :(得分: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而不是alert。按F12&gt;控制台查看结果。
有Math.round真正围绕随机数。每次在while循环中都必须随机重新计算var chance
。