我正在为我的游戏开发一个自然灾害序列,并使用Math.random来模拟爆发的变种。所以问题是在我的代码的最底部是一个if语句,它应该检测数字是否达到0但是由于某种原因它起作用。我尝试使用parseInt()但它仍然是dident工作。我可能会做一些严重错误的事情。谢谢你的阅读。
var start = document.getElementById("startbtn");
var waterOut = document.getElementById("waterOut");
start.addEventListener("click", disaster1);
function disaster1() {
//fire
var fireDisaster = Math.floor((Math.random() * 100) + 1);
var water = 1000;
setInterval(function() {
waterOut.innerHTML = "Water: " + water;
}, 1);
var waterbtn = document.getElementById("putFireOutbtn");
var fireCount = document.getElementById("fireCount");
var fireCountNumber = fireCount;
fireCount.innerHTML = "Fire: " + fireDisaster;
alert("Theres a wild fire! Use your water to put it out!");
if (fireDisaster >= 1) {
waterbtn.style.width = "100px";
waterbtn.style.height = "100px";
waterbtn.style.left = "50%";
waterbtn.addEventListener("click", putOutFire);
function putOutFire() {
if (water >= 1) {
water -= 1;
fireDisaster -= 1;
console.log(fireDisaster);
}
fireCount.innerHTML = "Fire: " + fireDisaster;
}
}
if (fireDisaster == 0) {
waterbtn.style.width = "0px";
waterbtn.style.height = "0px";
waterbtn.style.left = "1500px";
alert("You put out the fire!");
fireCount.innerHTML = "";
}
}

<p id="waterOut"></p>
<p id="fireCount"></p>
<button id="startbtn">start</button>
<button id="putFireOutbtn">put out the fire!</button>
&#13;
答案 0 :(得分:1)
现在,当灾难发生时,您只会检查一次fireDisaster
。你想在火上浇水时连续检查它,所以将该代码添加到putOutFire
函数中:
function putOutFire() {
if (water >= 1) {
water -= 1;
fireDisaster -= 1;
console.log(fireDisaster);
}
fireCount.innerHTML = "Fire: " + fireDisaster;
if (fireDisaster == 0) {
waterbtn.style.width = "0px";
waterbtn.style.height = "0px";
waterbtn.style.left = "1500px";
alert("You put out the fire!");
fireCount.innerHTML = "";
}
}