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:
Get the length of an array (including the element at location 0):
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):
yarrayas global variables.
- Then, draw a point or small circle at
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:
- Have it push
mouseYon 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
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
yarray. If the line starts at
yarray[i], how would you describe the next point (using
Modify each point in the array to move down by 1 pixel each draw() until points reach the bottom, as shown below.
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: