Remembering what is happening
A program’s state is the information that describes what is happening right now. In a game, it might include the score, the remaining lives, and whether a door is open.
State changes when something happens. Picking up a coin changes a total. Pressing a button might change a menu choice. A variable lets a program remember one of these values between instructions.
Remember a board game
If you pause a board game, you need to remember whose turn it is and where the pieces stand. Those details describe its current state. Without them, you would have to start again.
A computer game has a similar problem. Drawing a door does not by itself remember whether the player is allowed through it. We can keep that information in a Boolean: a value that is either true or false.
A door and a key
# language: en
let hasKey = false
let doorOpen = false
set hasKey = true
if hasKey:
set doorOpen = true
if doorOpen:
say "You may enter."
else:
say "The door is closed."
This tiny example represents picking up the key with set hasKey = true. It prints the result instead of drawing a game. hasKey and doorOpen are separate pieces of state: having a key and opening a door are different events.
Predict, then run
Which message should appear?
You may enter.
Now imagine removing the line that gives you the key. The starting value would remain false and the door would stay closed.
Your challenge
Add a lives variable starting at three. Represent one lost life by subtracting one. Display the remaining lives. Keep the door state separate from the number of lives.
A common mistake
Using let inside a repeated block to recreate a score can reset it every round. Create the lasting score before the loop and use set to update it. Also remember that ordinary runtime variables are not permanent saved data. A fresh run starts from its initial values unless you deliberately load saved information.
