Have you ever been on a highway going really slowly in heavy traffic and all of a sudden the traffic begins to speed up for no apparent reason at all? Nobody got off. You didn't pass an accident. Nothing seems to have changed except that now the cars are going faster. What happened?
In this lab, you will develop a model of what might affect traffic speed, and build a simulation in Snap! to explore that model.
The first four steps on this page ask you to think about the algorithm you'll use to build this program. You shouldn't be doing anything in Snap! during those steps.
Each of these steps asks you to think about one part of the program. You'll definitely want to talk to your partner. You may even want to write some things down.
Consider the overall setup. Each car is a sprite. All sprites will have essentially the same scripts. The only difference will be where the car starts in line and which car it is following. So, this is what car 5's scripts might look like. (But don't start building them now. Your programming starts in problem 5 below.)
startpos
and drive but avoid hitting sprite
.startpos
is the same for all sprites, it put all the sprites in the same place. So we needed each sprite to move
to space out the cars. Your program might be different.
The drive but avoid hitting sprite
block will repeat a set of actions that might be like this:
Design an algorithm for the behavior. Exactly how will the car's speed change? When it is close enough to the car in front of it, will it just become the speed of that car? Or will it slow down more gradually? It must not crash or pass.
Below is one possibility. Notice how it uses replace item
to replace the old speed with the new speed. This version just replaces it with a speed slightly (and randomly) less than the car in front of it.
When the car has lots of room in front of it, how will it speed up? It must not exceed the limit.
NOW, program your algorithm in Snap! Give one sprite the ability to detect its distance to the (not-yet-existent) sprite ahead of it, and write the script that uses that to control its forward motion. Make sure that when a car goes off the screen it comes back in the other side.
Here are two tools we found useful. You may or may not need them, depending on how you program your model. The 12 in SpriteNumber in front of me
was the number of sprites in our model. You may need a different number there. You might also build this tool quite differently.
One sprite will also need to set the variables that all sprites use. In our model, the script looked like this: