We’re going to build a program that uses a turtle in python to simulate the traffic lights.
There will be four states in our traffic light: Green, then Green and Orange together, then Orange only, and then Red.
The light should spend 3 seconds in the Green state, followed by one second in the Green+Orange state, then one second in the Orange state, and then 2 seconds in the Red state.
We’re going to use the concept of state machine.
A state machine is a system that can be in one of a few different states.
This idea is not new: for example, when first turning on a cellphone, it goes into a state which we could call “Awaiting PIN”. When the correct PIN is entered, it transitions into a different state — say “Ready”. Then we could lock the phone, and it would enter a “Locked” state, and so on.
A traffic light is a kind of state machine with four states: Green, then Green+Orange, then Orange only, and then Red.
We number these states 0, 1, 2 and 3. When the machine changes state, we change turtle’s position and its color.
Now we need to tell the window to start listening for events.
Our traffic light will look like this:
Below is the same program in interactive mode with minor modifications:
Resources:
The above program is an exercise from the book Think Python.