显示Javascript警报()

时间:2016-02-10 12:15:18

标签: javascript html alert freeze pause

我有一个javascript游戏,它提供警报" Game Over!"当满足条件的游戏时,距离大于另一个距离。距离越来越大,因此一次又一次地满足条件,浏览器要求"防止此页面从其他对话框创建"。单击“确定”并使用 F5 Ctrl + 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);
   }
}

1 个答案:

答案 0 :(得分:1)

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

var gameHasEnded = false;

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

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