High School Computer Science and Programming Workshop
Class 6: Implementing the Traffic Light Simulation


Hesam Samimi, Cliff Kushler
Ananda Living Wisdom School



Here is a direct link to Snap!


To play with Snap! you can just click on the play button on some of the images, like the one above. If you have any problems with it loading, visit Snap! directly in a new browser tab (On that page, click "Run Snap! now"). Another possible solution, if your browser is not Chrome, is to give Chrome a try.


Instance Variables, Global Variables

Remember how to make variables in Snap!? Remember when you make one it asks you whether it is for all or just this sprite? What is the difference?

A Global Variable is a single variable accessible to everybody. But a Instance Variable belongs to a specific object, that is a specific sprite copy, or instance as it is sometimes called. Remember, a sprite can act as a prototype and clone itself. If we have added an instance variable for the sprite, each clone will have its own variable. Think of an iPhone factory. Each iPhone is an exact copy of the prototype, but it is still unique, for instance it has a its own unique serial number. In that case, we can say the iPhone sprite has an instance variable called serial-number



Implementation: Cars and a Traffic Light

We have made part of the simulation for you. Open up this program and explore how the simulation works, clock ticking, car moving, light signal changing, and so on...


Here is a direct link to this exercise.


Exercise 1: Stop at Light

Modify the program above to make the car stop when it's in front of the light and the light is yellow or red. You don't need to worry about the car stopping right before the light; stopping at a bit of distance is OK. Also for simplicity assume the car's acceleration can only be -1, 0, or 1.


Exercise 2: Go at Green

Now modify the program below to make the car move again once the light turns green.

Here is a direct link to this exercise.


Exercise 3: Don't Speed!

Now modify the program below to make the car slow down if it passes the speed limit. It is OK to keep it moving at the speed limit.

Here is a direct link to this exercise.


Exercise 4: Don't Hit Cars!

Now modify the program below to make the car slow down when too close to the car in front of it.

Here is a direct link to this exercise.


Simulation: Investigate

Once you have the cars behaving reasonably well on the race track, the fun begins. It's time to ask some interesting questions and see if our simulation can answer them. For example:

Pick one of these or think one of your own. Then see if you can modify the program accordingly to see what happens?

Next: Class 7: Functions
Previous: Class 5: Modeling, Design, Implementation: Traffic Light, ATM
Back to: Table of Contents