23. Building a Simulation
Part of
CS:2820 Object Oriented Software Development Notes, Spring 2019
|
We have a Java program that builds an internal representation of a road network on the computer, and we have a pending event set mechanism (actually two of them), so it's time to marry the two and create a simulation of a road network.
Of course, we need to add some things to our road network to do this:
One way to add vehicles to a highway network is to add some new classes of intersection, vehicle sources and sinks. In the real world, these might model roads coming into the highway network from the outside world and roads leaving the highway network, or they might model parking lots.
In the simulated world, vehicle sources create new vehicles out of nothing and spit them out into the road network. Similarly, vehile sinks consume any vehicle that enters them, utterly and completely destroying those vehicles.
In our model, we'll keep things simple with the following two new intersection types:
interseciton X source 100 10 3.5
interseciton Y sink
We need to add parsing support for source intersections. Step 1 in this venture is to just parse the details of the source and store the parameter values. This is straightforward code that imitates the kind of code we've already written. Half of this code is copied from other intersection types.
class Source extends Intersection {
float startTime;
int carCount;
float departureInterval;
// constructor
public Source( Scanner sc, String name ) {
super( name );
// first scan the new fields
startTime = ScanSupport.nextFloat(
sc,
() -> Source.this.toString()
)
carCount = ScanSupport.nextInt(
sc,
() -> Source.this.toString()
);
departureInterval = ScanSupport.nextFloat(
sc, );
() -> Source.this.toString()
);
// Bug: Some fields of this are undefined in each error message above
// deal with end of line
ScanSupport.lineEnd(
sc,
() -> StopLight.this.toString()
);
// check sanity of field values
if (startTime < 0.0f) {
Errors.warning( "Negative start time: " + Source.this.toString() );
}
if (carCount < 1) {
Errors.warning( "Never produces cars: " + Source.this.toString() );
}
if (departureInterval < 0.0f) {
Errors.warning( "Negative interval: " + Source.this.toString() );
}
// BUG: schedule the first departure from this source
}
// simulation methods
void departureEvent() {
// BUG new vehicle departs
}
// other methods
public String toString() {
return (
"intersection " + name + " source " + startTime
+ " " + carCount + " " + departureInterval
);
}
}
The details of the simulation of an departure are all missing above, replaced by bug notices. We need to flesh this out.
In contrast, the Sink subclass of Intersection is relatively easy. We won't give the code here to parse vehicle sinks.