Lesson
Loop It Yourself
✕
This is the last topic of the course, and the loops are yours now.
Up to here every loop was written for you and you filled in the numbers. From now on the lines themselves are missing, and each missing line has a comment sitting directly above it saying what belongs there. That comment is the instruction. Read it as a sentence:
// circle(across, down, wide) — 40 + i * 78 across, 250 down, 50 wide
It names the drawing you need, then the order its numbers go in, then what to put in each one. Everything it asks for is something you have written before.
An empty line is not an error. The loop still runs, it just draws nothing, so a canvas with the grass and no flowers on it is telling you exactly which line is missing rather than shouting at you.
Then the headers go too. A header has three parts and they are always in the same order:
for (var i = 0; i < 5; i = i + 1) {
Where the counter starts. When to carry on. What to add each turn. Read the target, count the shapes, and the three parts follow: five shapes means stopping after five, a row that starts partway along means starting partway along, and shapes two apart in the counting means a step of two.
Counting down flips the middle part. If the counter starts at 5 and takes 1 away each turn, then carrying on means being greater than the finish, not less than it: for (var i = 5; i > 0; i = i - 1).
Watch the step. A step that counts away from the stop never reaches it, and the loop runs forever — the page will tell you so, in words, and stop the sketch. That message is feedback, not a crash: read the line number, turn the step around, and run it again.
One thing to remember about the pen. shapeColour belongs inside the loop with the drawing it is for, or every shape keeps whatever colour was last picked up — which is how a row of suns comes out grass green.
The last five challenges move. The counter says which shape, a number kept above everyFrame says when, and both of those lines are yours as well.
That is the whole course: a loop repeats, its counter is a number you can use, its header says how the counting goes, sums make patterns out of it, functions hold the drawings, loops hold loops, and time carries the lot along.