Home > Enterprise >  how light works traffic simulation in python
how light works traffic simulation in python

Time:10-10

I'm trying to build a light for traffic simulation system I'm writing a light class which is represents a traffic signal like this

  • period, i.e. the number of time steps between two changes from green to red
  • green-period, i.e. the number of time steps where the signal is green. Like this pic:...

    The image above is how you explained it's supposed to work.


    The problem is in the first line of the method step, because time is always set to zero, and so the value "returned" (there's no return but I think you got it) will be always the same since the only "variable" always starts from the same value.

    def __init__(self, period, green_period):
        self.period = period
        self.green_period = green_period
        self.color = 'G'
        self.time = 0 # This variable will tell you which instant we're in
    

    Now that you have time as a variable attribute, you can re-write the step function this way.

    def step(self):
        self.time  = 1
        # If time is on green phase...
        if time%self.period < self.green_period: # [For example 9%7 < 3]
            # ...then turn it to green (doesn't matter if it's already green)
            self.color = 'G'
        else: # ...else, if the time isn't on green phase it must be on red phase
            self.color = 'R'
    

    This should work, I haven't tested it but I think it's very close to what you need.

  • Related