A Box That Grows From Itself
One line puts a box's own value back into it, larger. It is the counter behind every score, timer and life count.
Here is the pattern that does the real work in games. Remember from The Basics that = means
put this in the box.
LET score = 0
SHOW "Score: ", score
LET score = score + 10
SHOW "Score: ", score
Score: 0 Score: 10
Read it as an instruction
Read LET score = score + 10 as maths and it is nonsense. Nothing equals itself plus ten.
Read it as an instruction and it is clear: take what is in score, add ten, put the result
back.
The order is what makes it work. The computer deals with the right-hand side first, using whatever the box holds right now. Only then does it put the answer back.
| Step | score before | score after | Shown |
|---|---|---|---|
| 1 | — | 0 | — |
| 2 | 0 | 0 | Score: 0 |
| 3 | 0 | 10 | — |
| 4 | 10 | 10 | Score: 10 |
Watch step 3. score appears on both sides of the =. The computer reads the
right-hand side first, adds ten to what it finds, then puts that answer back in the box.
It works in every direction
Adding to a box is only the common case. The same move takes away:
LET lives = 3
LET lives = lives - 1
SHOW "Lives: ", lives
Lives: 2
That one move is how every score climbs, every total mounts up and every life count falls. You will write it in every game you ever make.
When it’s wrong, see why
- The value never changes. Check that you put the answer back.
score + 10on its own works the sum out and then throws it away; it needsLET score =in front of it. - The value resets every time.
LET score = 0is sitting somewhere it runs more than once. Set a box’s starting value once, before the part that repeats. LET score = score + 10still looks wrong to you. Good, because it is wrong as maths. Read it as “the new score is the old score plus ten”.
What you’ve learnt
- A box can grow from its own value, and that is the counter behind every score.
- The computer works out the right-hand side first, then puts the answer back.
- The same move subtracts, which is how a life count falls.
=means put this in the box, which is exactly why a box can grow from itself.
What’s next
You can build a value up. In Unit 3 we deal with the sums that do not come out evenly, and with the part that gets left behind.