I am making a car traffic simulation using python. I don't know how I will add a delay on the start of each car. I need to put a delay on the start of each car every time they move after a stop or red light.
import random
class Car:
counter = 0
def __init__(self, position, latency, back_position, length):
self.position = position
self.latency = latency
self.back_position = back_position
self.length = length
self.allowed_to_move = True
Car.counter += 1
self.name = f"car{Car.counter}" #car namer
num_cars = int(input("How many cars do you want to generate? "))
cars = []
for i in range(num_cars):
if i == 0:
position = 0
else:
position = cars[i-1].back_position - 1
latency = 3
length = random.randint(3, 5)
back_position = position - length
car = Car(position, latency, back_position, length)
cars.append(car)
print(f"Generated {num_cars} cars with random positions, latencies, and lengths:")
for car in cars:
print(f"{car.name} at position {car.position} with latency {car.latency} and length {car.length}")
position = 0
timer = 0
while True:
# Checker ng track kung lahat nakalampas na
if all(car.position >= 100 for car in cars):
print("All cars have reached the end of the track!")
break
position += 1
timer += 1
colors = [1] * 10 + [2] * 2 + [3] * 10 + [2] * 2
color = colors[timer % len(colors)]
if color == 1:
traffic_color = "red"
elif color == 2:
traffic_color = "orange"
else:
traffic_color = "green"
print(f"Number: {timer}, Traffic color: {traffic_color}")
for i, car in enumerate(cars):
if car.position >= 100:
continue
# Check traffic light color at kung may kotse sa harap
if position % 10 == 0 and position != 100:
while traffic_color != "green":
print(f"Number: {timer}, Waiting for green light...")
timer += 1
color = colors[timer % len(colors)]
if color == 1:
traffic_color = "red"
elif color == 2:
traffic_color = "orange"
else:
traffic_color = "green"
print(f"Number: {timer}, Traffic color: {traffic_color}")
if traffic_color == "green":
if i == 0:
cars[i].allowed_to_move = True
cars[i+1].allowed_to_move = True
elif i == len(cars) - 1:
cars[i].allowed_to_move = True
cars[i-1].allowed_to_move = True
else:
cars[i].allowed_to_move = True
if cars[i-1].back_position != cars[i+1].position + 1:
cars[i-1].allowed_to_move = True
cars[i+1].allowed_to_move = True
else:
cars[i-1].allowed_to_move = False
cars[i+1].allowed_to_move = False
else:
cars[i].allowed_to_move = True
if cars[i].allowed_to_move:
cars[i].position += 1
cars[i].back_position += 1
print(f"{car.name} moved to position {car.position}")