gpt4 book ai didi

javascript - clearInterval 不会停止 setInterval

转载 作者:行者123 更新时间:2023-11-30 09:55:35 24 4
gpt4 key购买 nike

我有这个用于 javascript 积木游戏的游戏。问题是我的 clearInterval 函数不想停止,即使它是全局声明的。我在这里添加了我的绘制函数,它在每次调用 setInterval 时渲染 Canvas 。

initbricks();
draw();
init_mouse();
var i = setInterval(draw,100);

function play(){
document.getElementById("play").disabled = true;
}

function reset(){
clear();
clearInterval(i);
}

//Initialize game
function init() {
document.getElementById("play").addEventListener("click", play);
document.getElementById("reset").addEventListener("click", reset);
}

//Load canvas after window has loaded
if (document.getElementById) window.onload=init;

function draw() {
clear();
circle(ballX,ballY,radius);
rect(paddlex, height-paddleh, paddlew, paddleh);

//draw bricks
for (i=0; i < NROWS; i++) {
ctx.fillStyle = rowcolors[i];
for (j=0; j < NCOLS; j++) {
if (bricks[i][j] == 1) {
rect((j * (BRICKWIDTH + PADDING)) + PADDING,
(i * (BRICKHEIGHT + PADDING)) + PADDING,
BRICKWIDTH, BRICKHEIGHT);
}
}
}

// hit brick?
rowheight = BRICKHEIGHT + PADDING;
colwidth = BRICKWIDTH + PADDING;
row = Math.floor(ballY/rowheight);
col = Math.floor(ballX/colwidth);
// if so, reverse the ball and mark the brick as broken
if (ballY<NROWS*rowheight && row>=0 && col>=0 && bricks[row][col]==1) {
dy = -dy;
bricks[row][col] = 0;
}

// if game not over, move paddle
if (ballY+dy<height)
if (rightDown && paddlex+paddlew<width)
paddlex += 5;
else if (leftDown && paddlex>0)
paddlex -= 5;

// Right/Left stop condition
if (ballX+dx>width-5 || ballX+dx<5)
dx= -dx;

// Up stop condition
if (ballY+dy<5)
dy= -dy;

// Down stop condition
else
//i f ball is on the paddle
if (ballY+dy>height-20 && ballX>paddlex && ballX<paddlex+paddlew)
dy= -dy;

// if ball is not on the paddle
else if (ballY+dy>height+20){
// game over, so stop the animation
clearInterval(i);
}
ballX += dx;
ballY += dy;
}

最佳答案

for (i=0; i < NROWS; i++) {

似乎变量 i 已被 for 循环替换。

重命名区间变量名

关于javascript - clearInterval 不会停止 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34184871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com