A DOM-Based Snakes Game, Part II: Collision Handling | WebReference

A DOM-Based Snakes Game, Part II: Collision Handling


A DOM-Based Snakes Game, Part II (7)

Collision Handling

We need to check for possible collisions every time we move the snake one square. As we explained in the previous page, we need to restart the game if there is indeed a collision:

if (processBorderCases()) restartGame();

There are three possible types of collisions: with the board's four edges, with the snake itself, and with the target. Here is the processBorderCases() function:

function processBorderCases() {
  processTargetCollision();
  if (processBorderCollision()) return true;
  if (processSelfCollision()) return true;
}

The processTargetCollision() is explained in the next page. Let's look at the processBorderCollision():

function processBorderCollision() {
  if (snakeRowPos[1] + headRowChange == topBorder ||
  snakeRowPos[1] + headRowChange == bottomBorder ||
  snakeColumnPos[1] + headColumnChange == leftBorder ||
  snakeColumnPos[1] + headColumnChange == rightBorder) return true;
  return false;
}

The function checks if one of the snake's head coordinates will overlap the board's edges when a move takes place. After the move, the head's coordinates will be snakeRowPos[1] + headRowChange and snakeColumnPos[1] + headColumnChange. The function checks that they don't coincide with neither of the topBorder, leftBorder, rightBorder, and bottomBorder. If a collision is expected, the true value is returned, triggering a game restart.

The other collision that triggers a game restart is a self-collision. We need to check that the snake's head does not collide with the snake itself:

function processSelfCollision() {
  for (var i = 2; i <= snakeLength; i++) {
    if (snakeRowPos[1] == snakeRowPos[i] && snakeColumnPos[1] ==
     snakeColumnPos[i]) return true;
  // (The above two lines should be joined as one line.
  // They have been split for formatting purposes.)
  }
  return false;
}

The loop above checks that the snake's head coordinates do not overlap any one of the other snake's squares. Notice that the snakeColumnPos and snakeRowPos arrays start at the index of one. We did this in order to avoid the off-by-one syndrome as much as possible.

http://www.internet.com

Produced by Yehuda Shiran and Tomer Shiran

Created: August 30, 1999
Revised: August 30, 1999

URL: http://www.webreference.com/js/column47/collide.html