I am making a game with javascript, jquery, HTML, and CSS. It is a very simple game.:
- The blocks fade away, and the user has to click on them to keep them solid
- If one of the block fades completely away, you lose
- If you can keep them up for 10 seconds, you win.
- Beware that the blocks fade quicker and quicker with each second.
This was was working fine until I tried to turn win
into a function. Whenever I run the game, preStart()
works fine, but then once start()
begins, the game seems to call win() immediately, even though it's in a setTimeout()
.
The javascript code is below. Just tell me if you need the HTML and/or CSS. I apologize in advance for the lengthy code, but I felt it might be easier if I showed all of it. I would also like to thank you in advance for taking the time to answer my question thoughtfully and nicely.
var red = document.getElementById("red");
var blue = document.getElementById("blue");
var green = document.getElementById("green");
var text = document.getElementById("text");
var score = 0;
var fadeRate = 0.01;
var started = false;
var rop = 1.0;
var bop = 1.0;
var gop = 1.0;
function preStart() {
clearInterval(win);
reset();
if (started == false) {
started = true;
setTimeout(function() {text.style.left = '300px'; text.innerHTML = "3";}, 100);
setTimeout(function() {text.innerHTML = "3 2";}, 1100);
setTimeout(function() {text.innerHTML = "3 2 1";}, 2100);
setTimeout(function() {
text.style.left = '350px';
text.innerHTML = "Go!";
start();
}, 3100);
}
}
function start() {
fade = setInterval(function() {
rop = rop - fadeRate;
red.style.opacity = rop;
bop = bop - fadeRate;
blue.style.opacity = bop;
gop = gop - fadeRate;
green.style.opacity = gop;
if (rop <= 0 || bop <= 0 || gop <= 0) {lose();}
}, 50);
speedUp = setInterval(function() {
fadeRate = fadeRate + 0.01;
}, 1000);
setInterval(win(), 10000);
}
function redClick() {
score = score + rop * 10;
rop = 1.0;
red.style.opacity = rop;
}
function blueClick() {
score = score + bop * 10;
bop = 1.0;
blue.style.opacity = bop;
}
function greenClick() {
score = score + gop * 10;
gop = 1.0;
green.style.opacity = gop;
}
function lose() {
clearInterval(fade);
clearInterval(speedUp);
clearInterval(win);
setTimeout(function() {text.style.left = '150px'; text.innerHTML = "You lose!";}, 100);
setTimeout(function() {
text.style.left = '250px';
text.innerHTML = "Retry?";
started = false;
reset();
}, 2100);
}
function win() {
clearInterval(fade);
clearInterval(speedUp);
clearInterval(win);
setTimeout(function() {text.style.left = '175px'; text.innerHTML = "You win!";}, 100);
score = Math.floor(score);
setTimeout(function() {text.style.left = '100px'; text.innerHTML = "Score: " + score;}, 2100);
setTimeout(function() {
text.style.left = '250px';
text.innerHTML = "Retry?"
started = false;
reset();
}, 4100);
}
function reset() {
score = 0;
fadeRate = 0.01;
rop = 1.0;
bop = 1.0;
gop = 1.0;
}