If this is your first time reading about Bounce Coding, I recommend you start from the beginning.
A loop is a way to run a chunk of code multiple times. The simplest loop is a while loop. A while loop will continuously run a block of code while a condition of your choosing is true. We can use a while loop to simplify the list example in the previous step.
We've introduced a new variable, i, that is initially set to 0 and represents the current index into the array. Note that an index of 0 represents the first element in the list. Each time through the loop, we draw an ellipse using the x value at the specified index, then increment the index. While the index is less than the number of items we have in the array, keep going. Try adding values to the array. Notice how more ellipses are drawn without having to add any extra code (besides an extra value in the array).
Using a variable and incrementing it in a loop is so common, that there is a special kind of loop meant for exactly that called a for loop. Here's the same example as above, but uses a for loop rather than a while loop.
Instead of using an index into the array, each value is directly passed to a function that does something with it. As you can see, each of these examples do the same thing in a slightly different way. A for each loop is often the easiest kind of loop to read and understand. A for loop is the next easiest, and is favored if you need a sequence of numbers (such as the indices of an array). A while loop is the most multipurpose loop because the condition can be anything (i.e. while I have lives, keep playing the game or while there is nothing in front of me, walk forward, while true, loop forever, etc.).
Getting back to our Bounce example, which loop should we use? Since our last example had multiple arrays, we can't use a for each loop without combining them into a single array some how (we'll talk about how to do this later). We need a sequence of indices to access the variables in our arrays, so let's use a for loop. I've adapted the last Bounce example to use a for loop rather than unnecessarily duplicating code:
Now to add another circle to the simulation, we need to add a value to each of our four arrays. It can be a hassle to maintain 4 separate arrays, and if we want to add extra variables to control attributes of our circles (such as color, or bounciness), then we'd have to add more arrays. So this still isn't the best way to organize our variables. Stay tuned for a better way in the next post!
Things to note
- Try making the balls bounce off the top and bottom of the screen as well. You may have done this in a previous step, so copy over the necessary code and adapt it to take advantage of the for loop.
- For more information on loops, check out Khan Academy's tutorial.
Want more? Let me know in the comments and subscribe to my newsletter to be alerted when I post more Bounce Coding tutorials. Make sure to check Coding under Interests!