完成执行jQuery函数

时间:2016-03-22 21:25:18

标签: jquery html

它似乎是一个直截了当的想法,如果我想停止执行一个函数,我应该return false或只是return或调用函数undefined等...但不是在这种情况下

所以我有一个网站项目,我有一个蛇游戏,用户可以通过向上,向下,向左,按键进行交互。我的主要问题是游戏处于循环中,每当蛇撞到墙壁或自己吃掉时它就会重新启动。

所以这里是HTML代码

<canvas id="canvas" width="200" height="200"></canvas>

Javascript

$(document).ready(function(){
jQuery("#snake-game").on('click',function(e){
    jQuery("div.over-over").removeClass('not-shown');
    playGame();
});
function playGame(e) {
    var canvas = jQuery("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = jQuery("#canvas").width();
var h = jQuery("#canvas").height();
var halt = e;

//Lets save the cell width in a variable for easy control
var cw = 10;
var d;
var food;

//Lets create the snake now
var snake_array; //an array of cells to make up the snake

function init()
{
    d = "right"; //default direction
    create_snake();
    create_food(); //Now we can see the food particle

    //Lets move the snake now using a timer which will trigger the paint function
    //every 60ms
    if(typeof game_loop != "undefined") clearInterval(game_loop);
    game_loop = setInterval(paint, 60);


}

function create_snake()
{
    var length = 5; //Length of the snake
    snake_array = []; //Empty array to start with
    for(var i = length-1; i>=0; i--)
    {
        //This will create a horizontal snake starting from the top left
        snake_array.push({x: i, y:0});
    }
}

//Lets create the food now
function create_food()
{
    food = {
        x: Math.round(Math.random()*(w-cw)/cw), 
        y: Math.round(Math.random()*(h-cw)/cw), 
    };
    //This will create a cell with x/y between 0-44
    //Because there are 45(450/10) positions accross the rows and columns
}

//Lets paint the snake now
function paint()
{
    //To avoid the snake trail we need to paint the BG on every frame
    //Lets paint the canvas now
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, w, h);
    ctx.strokeStyle = "black";
    ctx.strokeRect(0, 0, w, h);

    //The movement code for the snake to come here.
    //The logic is simple
    //Pop out the tail cell and place it infront of the head cell
    var nx = snake_array[0].x;
    var ny = snake_array[0].y;
    //These were the position of the head cell.
    //We will increment it to get the new head position
    //Lets add proper direction based movement now
    if(d == "right") nx++;
    else if(d == "left") nx--;
    else if(d == "up") ny--;
    else if(d == "down") ny++;

    //Lets add the game over clauses now
    //This will restart the game if the snake hits the wall
    //Lets add the code for body collision
    //Now if the head of the snake bumps into its body, the game will restart
    if(nx == -1 || nx == w/cw || ny == -1 || ny == h/cw || check_collision(nx, ny, snake_array))
    {
        //restart game
        init();
        //Lets organize the code a bit now.
        return;
    }

    //Lets write the code to make the snake eat the food
    //The logic is simple
    //If the new head position matches with that of the food,
    //Create a new head instead of moving the tail
    if(nx == food.x && ny == food.y)
    {
        var tail = {x: nx, y: ny};
        //Create new food
        create_food();
    }
    else
    {
        var tail = snake_array.pop(); //pops out the last cell
        tail.x = nx; tail.y = ny;
    }
    //The snake can now eat the food.

    snake_array.unshift(tail); //puts back the tail as the first cell

    for(var i = 0; i < snake_array.length; i++)
    {
        var c = snake_array[i];
        //Lets paint 10px wide cells
        paint_cell(c.x, c.y);
    }

    //Lets paint the food
    paint_cell(food.x, food.y);
}

//Lets first create a generic function to paint cells
function paint_cell(x, y)
{
    ctx.fillStyle = "blue";
    ctx.fillRect(x*cw, y*cw, cw, cw);
    ctx.strokeStyle = "white";
    ctx.strokeRect(x*cw, y*cw, cw, cw);
}

function check_collision(x, y, array)
{
    //This function will check if the provided x/y coordinates exist
    //in an array of cells or not
    for(var i = 0; i < array.length; i++)
    {
        if(array[i].x == x && array[i].y == y)
        return true;
    }
    return false;
}

//Lets add the keyboard controls now
jQuery(document).keydown(function(e){
    var key = e.which;
    //We will add another clause to prevent reverse gear
    if(key == "37" && d != "right") d = "left";
    else if(key == "38" && d != "down") d = "up";
    else if(key == "39" && d != "left") d = "right";
    else if(key == "40" && d != "up") d = "down";
    //The snake is now keyboard controllable
});
}
});

我想要的是让用户点击画布外的任何地方,该功能将停止执行。有任何想法吗?

1 个答案:

答案 0 :(得分:0)

当您在画布外单击时,可以尝试停止游戏循环:原始代码 - &gt; give credit where credit is due

$(document).ready(function() {
  $(document).click(function(e) {
    if ($(e.target).closest('#canvas').length === 0) {
      alert('out of the canvas');
      clearInterval(game_loop);
    }
  });

  $("#canvas").click(function(e) {
    alert('click in the canvas');
    game_loop = setInterval(paint, 60);
  });

  //Canvas stuff
  var canvas = $("#canvas")[0];
  var ctx = canvas.getContext("2d");
  var w = $("#canvas").width();
  var h = $("#canvas").height();

  //Lets save the cell width in a variable for easy control
  var cw = 10;
  var d;
  var food;
  var score;

  //Lets create the snake now
  var snake_array; //an array of cells to make up the snake

  function init() {
    d = "right"; //default direction
    create_snake();
    create_food(); //Now we can see the food particle
    //finally lets display the score
    score = 0;

    //Lets move the snake now using a timer which will trigger the paint function
    //every 60ms
    if (typeof game_loop != "undefined") clearInterval(game_loop);
    game_loop = setInterval(paint, 60);
  }
  init();

  function create_snake() {
    var length = 5; //Length of the snake
    snake_array = []; //Empty array to start with
    for (var i = length - 1; i >= 0; i--) {
      //This will create a horizontal snake starting from the top left
      snake_array.push({
        x: i,
        y: 0
      });
    }
  }

  //Lets create the food now
  function create_food() {
    food = {
      x: Math.round(Math.random() * (w - cw) / cw),
      y: Math.round(Math.random() * (h - cw) / cw),
    };
    //This will create a cell with x/y between 0-44
    //Because there are 45(450/10) positions accross the rows and columns
  }

  //Lets paint the snake now
  function paint() {
    //To avoid the snake trail we need to paint the BG on every frame
    //Lets paint the canvas now
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, w, h);
    ctx.strokeStyle = "black";
    ctx.strokeRect(0, 0, w, h);

    //The movement code for the snake to come here.
    //The logic is simple
    //Pop out the tail cell and place it infront of the head cell
    var nx = snake_array[0].x;
    var ny = snake_array[0].y;
    //These were the position of the head cell.
    //We will increment it to get the new head position
    //Lets add proper direction based movement now
    if (d == "right") nx++;
    else if (d == "left") nx--;
    else if (d == "up") ny--;
    else if (d == "down") ny++;

    //Lets add the game over clauses now
    //This will restart the game if the snake hits the wall
    //Lets add the code for body collision
    //Now if the head of the snake bumps into its body, the game will restart
    if (nx == -1 || nx == w / cw || ny == -1 || ny == h / cw || check_collision(nx, ny, snake_array)) {
      //restart game
      init();
      //Lets organize the code a bit now.
      return;
    }

    //Lets write the code to make the snake eat the food
    //The logic is simple
    //If the new head position matches with that of the food,
    //Create a new head instead of moving the tail
    if (nx == food.x && ny == food.y) {
      var tail = {
        x: nx,
        y: ny
      };
      score++;
      //Create new food
      create_food();
    } else {
      var tail = snake_array.pop(); //pops out the last cell
      tail.x = nx;
      tail.y = ny;
    }
    //The snake can now eat the food.

    snake_array.unshift(tail); //puts back the tail as the first cell

    for (var i = 0; i < snake_array.length; i++) {
      var c = snake_array[i];
      //Lets paint 10px wide cells
      paint_cell(c.x, c.y);
    }

    //Lets paint the food
    paint_cell(food.x, food.y);
    //Lets paint the score
    var score_text = "Score: " + score;
    ctx.fillText(score_text, 5, h - 5);
  }

  //Lets first create a generic function to paint cells
  function paint_cell(x, y) {
    ctx.fillStyle = "blue";
    ctx.fillRect(x * cw, y * cw, cw, cw);
    ctx.strokeStyle = "white";
    ctx.strokeRect(x * cw, y * cw, cw, cw);
  }

  function check_collision(x, y, array) {
    //This function will check if the provided x/y coordinates exist
    //in an array of cells or not
    for (var i = 0; i < array.length; i++) {
      if (array[i].x == x && array[i].y == y)
        return true;
    }
    return false;
  }

  //Lets add the keyboard controls now
  $(document).keydown(function(e) {
    var key = e.which;
    //We will add another clause to prevent reverse gear
    if (key == "37" && d != "right") d = "left";
    else if (key == "38" && d != "down") d = "up";
    else if (key == "39" && d != "left") d = "right";
    else if (key == "40" && d != "up") d = "down";
    //The snake is now keyboard controllable
  })

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="200" height="200">
</canvas>