Application Structure
The other classes used in this application are Car and Simulation. The Car class holds information about the car's position, a reference to the RoadSegment that it currently occupies and a bool flag isTravelling which turns false when the car reaches the end.Simulation uses a .NET container object called an Arraylist. for holding all of the road segments, an int Segment variable and an instance rndof the .NET Random class for generating random numbers.
An instance of the Car class is created in the Simulation.RunSimulation() method. Both the Rnd object and Segment are used in a couple of the Simulation methods so have to be declared at the class level.
rnd generates random numbers. rnd.Next(number) returns a value in the range 0..number-1, so rnd.Next(6)+1 is a six sided dice roll.
How it Works
The simulation first builds a list of road segments in the Simulation() constructor in the ArrayList object Roads. Each segment has a random length and speed limit. The parameter LastSegment is set to false for every segment except the last.. So when the Simulation() constructor has finished, all RoadSegment objects have been created.Most of the simulation is spent in Simulation.RunSimulation(). This starts by creating a car object. One of the two parameters passed into this constructor is a reference to the first RoadSegment. The car needs to know which bit of road it is on so it can limit the car speed to the current speed limit. This calls Simulation.NextSegment() to increments the Segment index variable. Road segments are indexed 0..99 so Segment is set to -1 to start with. By calling NextSgment() this increments Segment and fetches the first road segment at position 0.
On the next page : Car Simulation Continued

