A DOM-Based Snakes Game, Part II: Winning Points | WebReference

A DOM-Based Snakes Game, Part II: Winning Points


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

Winning Points

The user earns points by eating the target apple. Every time the snake hits its target, it is extended by 1 and a new target appears on the board. Here is the function that process collisions with the target:

function processTargetCollision() {
  if (snakeRowPos[1] == targetRow && snakeColumnPos[1] == targetColumn){
    snakeLength++;
    snakeRowPos[snakeLength] = afterTailRow;
	snakeColumnPos[snakeLength] = afterTailColumn;
	loadTarget();
	divNode.childNodes[domIndex(afterTailColumn, afterTailRow)].src =
     snakeGif;
  // (The above two lines should be joined as one line.
  // They have been split for formatting purposes.)
	score++;
	scoreThisLevel++;
	window.status = "Turn with (u, h, n, k) or with NumLock
     (8, 4, 2, 6); Your score is " + score;
  // (The above two lines should be joined as one line.
  // They have been split for formatting purposes.)
    if (scoreThisLevel == qualifyingScore) {
	  scoreThisLevel = 0;
	  interval = interval/2;
	  clearInterval(cycleObj);
	  setInterval("moveOne()", interval);
	}
  }
} 

Detecting a collision is simple. We just check if the snake's head coordinates coincide with the target's coordinates:

if (snakeRowPos[1] == targetRow && snakeColumnPos[1] == targetColumn)

We first increment the snakeLength. Then we set the coordinates of the newly-created square to afterTailRow and afterTailColumn. The trick here is that we extend the snake to where the snake tail was before the last move. We then load the new target via the loadTarget() function. The last statement dealing with the target is the one that fill the tail with the right GIF file:

divNode.childNodes[domIndex(afterTailColumn, afterTailRow)].src = snakeGif;

The rest of the function deals with the scoring. We first add one point to the score, and to the scoreThisLevel. We also update the message on the window status. Finally, when the scoreThisLevel reaches a certain qualifyingScore, we want to double the game's speed. Notice that in order to set the new interval, you need to clear the previous one, and set it again with the new interval:

if (scoreThisLevel == qualifyingScore) {
  scoreThisLevel = 0;
  interval = interval/2;
  clearInterval(cycleObj);
  setInterval("moveOne()", interval);
}

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/win.html