A Simple Traffic Light System
This is little more than an exercise to see if I can create a traffic light system for an intersection.
There isn't much use for this program ... although, it might be possible to hook it up to a model train set or something like that. Why not! Anyway the code is quite neat and small considering what it does.
Firstly, A traffic light is a light with three colours
traffic_light_colour(red).
traffic_light_colour(green).
traffic_light_colour(orange).
Traffic lights force all roads to have a red light except one. That one road can have any colour.
traffic_rules(_, red).
traffic_rules(red, _).
From these rules the whole traffic light sequence can be obtained. I'll use Baker St and Main St as an example intersection.
traffic_light_colour_for_street(BakerSt, MainSt) :-
traffic_rules(BakerSt, MainSt),
traffic_light_colour(BakerSt),
traffic_light_colour(MainSt).
Just need to write a way to sequence them and print the states, use a failure driven loop and print out the states.
single_light_seq :-
traffic_light_colour_for_street(BakerSt, MainSt),
format('Baker St. is now ~p, Main St. is now ~p.~n', [BakerSt, MainSt]),
sleep_by_state(BakerSt, MainSt, SleepTime),
sleep(SleepTime),
fail.
that does the sequence but only one time, so add a repeat of the single sequence to run the lights forever!
repeating_light_seq :-
repeat,
single_light_seq,
fail.
The lights need to vary by time depending on the current state so identify the times by the street (in seconds).
sleep_by_state(red, red, 3).
sleep_by_state(green, red, 5).
sleep_by_state(orange, red, 2).
sleep_by_state(red, green, 10).
sleep_by_state(red, orange, 2).
And that is that for now, enjoy!