我正在使用javascript,jquery,HTML和CSS制作游戏。这是一个非常简单的游戏。:
在尝试将win
转换为函数之前,这工作正常。每当我运行游戏时,preStart()
工作正常,但是一旦start()
开始,游戏似乎立即调用win(),即使它在setTimeout()
中。
javascript代码如下。只需告诉我你是否需要HTML和/或CSS。我提前为冗长的代码道歉,但我觉得如果我展示所有这些代码可能会更容易。我还要提前感谢你花时间仔细而愉快地回答我的问题。
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;
}
答案 0 :(得分:4)
当您通过打开和关闭括号(&#34; ()
&#34;在setInterval中将其设置为回调时, 调用 获胜)之后的功能
改变这个:
setInterval( win(), 10000);
对此(删除括号以避免调用获胜):
setInterval(win, 10000);
此外,您似乎试图通过传递函数win
而不是设置间隔时返回的整数来清除间隔:
// set win to be invoked every 10000 ms
var intervID = setInterval(win, 10000);
// clear the interval above and thus stop it from
// invoking win any further
clearInterval(intervID);