Lab Week 6

Snakes on a (2D) Plane!

(Sorry, I couldn’t resist.)

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]

Implementation

  • 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(1); which “shifts the data to one position lower, dropping element 0 (the oldest).

Refining your code

You can

  • Connect lines by drawing from point i to point i + 1. You must be careful at the end of the array: If there are 10 points in the array, there are only 9 line segments joining them!
  • Record points only when the mouse is down.
  • Change colors each time a new line is drawn.
  • Modify each point in the array to move down by 1 pixel each draw() until points reach the bottom, as shown below.