Bounce Coding - Step 6 - Lists

If this is your first time reading about Bounce Coding, I recommend you start from the beginning.

Lists

Now we're getting to the point where just one ball is a little boring. How should we go about adding more? Right now we have 4 variables for a single circle: x, y, r and velocity_x (possibly 5 if you've added a velocity_y). We could add more 4 more variables to represent each circle, such as x2, y2, r2, velocity_x2, but there's a better way. We could use a data structure called a list. A list can hold multiple values in a single variable. The simplest kind of list is called an array. In javascript, you can create an array by surrounding a comma separated list of values with square brackets (i.e. []). Once you've created an array, you can access an individual value in the array by using square brackets and an index value (i.e. x[0]). The first element of an array has an index of 0. The second value has an index of 1 and the last value in the array is N-1 where N is the number of items in the array. Before we get adapt our program to use arrays, here's a basic array example.

Notice how I have a single variable x, that contains an array with 3 values in it. Each value represents the x coordinate of a circle. You can access each value of the array using an integer value called an index. An index value of 0 returns the first value. An index value of 1 returns the second and so on. Can you add a 4th circle by adding another value to the array and using it in another call to the ellipse function?

Let's get back to our Bounce project. I've modified the program from the previous step to use arrays. Each of the 4 variables listed above has been changed to be a three element array. I copied the code that made the circle move, bounce and render three times so there are now 3 differently sized circles, each moving a different speed, in a different y position. 

Things to note

  • Notice how we copied the same code 3 separate times with the only change being the index into the array to pull out different values for each circle. We'll see how to eliminate this duplicated code in the next step.
  • Can you make each circle bounce against the top and bottom of the screen as well?
  • If you manage to get the circles bouncing around the screen, you may notice that the circles still pass through each other. When I was first learning to program this was very unsatisfying. It took me years before I learned enough to make them bounce off each other. I'll show you how in one of the following steps.
  • For more information on arrays, check out Khan Academy's tutorial.