0 svar
143 visningar
Enbjörn 18
Postad: 13 dec 2023 16:21 Redigerad: 13 dec 2023 16:22

Simulering

 Jag ska programmera en kod där jag ska simulerar trafik och skapa en väg där det är ett rödljus mellan. Koden fungerar bra, men blir fel när rödljuset blir rött och bilarna stannar. Min teori är att vägen fortsätter fyllas med bilar trots att vägen är full. Jag vill skapa en "kö" med bilar innan vägen. Men vet inte riktigt hur jag går tillväga. Har någon något bra förslag?

 

Detta har jag programmerat hittills:

from trafficComponents import Lane
from trafficComponents import Light
from trafficComponents import Vehicle
from statistics import mean, median
from time import sleep
import destinations
from destinations import DestinationGenerator
import trafficComponents as tc


class TrafficSystem:
    """Represents a traffic system with files, signals"""
    # constructor that creates two files, a signal and a DestinationGenerator object.
    def __init__(self):
        self.file1 = Lane(5) 
        self.signal = Light(10, 8)  
        self.file2 = Lane(5)  
        self.destination_generator = DestinationGenerator() 
        self.time = 0

    def snapshot(self):
        """Print a snapshot of the current state of the system."""
        #__str__ methods of the various components.
        print(f'Time: {self.time} {self.file1} {self.signal} {self.file2}')

    def step(self):
        """Take one time step for all components."""
        # Take out the first vehicle from the first file in the figure.
        first_vehicle = self.file1.remove_first()

        # Step the first file using its step method.
        self.file1.step()

        # Check If the signal is green, then move the first vehicle in the second (right) lane to the first lane.
        if self.signal.is_green() and self.file2.get_first():
            vehicle = self.file2.remove_first()
            self.file1.enter(vehicle)

        # Step the light signal with its step method.
        self.signal.step()

        # Step the second file.
        self.file2.step()

        # Call the step method on the DestinationGenerator object
        destination = self.destination_generator.step()
        
        '''
        If this returns a destination (ie something other than None) 
        then create a vehicle and put it last in the second file.
        '''
        if destination:
            vehicle = Vehicle(destination, self.time)
            self.file2.enter(vehicle)

        self.time += 1

def main():
    ts = TrafficSystem()
    for i in range(100):
        ts.snapshot()
        ts.step()
        sleep(0.1) # Pause for 0.1 s.
    print('\nFinal state:')
    ts.snapshot()
    print()


if __name__ == '__main__':
    main()
Svara
Close