Reputation: 164
I am busy making a Red Or blue clicking game which can be viewed here: http://www.ysk.co.za/red-blue
My problem is the countdown I have made by de incrementing var countdown
only stops when the function key()
is run, and until it is run the countdown goes into negative values if more than 12 seconds
My Javascript is:
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);
}
}
My HTML is:
<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>`
How Can I do this so that when countdown == 1
the alert()
appears, also if you know of any better way to stop and reset the game other than refreshing the page that would be great.
Your help is much appreciated
Upvotes: 0
Views: 139
Reputation: 3723
Since you are updating your time in the setInterval, you should check in there whether the countdown value has reached 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);
Upvotes: 1