Lesson 7

To change the direction of the snake, we need to change the direction of its first segment. Add the following function to snake.js:

var changeDirection = function(direction) {
  snake[0].direction = direction;
}

Next, we have CHUNK call changeDirection when an arrow key is pressed. Add the following line at the end of snake.js:

CHUNK.onArrowKey(changeDirection);

This tells CHUNK to call the changeDirection function every time an arrow key is pressed.

Just like we pass our snake object into the drawSnake function, we can pass the changeDirection function into the onArrowKey function.

In JavaScript, we can pass functions into functions just like we can pass arrays, strings, integers, and objects into 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 moveSegment = function(segment) {
  switch(segment.direction) {
    case "down":
      return { top: segment.top + 1, left: segment.left };
    case "up":
      return { top: segment.top - 1, left: segment.left };
    case "right":
      return { top: segment.top, left: segment.left + 1 }
    case "left":
      return { top: segment.top, left: segment.left - 1 }
    default:
      return segment;
  }
}

var moveSnake = function(snake) {
  var oldSegment = snake[0];
  var newSegment = moveSegment(oldSegment);
  newSegment.direction = oldSegment.direction;
  var newSnake = [newSegment];
  return newSnake;
}

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

var changeDirection = function(direction) {
  snake[0].direction = direction;
}

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

How the game should work so far:

Next Step: