我正在用JS编写一个简单的游戏。这基本上是一场机会游戏。你按下一个按钮(运行一个功能),如果它没有返回数字9,那么它会显示一张图片,你得到一个点并继续前进。如果它确实返回9,你会看到一张丢失的图片然后你松了。游戏等待两秒钟(所以你实际上可以看到丢失的图像),然后抛出一条警告消息,告诉你高分,然后刷新页面。
问题出现在你失去两秒钟并收到警报信息之间,你仍然可以点击并接收积分。有没有办法禁用再次调用的函数表单?我正在寻找一种方法来做到这一点。
var didIGetAPoint = function() {
if(num != losing number) {
show pic, get a point and keep going
}
else { show losing pic, disable this function from running again, pause, then alert box.}
}
答案 0 :(得分:0)
最简单的方法是禁用按钮(删除onclick处理程序并设置按钮禁用属性)。
你可以做这样的事情。var gameover = false;
var didIGetAPoint = function() {
if(num != losing number) {
if (gameover === true) {return false;}
show pic, get a point and keep going
}
else { show losing pic, disable this function from running again, pause, then alert box.
gameover = true;
}
}
答案 1 :(得分:0)
创建一个布尔变量来设置游戏是否结束。
这是我的例子。 JSFIDDLE
HTML
<button id="pointbutton" onclick="clickforpointsandlose()">Click me to earn points and Lose!</button>
JS
var points = 0;
var isaLoser = false;
function clickforpointsandlose(){
if(!isaLoser) {
//show pic, get a point and keep going
points+=1;
console.log("total points "+ points);
}
else {
console.log("You can't earn points because you already lost.");
//show losing pic, disable this function from running again, pause, then alert box.}
}
}
console.log("You are losing in 2 seconds");
loserhaha = setTimeout(function(){
alert("You Lose!");
isaLoser = true;
}, 2000);