Lab Week 6

Snakes on a (2D) Plane!

(Sorry, I couldn’t resist. Photo from Washington Post archives)

Lab Week 6 looks at arrays. Consider the following (which you will implement today):

To begin, review some array operations:

Create an empty array: var xarray = [];

Append a number to the end of an array: xarray.push(mouseX);

Get the length of an array (including the element at location 0): xarray.length

What is the index of the last element of the array?

Access element number i (aka the i-th element or ith element of the array): xarray[i]

Task 1

  • Declare xarray and yarray as global variables.
  • Call background in draw.
  • Then, draw a point or small circle at xarray[i], yarray[i] for each valid index i in the arrays.

Test your code. It should not draw anything! But the background color should be filled in so you know your program is running.

Modify your code to record mouse movements:

  • Define function mouseDragged().
  • Have it push mouseX and mouseY on the end of the arrays.

Test your code — when you “drag” The mouse, lines of points or circles should appear.

Modify your code to clear xarray and yarray when the mouse is pressed (define mousePressed). Note: to “clear” and array, you can assign it the value [] which is a new empty array. There are other ways too.

Modify your code to limit the length of the arrays to 20. In draw, if the length is greater than 20, you can do the following operation on each array: xarray.shift(); which “shifts the data to one position lower, dropping element 0 (the oldest).

Modify your code to draw lines connecting the points (as shown above in the video). Be careful! If you have 20 points, you will have only 19 lines! Hint: The first line will be drawn from xarray[0] to xarray[1] and yarray[0] to yarray[1]. If the line starts at xarray[i] and yarray[i], how would you describe the next point (using i)?

Task 2

Modify each point in the array to move down by 1 pixel each draw() until points reach the bottom, as shown below.

Task 3

Modify your code so that the snake’s width gradually (and smoothly) decreases from its head to its tail. The head of the snake should always be 20 pixels wide, regardless of the snake’s length. See examples below:

A short “snake”
A longer “snake”