Lesson 3

Now that we have a snake being drawn on the screen, We're going to want to be able to draw it many times, for instance every time it moves.

To do this, we'll define a function which draws the snake it's given. Add the following line to the beginning of game/snake.js:

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

Functions are a way to group instructions so they're easy for humans to understand or so the computer can use them over and over without us writing the code out multiple times.

Functions exist somewhat independently from the code around them; this means that if the function needs variables from the rest of the code base they should be passed in as arguments. The drawSnake function takes a single argument, snakeToDraw which it then uses to create the drawableSnake.

Now all we have to do is call drawSnake with a snake and it will be drawn on the screen! Write the following under the drawSnake function.

var snake = [{ top: 0, left: 0}];
drawSnake(snake);

Because Javascript interprets code from top to bottom we can't call functions until after we've defined them. Make sure you put this code at the end of the snake.js file.

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 snake = [{ top: 0, left: 0}];
drawSnake(snake);

How the game should work:

Play Time!

  • Open up the console and play around with making the snake move by calling drawSnake with snakes that have different top and left values for their segment.
  • Try to access drawableSnake from outside of the drawSnake function. Check the javascript console.
  • Try to access snake inside of the drawSnake function. Check the javascript console.
  • Why do you suppose you could access one but not the other? Scope is how you know what variables a function or piece of code has access too. Understanding scope is hugely important when reading and writing code.

Syntax Breakdown

function() { } says "Hey, between the curly braces is some code we want to be able to execute." Functions can be stored inside variables just like words and numbers and objects and lists.

( and ) in this case are a way to say that this function expects a value to be given to it when it is called. These values are called arguments, and can be used inside of the function body (the code between the curly braces).

Helpful Links

  1. An article explaining functions
  2. Information on Objects

Next Step: