This lab will simulate a four way intersection. Cars arrive from all four directions and wait until they are first in line. Then they follow the rules of the road (wait for a green, don't pull a "Pittsburgh left") until eventually they cross. The intersection keeps track of time and will maintain statistics about the number of cars entering from each direction and how long they waited.
Car class
You should first complete the Car class. This is a simple object that keeps track of when it entered the intersection and which direction it is going.
Skeleton code: Car.java
Queue class
You will need to implement a Queue class to model the four roads. This class should accept Objects and not Cars (you can cast the Object back into a Car). Your Queue class must contain the following methods in addition to the constructor:
- public void enqueue(Object o)
- public Object dequeue()
- public Object peek()
- public int getLength()
Skeleton code: none! You need to write this from the ground up.
Generator class
This class will create Cars to insert into the simulation. They may be created randomly, read from a file, entered by the user, etc. The sample Generator that we provided has a 1 in 4 chance of adding a car to each road at each time step. We may use a different Generator to test your solution.
Source code: Generator.java
You should edit this class as part of your testing.
Intersection class
This class performs the simulation. It has several instance variables, the most important being an array of four Queues. The run function actually performs the simulation; it steps through time moving cars, adding new ones, and switching the lights as needed. You need to complete this class by writing the advance method. This method moves up to two Cars across the intersection. A car is allowed to cross if it is at the beginning of the queue and the light is green. Also a car may not turn left if there is a car on the other side of the intersection which is traveling straight. This method will also need to accumulate the number of cars and the delay they experience for each street (needed to compute statistics later). The necessary instance variables have already been declared for you. Hint: you may find it useful to write another helper function that will move a single car from a specified street.
Skeleton code: Intersection.java
Sim class
This driver class contains the main entry point. It instantiates a Generator and Intersection, starts the simulation, and displays statistics.
Source code: Sim.java
You should edit this class as part of your testing.