Display of Javascript alert()



我有一个javascript游戏,当满足游戏结束条件时,它会发出警报"游戏结束!",这是一个距离大于另一个距离。距离越来越大,因此一次又一次地满足条件,浏览器要求"阻止从其他对话框创建此页面"。当我单击"确定"并使用 F5Ctrl + F5 刷新浏览器时。"游戏结束!"警报不再出现,必须重新启动浏览器。要么我必须在游戏结束时暂停游戏中的所有内容,要么在页面刷新时以某种方式启用 alert()。

会很高兴得到你的提示!下面是我的代码:

function run(t) {
   requestAnimationFrame(run);
   if (t === undefined) {
      t=0;
   }
   var h = t - tprev;   // time step 
   tprev = t;

   SmileyApp.xpos += SmileyApp.xspeed * h/1000;  // update position according to constant speed for Yellow Smiley
   SmileyApp.ypos += SmileyApp.yspeed * h/1000;  // update position according to constant speed
    for (var i=0; i<SmileyReds.length; i++){
   SmileyReds[i].xpos += SmileyReds[i].xspeed * h/1000;  // update position according to constant speed for Red Smileys
   SmileyReds[i].ypos += SmileyReds[i].yspeed * h/1000;  // update position according to constant speed
    }
   // Yellow Smiley edge hit control
   if (lineDistance(350, 350, SmileyApp.xpos, SmileyApp.ypos) + SmileyApp.radius > 300) {
     alert("Game Over");
     //swal("Game Over");
     //break;
     //Object.freeze(canvas);
     fade(canvas);
   }
    for (var i=0; i<SmileyReds.length; i++){
      if (lineDistance(350, 350, SmileyReds[i].xpos, SmileyReds[i].ypos) + SmileyReds[i].radius > 300) {
      // Red Smiley collusion with circle edge
      // bounce formula : v2 = v1 − [2 (n · v1) n]
        nx = 350 -  SmileyReds[i].xpos ;
        ny = 350 -  SmileyReds[i].ypos ;
        var len = Math.sqrt(nx * nx + ny * ny)
        nx = nx / len;
        ny = ny / len;
      //new calc
       v_newx = SmileyReds[i].xspeed - (2 *( nx * SmileyReds[i].xspeed + ny * SmileyReds[i].yspeed ) ) * nx;
       v_newy = SmileyReds[i].yspeed - (2 *( nx * SmileyReds[i].xspeed + ny * SmileyReds[i].yspeed ) ) * ny;
       SmileyReds[i].xspeed = v_newx;
       SmileyReds[i].yspeed = v_newy;
        }
        // Red - Yellow Smiley collusion
     if (lineDistance(SmileyApp.xpos, SmileyApp.ypos, SmileyReds[i].xpos, SmileyReds[i].ypos) < 2*SmileyApp.radius ) {
        alert("Game Over");
        }
    }// for loop end
   // redraw smileys at new position
   ctx.clearRect(0,0,canvas.height, canvas.width);
   drawBigCircle();
   drawSmiley(SmileyApp.xpos, SmileyApp.ypos, SmileyApp.radius);
   for (var i=0; i<SmileyReds.length; i++){
   drawSmileyRed(SmileyReds[i].xpos, SmileyReds[i].ypos, SmileyReds[i].radius);
   }
}

在函数顶部附近定义一个变量:

var gameHasEnded = false;

然后,使用它来确定游戏是否已结束:

if (lineDistance(350, 350, SmileyApp.xpos, SmileyApp.ypos) + SmileyApp.radius > 300) {
    if (! gameHasEnded) {
        gameHasEnded = true;
        alert("Game Over");
        fade(canvas);
    }
}

最新更新