PencilCoder

Arrays!

Goals:

  • Learn about the JavaScript array object
  • Use arrays in for loops and as arguments to random to write more concise and interesting programs

Coding Snippets:

  • Create an array by putting a comma-delimited list of values and/or variables inside a pair of brackets.
  • The for loop to the left repeats three times, once for each element in the array.
  • In each iteration of the loop, the variable r represents a different turtle.

Math and Computer Concepts:

  • You can think of "array" as a fancy word for "ordered list".
  • We have been using arrays since the For Loops! lesson: [1..4] is a CoffeeScript shortcut to create the array [1,2,3,4].
  • Arrays can hold any type of data (numbers, strings, Turtles, etc.).
  • The random function accepts array arguments. For example, random([-90..90]) returns a value between -90 and 90.

Activities:

Use variables, arrays, and loops to accomplish the following tasks using as few lines of code as possible. Save your scripts in a folder called Arrays.

  • Code a Starburst, but this time randomly select each burst color from an array of just a few colors. Given your increased sophistication as a programmer since coding your first Starburst, consider making your design fancier by using a rhombus for each burst.
  • Write a ROYGBIV script that creates a simple rainbow by iterating over an array of the seven primary rainbow colors.
  • NeonLights: create an array of three turtles with different pen colors and widths. Iterate over this array to make them draw your name in a three-colored line, by forcing the one with the thickest pen to go first.
  • StarburstsStarbursts: Expand upon the Starburst program to create multiple randomly-placed starbursts. For each startburst, randomly select a color family, and then proceed much as you did in the Starburst activity.
  • Coding ExampleTurtleVersusFrog: Code a race between a turtle and a frog (use the wear function and images). The turtle should move forward every turn, either 1, 2, or 3 units. 80% of the time, the frog should not move. However, the other 20% of the time, it should move forward a larger amount. To simulate this, create an array with 8 zeroes and two values greater than 3. Use the random function in each iteration to randomly select from this array, using the resulting value as the frog's distance.