The real power of computers is that they can repeatedly execute a set of instructions that we, the programmer, only have to write down once. For example, think about the simple game of Tetris. The current game piece keeps moving down a space until it reaches another block below it. The statement of code to move the block slightly downward only has to be written once, but we can set a condition for when it stops repeating: when it touches another block.
Or think about this non-computer code example: putting cookie dough on a baking sheet to put in the oven. You roll the dough into a ball and put the ball onto the pan. Then you do it again with more dough. Then again with more dough, until the pan is full. There are only two things you are really doing (rolling the dough and placing it on the pan), but you have to do it multiple times. This is like a loop.
Counted Loops
Sometimes we might have something we want to have happen some number of times.
Direct link to vid (10.1 - Cement Truck)
- https://docs.google.com/leaf?id=0B6MEauh__dIYcXp2aUFWY0RVWG8
This was a somewhat complicated scene. Were you able to "see" a set of things that were repeated 3 times? If not, watch it again...
Nested (Counted) Loops
Here's something where it's harder to see where the "repeated" parts are. We have something repeated three times, then something else happens, then the whole process starts over again!
While Loops
Sometimes, we can't know in advanced exactly how many times something should happen. This is true in a lot of games. In the scene below, we have a a zombie and a lunchlady. We want the zombie to chase the lunchlady such that when the zombie gets within 1 meter of the lunchlady he eats her. The trick to notice is the we aren't controlling the zombie or the lunchlady with user events -- instead the amount they move (and the direction for the lunchlady) is a random amount each time.