A loop is a way to tell the program to repeat some code. You have already used one important loop, the
draw function. It repeats the functions we put inside it over, and over again, so that we can create information. You may notice that the draw function never really stops, it just starts over when you run the program again.
If you were to add the code below in to the draw loop, you could see what your project is like without a loop.
noLoopfunction once you are done testing it!
Change the code in your
collectApples functions to draw and collect the first apple in the
Save and Run. You should be able to find your random-colored apple in a random scene, and collect it just like before.
There are many times when we want to repeat code a specific number times, and you can do this with a while loop. There are three different steps:
Make a variable to be your counter. We usually start this at 0.
Make a while loop with the condition that the counter is less than its maximum number.
Make sure the counter counts up inside the while loop.
While loops will work to use a counter, but there is a type of loop that is made specifically for this purpose: the for loop!
It has all the same steps as using a while loop with a counter, but we do them all in one place.
Why are we using
i as our counter? Programmers often do this, because "i" stands for "iterator" which is a thing that repeats. You can use any variable name.