w
wiktorch
DEV
•last year
General

code help

Code Helper
Code HelperRolePlay v2

I'd be happy to help you understand and implement a traffic light system! A traffic light system is a simple program that simulates the behavior of traffic lights at an intersection, allowing vehicles to pass safely in an orderly manner. Here's a basic implementation in Python that demonstrates the concept:

python
# Define the traffic light colors as constants
RED = "Red"
YELLOW = "Yellow"
GREEN = "Green"

def traffic_light_system(seconds):
    current_time = 0
    while current_time < seconds:
        # Red phase: 60 seconds
        print(f"Time: {current_time} seconds - {RED} light on.")
        time.sleep(60)
        current_time += 60

        # Yellow phase: 10 seconds
        print(f"Time: {current_time} seconds - {YELLOW} light on.")
        time.sleep(10)
        current_time += 10

        # Green phase: 40 seconds
        print(f"Time: {current_time} seconds - {GREEN} light on.")
        time.sleep(40)
        current_time += 40

# Call the function with the desired simulation duration in seconds (e.g., 240 seconds = 4 minutes)
traffic_light_system(240)

In this example, the traffic_light_system function takes one argument, seconds, which represents the total duration of the simulation in seconds. The function uses a while loop to simulate the traffic light cycles until the specified time is reached.

The traffic light system has three phases:

  1. Red phase (60 seconds): During this phase, the red light is on, allowing vehicles to pass through the intersection from the north-south direction.
  2. Yellow phase (10 seconds): The yellow light signals that the red light will soon turn green, giving drivers a chance to prepare to stop or proceed.
  3. Green phase (40 seconds): The green light allows vehicles to pass through the intersection from the east-west direction.

The time.sleep() function is used to pause the execution of the program for a specific amount of time, simulating the passage of time during each phase of the traffic light cycle.

You can modify the duration of each phase, add more colors (e.g., flashing yellow), or create a more complex system with multiple intersections and timings as needed. The key is to understand the basic concept of a while loop, conditional statements, and using functions to encapsulate the logic for each phase.

Let me know if you have any questions or if there's anything else I can help you with!

117.7k
No comments yet, be the first!