我正忙着制作红色或蓝色点击游戏,可在此处查看:http://www.ysk.co.za/red-blue
我的问题是我通过de var countdown
仅在运行函数key()
时停止的倒计时,直到它运行,倒计时如果超过12秒则进入负值
我的Javascript是:
var i = 0;
var seconds = 0;
var countdown = 12;
setInterval(function () {
$("#counter").html(countdown.toFixed(2));
}, 10);
function play() {
$("#num").select();
}
function key(e) {
var code = e.keyCode ? e.keyCode : e.charCode;
var random = Math.random();
if (random <= 0.5) {
$("#RedBlue").css("background-color", "red")
} else {
$("#RedBlue").css("background-color", "blue")
}
if (code === 86) {
$("#red").css("background", "#ff4e00");
setTimeout(function () {
$("#red").css("background-color", "red")
}, 500);
var color = "rgb(255, 0, 0)";
} else if (code === 66) {
$("#blue").css("background-color", "#006bff");
setTimeout(function () {
$("#blue").css("background-color", "blue")
}, 500);
color = "rgb(0, 0, 255)";
}
var score = i / seconds;
var Endscore = (i - 1) / seconds;
if ($("#RedBlue").css("background-color") != color) {
alert("You clicked " + i + " times in " + seconds.toFixed(2) + " seconds. your score was " + score.toFixed(2));
document.location.reload(true);
} else if ($("#RedBlue").css("background-color") == color) {
$("#score").html("");
i++;
}
if (i == 1) {
setInterval(function () {
seconds += 0.01
}, 10);
setInterval(function () {
countdown -= 0.01
}, 10);
};
if (countdown < 0) {
alert("You clicked " + (parseInt(i) - 1) + " times in 12 seconds. your score was " + Endscore.toFixed(2));
document.location.reload(true);
}
}
我的HTML是:
<div id="game">
<div id="RedBlue"></div>
<div id="red" style="background:red;"></div>
<div id="blue" style="background:blue;"></div><div class="clear"></div>
<button onclick="play()">start</button><br>Enter "v" if the block is red or "b" if the block is blue
<input type="text" size="2" maxlength="1" id="num" onkeyup="key(event); this.select()" />
</div>
<div id="counter" style="font-family:monospace;font-size:100px;font- weight:600;float:left;margin-left:40px;"></div>
<div id="score"></div>`
我该如何做到这一点,以便countdown == 1
出现alert()
时,如果你知道有什么更好的方法来停止和重置游戏,那么刷新页面会很棒。
非常感谢您的帮助
答案 0 :(得分:1)
由于您正在更新setInterval中的时间,因此您应该在那里检查倒计时值是否已达到0
setInterval(function () {
countdown -= 0.01;
if (countdown < 0) {
alert("You clicked " + (parseInt(i) - 1) + " times in 12 seconds. your score was " + Endscore.toFixed(2));
document.location.reload(true);
}
}, 10);