我正在做我的第一个游戏蛇,但是当我吃一个矩形并尝试生成另一个我的脚本崩溃并且出现无限循环时,有时会出现问题

var coincide = false;
         var cmpt;
         do {
             mangey = Math.random();
             mangey *= canvas.height;
             t = mangey % 20;
             mangey -= t;
             mangex = Math.random();
             mangex *= canvas.width;
             t = mangex % 20;
             mangex = mangex - t;
             for (cmpt = 0; cmpt < snake.length; cmpt++) {
                 if ((snake[cmpt][0] == mangex) && (snake[cmpt][1] == mangey)) {
                     coincide = true;
                     alert(snake);
                     console.log(mangex,mangey);
                 }
             }
         }
         while ((coincide) || ((mangex > 480) || (mangex < 0)) || ((mangey > 380) || (mangey < 0)));

最佳答案

coincide = true;时,它永远不会改变,因此它始终为真,因此是无限循环。所以我要添加一个else语句:

if ((snake[cmpt][0] == mangex) && (snake[cmpt][1] == mangey))
{
  coincide = true;
  alert(snake);
  console.log(mangex,mangey);
}
else
{
  coincide = false;
}

关于javascript - Javascript循环错误无限循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28915742/

10-12 02:10