1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
#include <iostream> #include <chrono> #include <thread> // Enum to represent traffic light states enum class LightState { RED, YELLOW, GREEN }; // Class to represent a traffic light class TrafficLight { public: TrafficLight() : currentState(LightState::RED) {} // Method to update the state of the traffic light void update() { switch (currentState) { case LightState::RED: currentState = LightState::GREEN; break; case LightState::YELLOW: currentState = LightState::RED; break; case LightState::GREEN: currentState = LightState::YELLOW; break; } } // Method to print the current state of the traffic light void printStatus() const { switch (currentState) { case LightState::RED: std::cout << "Red Light\n"; break; case LightState::YELLOW: std::cout << "Yellow Light\n"; break; case LightState::GREEN: std::cout << "Green Light\n"; break; } } private: LightState currentState; }; int main() { TrafficLight trafficLight; // Simulation parameters const int redDuration = 5; // Duration for red light in seconds const int yellowDuration = 2; // Duration for yellow light in seconds const int greenDuration = 4; // Duration for green light in seconds while (true) { // Print the current status trafficLight.printStatus(); // Wait for the duration corresponding to the current light switch (trafficLight.currentState) { case LightState::RED: std::this_thread::sleep_for(std::chrono::seconds(redDuration)); break; case LightState::YELLOW: std::this_thread::sleep_for(std::chrono::seconds(yellowDuration)); break; case LightState::GREEN: std::this_thread::sleep_for(std::chrono::seconds(greenDuration)); break; } // Update the traffic light to the next state trafficLight.update(); } return 0; } |
Explanation
- LightState Enum:
- Purpose: Represents the possible states of the traffic light.
- States:
RED
,YELLOW
,GREEN
.
Advertisement - TrafficLight Class:
- Attributes:
currentState
: The current state of the traffic light.
- Methods:
update()
: Changes the traffic light to the next state in the sequence: RED -> GREEN -> YELLOW -> RED.printStatus()
: Prints the current state of the traffic light.
Advertisement
- Attributes:
- Main Function:
- Traffic Light Creation: Initializes a
TrafficLight
object. - Simulation Loop:
- Print Status: Displays the current light state.
- Wait: Pauses execution for a duration depending on the current light state.
- Update State: Advances the traffic light to the next state.
- Traffic Light Creation: Initializes a
Usage
- Traffic Light Simulation: Models the operation of a traffic light with simple state transitions and timing.
- State Durations: The program uses fixed durations for each light state (red, yellow, green) and updates the light accordingly.
Advertisement