Lesson 5

Hooray! We can both draw and move the snake! Of course, having our users copy and paste lines of code into their javascript console isn't a wonderful idea, so we're going to have CHUNK execute the move and draw commands for us.

We'll start with an advanceGame function

var advanceGame = function() {
  snake = moveSnake(snake);
  drawSnake(snake);
}

To get this function running we'll use our CHUNK game engine to CALL the executeNTimesPerSecond function. It does exactly that, to do this executeNTimesPerSecond takes in two arguments. The first argument advances the game, and the second tells it how many times to move per-second.

CHUNK.executeNTimesPerSecond(advanceGame, 1);

Bam! Now the snake moves down until it runs off the game screen.

Because functions are just another kind of value (like numbers, arrays, objects, strings, etc.) we can pass them as arguments to other functions.

Expected Results

What your snake.js file should look like:

var drawSnake = function(snakeToDraw) {
  var drawableSnake = { color: "green", pixels: snakeToDraw };
  var drawableObjects = [drawableSnake];
  CHUNK.draw(drawableObjects);
}


var moveSnake = function(snake) {
  var oldSegment = snake[0];
  var newSegment = { top: oldSegment.top + 1, left: oldSegment.left };
  var newSnake = [newSegment];
  return newSnake;
}

var advanceGame = function() {
  snake = moveSnake(snake);
  drawSnake(snake);
}

var snake = [{ top: 0, left: 0}];
CHUNK.executeNTimesPerSecond(advanceGame, 1);

How the game should work so far:

Play Time!

  • How can you increase the speed at which the snake moves?

Helpful Links

  1. Writing functions with more than one argument

Next Step: