Saturday, 30 December 2017

TrafficControl: Locking Tracks for Trains - Code

Preventing trains to collide is an essential of any traffic controller. In this blog post, I'll implement some basic functionality for that purpose.

I'll use a simplistic model with two boolean variables: lockedUpStream (end station locked) and lockedDownStream (start station locked) with corresponding get and set classes.

When the train is in readyState (in a station), it will try to find a suitable track to the target station in Station::findLeavingTrackIndexToStation(int targetStationID).

If the train finds a suitable track and enters it, it will set a lock on the track:
  • When a train enters a track in upstream direction, the lockedDownStream will be set to true.
  • When a train enters a track in downstream  direction, the lockedUpStream will be set to true (see above). This happens in track::findLeavingTrackIndexToStation.
  • When the last train leaves track in upstream direction, the lockedDownStream will be set to false.
  • When the last train leaves track in downstream direction, the lockedUpStream will be set to false.
If all suitable tracks are locked, the train will wait one second and search for tracks again. 

As a safeguard, the track will also consider the locks when adding a train:

The locks are reset only if there is no train on the track.

The next blog post will cover tests and visualisation of track locks.

Future improvements:
For a certain time after a train enters the track, the track should be marked as red and no trains should be able to enter from any direction.

No comments:

Post a Comment