Beispiel #1
0
def main():
    car_1 = Car(tire_wash_strategy=WithoutBubbles(),
                carbody_wash_strategy=WithWax())
    car_1(car_model="Fiat Punto", wheel_diameter="16")

    car_2 = Car(WithBubbles(), WithoutWax())
    car_2(car_model="Volkswagen Passat", wheel_diameter="16")
Beispiel #2
0
    def find(self):
        print("Znajdź pojazd")
        print("-----------------")

        register_number = input('Numer rejestracyjny: ')

        try:
            status = input('(opcja) Status [d] - dostępny, [n] - niedostępny: ')
        except ValueError:
            status = None

        if status:
            cars = Car().select().where(
                (Car.register_number == register_number) &
                (CarStatus.name == ('Dostępny' if status == 'd' else 'Wypożyczony'))
            ).join(CarStatus)
        else:
            cars = Car().select().where(Car.register_number == register_number)

        result: List[Car] = []

        for car in cars:
            result.append(car)
            print(car.id, car, car.status)

        return result
Beispiel #3
0
class TestCar(unittest.TestCase):
    def setUp(self):
        plate_number = 'PCO-5649'
        self.car = Car(plate_number)

    def test_last_digit(self):
        self.assertEqual(self.car.last_digit(), '9')

    @patch.object(DayRule, '_load_rules', return_value={})
    @patch.object(DayRule, 'is_broken_by_digit')
    @patch.object(DayRule, 'is_broken_by_time')
    @data((True, False, False), (False, False, False), (False, True, False),
          (True, True, True))
    @unpack
    def test_is_breaking_the_rule(self, is_broken_by_time_return_value,
                                  is_broken_by_digit_return_value,
                                  expected_result, is_broken_by_time_mock,
                                  is_broken_by_digit_mock, mocked_rules):
        """
        @data: contains the values for the patched methods
        """
        is_broken_by_time_mock.return_value = is_broken_by_time_return_value
        is_broken_by_digit_mock.return_value = is_broken_by_digit_return_value
        any_rule = DayRule('2017-01-01')
        any_time = '00:00:00'
        self.assertEqual(self.car.is_breaking_the_rule(any_rule, any_time),
                         expected_result)
def simulate_collisions(log):
    """
    Simulates all the collisions of a log. Every simulation starts paused,
    pressing any key but ESC will start the simulation. All the cars that were
    present when the second collided car was created will be at their positions
    with their current speeds and directions. Pressing the ESC key will jump to
    the next collision, or end the simulation.
    :param log: <string> Name of the log with collisions.
    """
    log_directory = os.path.dirname(os.path.abspath(__file__)) + "/../logs/"
    all_cars_file = open(log_directory + "left_intersection" + log + ".log")
    collisions_file = open(log_directory + "collisions" + log + ".log")
    coordination_file = open(log_directory + "coordination" + log + ".log")

    all_cars = generate_left_intersection_cars_from_file(all_cars_file)
    collisions_cars, collided_cars_info = generate_collision_cars_from_file(
        collisions_file, all_cars
    )
    coordination_info = generate_coordination_info_from_file(coordination_file)

    collided_cars_info[0].sort(key=lambda this_car: this_car.get_name())

    screen, background, intersection_background, font = (
        init_graphic_environment(1468, 768)
    )
    full_intersection_rect = pygame.Rect(0, 0, 768, 768)

    infrastructure_supervisor = SupervisorCar(-1)
    # infrastructure_supervisor.set_active_supervisory(True)
    screen_width = 1468
    creation_dummy_cars = []
    initial_coordinates = [
        (435, 760, 0, 0),
        (760, 345, 90, 1),
        (345, 10, 180, 2),
        (10, 435, 270, 3)
    ]
    for coordinates in initial_coordinates:
        dummy_car = Car(
            -1,
            coordinates[0],
            coordinates[1],
            direction=coordinates[2],
            lane=coordinates[3]
        )
        dummy_car.new_image()
        creation_dummy_cars.append(dummy_car)
    for key in collided_cars_info:
        cars = []
        messages = []
        new_messages = []
        collision_wait = True
        iteration = True
        print [str(car) for car in collided_cars_info[key]]
Beispiel #5
0
    def test_car_parked_already(self):
        # Arrange
        lh = LotHandler(2)
        firstCar = Car('KA-01-HH-1234', 'White')
        duplicateCar = Car('KA-01-HH-1234', 'White')

        # Act
        lh.FillSlot(firstCar, 1)
        lh.FillSlot(duplicateCar, 2)

        # Assert
        self.assertTrue(lh.IsCarParked(duplicateCar))
Beispiel #6
0
    def test_vaccate_slot(self):
        # Arrange
        lh = LotHandler(2)
        firstCar = Car('KA-01-HH-1234', 'White')
        secondCar = Car('KA-01-BB-0001', 'Red')

        lh.FillSlot(firstCar, 1)
        lh.FillSlot(secondCar, 2)

        slotNumToVaccate = 1
        lh.VaccateSlot(slotNumToVaccate)
        self.assertTrue(slotNumToVaccate in lh.freeSlots)
        self.assertTrue(2 not in lh.freeSlots)
Beispiel #7
0
 def test_update_car_coordinates_when_called_with_same_coords_speed_equals_0(
         self):
     car = Car(0, 0, 0, 1)
     car_coords = {
         'timestamp': 1,
         'carIndex': 1,
         'location': {
             'lat': 0,
             'long': 0
         }
     }
     car.update_car_coordinates(car_coords)
     assert car.curr_speed == 0
Beispiel #8
0
 def test_update_car_coordinates_when_called_normally_returns_updated_ts(
         self):
     car = Car(0, 0, 0, 1)
     car_coords = {
         'timestamp': 3600000,
         'carIndex': 1,
         'location': {
             'lat': 0.01,
             'long': 0
         }
     }
     car.update_car_coordinates(car_coords)
     assert car.get_car_timestamp() == 3600000
Beispiel #9
0
 def test_update_car_coordinates_when_called_with_same_ts_distance_equals_0(
         self):
     car = Car(0, 0, 0, 1)
     car_coords = {
         'timestamp': 0,
         'carIndex': 1,
         'location': {
             'lat': 1,
             'long': 1
         }
     }
     car.update_car_coordinates(car_coords)
     assert car.distance_travelled == 0
Beispiel #10
0
 def test_update_car_coordinates_when_called_normally_returns_correct_distance_travelled(
         self):
     car = Car(0, 0, 0, 1)
     car_coords = {
         'timestamp': 3600000,
         'carIndex': 1,
         'location': {
             'lat': 0.01,
             'long': 0
         }
     }
     # Calculated value of this transtion = 0.6870766960504942
     car.update_car_coordinates(car_coords)
     assert car.distance_travelled == 0.6870766960504942
Beispiel #11
0
    def test_vaccate_slot_not_present(self):
        # Arrange
        lh = LotHandler(2)
        firstCar = Car('KA-01-HH-1234', 'White')
        secondCar = Car('KA-01-BB-0001', 'Red')

        lh.FillSlot(firstCar, 1)
        lh.FillSlot(secondCar, 2)

        slotNumToVaccate = 3
        with self.assertRaises(ValueError) as ex:
            lh.VaccateSlot(slotNumToVaccate)
        self.assertEqual(ex.exception,
                         'No such Slot Number found in Parking lots')
Beispiel #12
0
def import_data(car_instance_list: list, driver_instance_list: list) -> None:
    """
    Import saved data into the respective instance lists

    Args:
        car_instance_list (list): Car instance list
        driver_instance_list (list): Driver instance list
    """
    try:
        with open("data/cars.json", 'r') as cars_file:
            json_ = json.load(cars_file)
            cars_ = json_["cars"]
            for car_ in cars_:
                car_instance_list.append(
                    Car(car_["id"], car_["reg"], car_["brand"], car_["hp"],
                        car_["kms"]))
    except FileNotFoundError:
        from ui.console_messages import warning
        warning("cars.json doesn't exist! -> Cars not loaded")

    try:
        with open("data/drivers.json", 'r') as drivers_file:
            json_ = json.load(drivers_file)
            drivers_ = json_["drivers"]
            for driver_ in drivers_:
                car_for_driver = return_right_car(driver_["car_id"],
                                                  car_instance_list)

                driver_instance_list.append(
                    Driver(driver_["id"], driver_["name"], driver_["age"],
                           car_for_driver))
    except FileNotFoundError:
        from ui.console_messages import warning
        warning("drivers.json doesn't exist! -> Drivers not loaded loaded")
Beispiel #13
0
 def seed_cars(self):
     for c in cars:
         car = Car(
             plate=c["plate"],
             client_id=c["client_id"],
         )
         session.add(car)
Beispiel #14
0
    def test_check_car_already_parked(self):
        s = EntryService()
        s.InitializeParkingLot(4)
        s.lotHandler.IsCarParked = MagicMock(return_value=True)

        result = s.CheckCarParkedAlready(Car('KA-01-HH-1234', 'White'))
        self.assertTrue(result)
Beispiel #15
0
    def park_car(self, registration_number, color):
        """
        :param registration_number: Registration Number of the car
        :param color: Color of the car
        :return:

        Desc:
        1. Creates a car object with given details of the car
        2. Checks for the availability of the slot
        3. If available assigns the Slot and returns the associated slot number
        4. Else returns the error message
        """
        if not self.parking_lot.are_slots_available():
            # no slots are available i.e parking lot is full and cannot accomadate any more cars
            return errors.PARKING_LOT_IS_FULL

        if self.check_car_already_parked(
                registration_number=registration_number):
            return errors.CAR_ALREADY_PARKED

        car = Car(regnumber=registration_number, color=color)
        slot = self.parking_lot.get_available_slot()
        if not slot:
            return errors.PARKING_LOT_IS_FULL

        self.parking_lot.allocate_parking(car=car, slot=slot)
        return 'Allocated slot number: {}'.format(slot.slotNumber)
Beispiel #16
0
    def test_is_slot_available(self):
        # Arrange
        lh = LotHandler(2)
        firstCar = Car('KA-01-HH-1234', 'White')

        # Act
        filledSlot = lh.FillSlot(firstCar, 1)

        # Assert
        self.assertFalse(lh.IsSlotAvailable(filledSlot.SlotNum))
        self.assertTrue(lh.IsSlotAvailable(2))
    def post(self):

        carBusiness = CarBusiness()

        car = request.json['car']
        new_car = Car(car['model'], car['brand'], car['price'], car['year'],
                      car['car_type'])

        car = carBusiness.saveCar(new_car)

        return car, 201
Beispiel #18
0
    def test_get_nearest_slot(self):
        # Arrange
        lh = LotHandler(4)
        car1 = Car('KA-01-HH-1234', 'White')
        car2 = Car('KA-04-HH-1231', 'Blue')
        car3 = Car('KA-04-HH-1231', 'Red')
        car4 = Car('KA-04-HH-1231', 'Blue')

        lh.FillSlot(car1, 1)
        lh.FillSlot(car2, 2)
        lh.FillSlot(car3, 3)
        lh.FillSlot(car4, 4)

        lh.VaccateSlot(2)
        lh.VaccateSlot(4)

        # Act
        val = lh.GetNearestSlot()
        # Assert
        self.assertEqual(val, 2)
def select_all():
    cars = []

    sql = "SELECT * FROM cars ORDER BY mot_renewal_date ASC, registration_number ASC"
    results = run_sql(sql)

    for row in results:
        car = Car(row['registration_number'], row['make'], row['model'],
                  row['mot_renewal_date'], row['id'])
        cars.append(car)

    return cars
Beispiel #20
0
    def test_allow_entry_parking_lot_full(self):
        # Arrange
        car = Car('KA-01-HH-1234', 'White')
        s = EntryService()
        s.InitializeParkingLot(6)
        s.lotHandler.IsLotFull = MagicMock(return_value=True)

        # Act
        status = s.allow(car)

        # Assert
        self.assertEqual(status, 'Sorry, parking lot is full')
Beispiel #21
0
    def test_fill_slot_invalid_slot_num(self):
        # Arrange
        lh = LotHandler(2)
        firstCar = Car('KA-01-HH-1234', 'White')

        # Act
        with self.assertRaises(ValueError) as ex:
            lh.FillSlot(firstCar, 3)

        # Assert
        self.assertEqual('No Such Slot Number foudn in Parking Lot',
                         str(ex.exception))
Beispiel #22
0
    def test_allow_re_park_car(self):
        # Arrange
        car = Car('KA-01-HH-1234', 'White')
        s = EntryService()
        s.InitializeParkingLot(6)
        s.lotHandler.IsCarParked = MagicMock(return_value=True)

        # Act
        status = s.allow(car)

        # Assert
        self.assertEqual(
            'Cannot park already Parked Car: {0}'.format(car.RegNum), status)
Beispiel #23
0
    def test_get_slot_num_by_reg_num(self):
        # Arrange
        lh = LotHandler(4)
        car1 = Car('KA-01-HH-1234', 'White')
        car2 = Car('KA-04-HH-1231', 'Blue')
        car3 = Car('KA-08-HH-1111', 'Red')
        car4 = Car('KA-02-HH-9999', 'Blue')

        lh.FillSlot(car1, 1)
        lh.FillSlot(car2, 2)
        lh.FillSlot(car3, 3)
        lh.FillSlot(car4, 4)

        expectedSlotNum = '2'

        # Act
        actualSlotNum = lh.GetSlotNumByRegNum('KA-04-HH-1231')
        actualNotFound = lh.GetSlotNumByRegNum('KA-04-HH-3333')

        # Assert
        self.assertEqual(expectedSlotNum, actualSlotNum)
        self.assertEqual('Not Found', actualNotFound)
Beispiel #24
0
    def test_get_slot_nums_by_color(self):
        # Arrange
        lh = LotHandler(4)
        car1 = Car('KA-01-HH-1234', 'White')
        car2 = Car('KA-04-HH-1231', 'Blue')
        car3 = Car('KA-08-HH-1111', 'Red')
        car4 = Car('KA-02-HH-9999', 'Blue')

        lh.FillSlot(car1, 1)
        lh.FillSlot(car2, 2)
        lh.FillSlot(car3, 3)
        lh.FillSlot(car4, 4)

        expectedBlueSlots = ['2', '4']
        expectedRedslots = ['3']

        # Act
        actualBlueSlots = lh.GetSlotNumsByColor('Blue')
        actualRedSlots = lh.GetSlotNumsByColor('Red')
        actualYellowSlots = lh.GetSlotNumsByColor('Yellow')
        # Assert
        self.assertEqual(expectedBlueSlots, actualBlueSlots)
        self.assertEqual(expectedRedslots, actualRedSlots)
        self.assertEqual([], actualYellowSlots)
def create_car():

    registration_number = request.form['registration_number']
    make = request.form['make']
    model = request.form['model']
    mot_renewal_date = request.form['mot_renewal_date']

    car = Car(registration_number, make, model, mot_renewal_date)

    # send request to save mechanic to database
    car_repository.save(car)

    # return to mechanics webpage
    return redirect('/cars')
    
def select(id):
    car = None

    sql = "SELECT * FROM cars WHERE id = %s"
    values = [id]

    result = run_sql(
        sql, values
    )[0]  # although only 1 row should be returned, making sure with the [0]..?

    if result is not None:
        car = Car(result['registration_number'], result['make'],
                  result['model'], result['mot_renewal_date'], result['id'])

    return car
Beispiel #27
0
    def test_fill_slot(self):
        # Arrange
        lh = LotHandler(2)
        firstCar = Car('KA-01-HH-1234', 'White')
        secondCar = Car('KA-01-HH-1231', 'Red')

        # Act
        filledSlot1 = lh.FillSlot(firstCar, 1)

        # Assert firstCar
        self.assertEqual(filledSlot1.SlotNum, 1)
        self.assertFalse(filledSlot1.IsAvailable)
        self.assertEqual(filledSlot1.ParkedCar, firstCar)
        self.assertFalse(lh.IsLotFull())

        # Act secondCar

        filledSlot2 = lh.FillSlot(secondCar, 2)
        # Assert secondCar
        self.assertEqual(filledSlot2.SlotNum, 2)
        self.assertFalse(filledSlot2.IsAvailable)
        self.assertEqual(filledSlot2.ParkedCar, secondCar)

        self.assertTrue(lh.IsLotFull())
Beispiel #28
0
    def test_get_reg_nums_by_color(self):
        # Arrange
        lh = LotHandler(4)
        car1 = Car('KA-01-HH-1234', 'White')
        car2 = Car('KA-04-HH-1231', 'Blue')
        car3 = Car('KA-04-HH-1231', 'Red')
        car4 = Car('KA-04-HH-1231', 'Blue')

        lh.FillSlot(car1, 1)
        lh.FillSlot(car2, 2)
        lh.FillSlot(car3, 3)
        lh.FillSlot(car4, 4)

        expectedBlueRegNums = ['KA-04-HH-1231', 'KA-04-HH-1231']
        expectedRedRegNums = ['KA-04-HH-1231']

        # Act
        actualBlueRegNums = lh.GetRegNumsByColor('Blue')
        actualRedRegNums = lh.GetRegNumsByColor('Red')
        actualYellowRegNums = lh.GetRegNumsByColor('Yellow')
        # Assert
        self.assertEqual(expectedBlueRegNums, actualBlueRegNums)
        self.assertEqual(expectedRedRegNums, actualRedRegNums)
        self.assertEqual([], actualYellowRegNums)
Beispiel #29
0
    def post(self):
        """
        Create new car.
        """
        parsed_args = parser.parse_args()
        car = Car(
            plate=parsed_args["plate"],
            client_id=parsed_args["client_id"],
            brand=parsed_args["brand"],
        )

        client = (
            session.query(Client).filter(Client.id == parsed_args["client_id"]).first()
        )
        client.cars.append(car)
        return self.finalize_post_req(car)
Beispiel #30
0
    def test_allow_slot_unavailable(self):
        # Arrange
        car = Car('KA-01-HH-1234', 'White')
        s = EntryService()
        s.InitializeParkingLot(6)
        s.lotHandler.IsCarParked = MagicMock(return_value=False)
        s.lotHandler.IsLotFull = MagicMock(return_value=False)
        s.lotHandler.GetNearestSlot = MagicMock(return_value=1)
        s.lotHandler.IsSlotAvailable = MagicMock(return_value=False)

        # Act
        with self.assertRaises(ValueError) as ex:
            s.allow(car)

        # Assert
        self.assertEqual('Slot Not Available'.format(car.RegNum),
                         str(ex.exception))
Beispiel #31
0
    def test_allow_park_car(self):
        # Arrange
        car = Car('KA-01-HH-1234', 'White')
        s = EntryService()
        s.InitializeParkingLot(6)
        s.lotHandler.IsCarParked = MagicMock(return_value=False)
        s.lotHandler.IsLotFull = MagicMock(return_value=False)
        s.lotHandler.GetNearestSlot = MagicMock(return_value=1)
        s.lotHandler.IsSlotAvailable = MagicMock(return_value=True)

        slot = Slot(1)
        s.lotHandler.FillSlot = MagicMock(return_value=slot)

        # Act
        status = s.allow(car)

        # Assert
        self.assertEqual(status, 'Allocated slot number: {0}'.format(1))
def main_simulation(graphic_environment, limit, stand_still_param=5, fix=True,
                    *args, **kwargs):
    distributed = "distributed" in args
    log = "log" in kwargs
    show_virtual_caravan = "show_caravan" in args
    initial_speed = -1
    if "initial_speed" in kwargs:
        initial_speed = kwargs["initial_speed"]
    if log:
        log_name = kwargs["log"]
        create_logs(log_name)
        collision_log = logging.getLogger('collision{}'.format(log_name))
        left_intersection_log = logging.getLogger(
            'left_intersection{}'.format(log_name)
        )
        total_cars_log = logging.getLogger(
            'numbers_of_cars{}'.format(log_name)
        )
        coordination_log = logging.getLogger('coordination{}'.format(log_name))
    cars = {}
    iteration = True
    intersection_rect = pygame.Rect(280, 280, 210, 210)
    collisions = 0
    collision_list = []

    if graphic_environment:
        screen_width = 768
        if show_virtual_caravan:
            screen_width = 1468
        screen, background, intersection_background, font = (
            init_graphic_environment(screen_width, 768)
        )

    full_intersection_rect = pygame.Rect(0, 0, 768, 768)
    counter = 0
    car_name_counter = 0
    cars_per_second = 4
    collision = False
    min_speed = 20
    max_speed = 20
    not_created_vehicles = 0
    collision_wait = False
    display_time_counter = 0
    lanes_waiting_time = [(0, 0), (0, 0), (0, 0), (0, 0)]
    rate = 0.1
    number_of_lanes = 4

    infrastructure_supervisor = InfrastructureCar(-1, fix=fix)
    if not distributed:
        infrastructure_supervisor.new_image()
        cars[-1] = infrastructure_supervisor

    for i in range(len(lanes_waiting_time)):
        lane = lanes_waiting_time[i]
        lanes_waiting_time[i] = (np.random.exponential(1.0/rate), lane[1])
    print_collision_message = True

    collided_car_surface = pygame.Surface((50, 50))
    collided_car_surface.fill((255, 0, 0, 0))
    messages = []
    new_messages = []
    creation_dummy_cars = []
    initial_coordinates_per_lane = [
        (435, 760, 0, 0),
        (760, 345, 90, 1),
        (345, 10, 180, 2),
        (10, 435, 270, 3)
    ]
    for coordinates in initial_coordinates_per_lane:
        dummy_car = Car(
            -1,
            coordinates[0],
            coordinates[1],
            direction=coordinates[2],
            lane=coordinates[3]
        )
        dummy_car.new_image(0.1)
        creation_dummy_cars.append(dummy_car)

    while iteration and car_name_counter < limit:
        if not collision_wait or not graphic_environment:
            display_time_counter += 1
            counter += 1
            for lane in range(len(lanes_waiting_time)):
                if not creation_dummy_cars[lane].collide(cars.values()):
                    lanes_waiting_time[lane] = (
                        lanes_waiting_time[lane][0],
                        lanes_waiting_time[lane][1] + 1
                    )
                if lanes_waiting_time[lane][0] <= lanes_waiting_time[lane][1]:
                    new_car = random_car(
                        car_name_counter,
                        min_speed,
                        max_speed,
                        counter,
                        number_of_lanes,
                        fix,
                        stand_still_param,
                        lane=lane,
                        initial_speed=initial_speed
                    )
                    new_car.new_image()
                    lanes_waiting_time[lane] = (
                        np.random.exponential(1.0 / rate),
                        0
                    )
                    # not supervisor(cars) and
                    # not supervisor_message(messages):
                    if len(cars) == 0:
                        new_car.__class__ = SupervisorCar
                    cars[car_name_counter] = new_car
                    new_messages.append(NewCarMessage(new_car))
                    car_name_counter += 1
                    if car_name_counter % 500 == 0:
                        print str(car_name_counter) + " cars created"
            left_intersection_cars = []
            left_intersection_cars_log = []
            messages.sort(
                key=lambda not_sorted_message: not_sorted_message.get_value(),
                reverse=True
            )
            for car in cars.values():
                for message in messages:
                    message.process(car)
                car.update()
                for new_message in car.get_new_messages():
                    new_messages.append(new_message)
                car.set_new_messages([])
                if not car.screen_car.colliderect(full_intersection_rect):
                    left_intersection_cars.append(car)
                    car.set_left_intersection_time(counter)
                    if car.get_left_intersection_messages() is not None:
                        new_messages.append(
                            car.get_left_intersection_messages()
                        )
                    if log:
                        left_intersection_cars_log.append(car)
            for left_car in left_intersection_cars:
                del cars[left_car.get_name()]
            messages = new_messages
            new_messages = []
            collided_cars, collide = colliding_cars(cars.values())
            if log:
                car_in_intersection = (
                    collide and
                    collided_cars[0].screen_car.colliderect(intersection_rect)
                )
                collision_message_dict = {}
                if (collide and car_in_intersection):
                    collision_code = "{}to{}".format(
                        collided_cars[0].get_name(),
                        collided_cars[1].get_name()
                    )
                    if collision_code not in collision_list:
                        collision = True
                        collision_wait = True
                        collision_list.append(collision_code)
                        collisions += 1
                        collision_message_dict["collision_code"] = (
                            collision_code
                        )
                        collision_message_dict[
                            "collision_initial_conditions"
                        ] = [car.to_json() for car in cars.values]
                        # collision_message = (
                        #     '{"collision_code":" {}", '
                        #     '"collision_initial_conditions":['
                        # ).format(collision_code)
                        # for car in cars.values():
                        #     collision_message += car.to_json() + ','
                        collision_message_dict['collided_cars'] = [
                            [car.to_json() for car in collided_cars]
                        ]
                        # collision_message = (
                        #     '{}],"collided_cars":['.format(
                        #         collision_message[
                        #             :len(collision_message)-1
                        #         ]
                        #     )
                        # )
                        # for car in collided_cars:
                        #     collision_message += car.to_json() + ','
                        # collision_message = '{}]}'.format(
                        #     collision_message[:len(collision_message) - 1]
                        # )
                supervisor_car = get_supervisor(cars.values())
                if supervisor_car is not None:
                    for message in supervisor_car.get_log_messages():
                        try:
                            message["coordinated_car"].set_x_position(
                                cars[
                                    message["coordinated_car"].get_name()
                                ].get_x_position()
                            )
                            message["coordinated_car"].set_y_position(
                                cars[
                                    message["coordinated_car"].get_name()
                                ].get_y_position()
                            )
                            message["coordinated_car"].set_direction(
                                cars[
                                    message["coordinated_car"].get_name()
                                ].get_direction()
                            )
                            message["coordinated_car"].set_speed(
                                cars[
                                    message["coordinated_car"].get_name()
                                ].get_speed()
                            )
                            log_message = {}
                            log_message["coordinated_car"] = (
                                message["coordinated_car"].to_json()
                            )
                            log_message["car_order"] = []
                            for car in message["old_cars"]:
                                for old_car in cars.values():
                                    if old_car.get_name() == car.get_name():
                                        car.set_x_position(
                                            old_car.get_x_position())
                                        car.set_y_position(
                                            old_car.get_y_position())
                                        car.set_direction(
                                            old_car.get_direction())
                                        car.set_speed(old_car.get_speed())
                                        break
                                log_message["car_order"].append(car.to_json())
                            log_message["selected_car"] = (
                                message["selected_car"].to_json()
                            )
                            coordination_log.info(log_message)
                        except KeyError:
                            pass
                    supervisor_car.set_log_messages([])
                if collision:
                    collision_log.info(str(collision_message_dict))
                    collision = False
                    return -1
                log_threshold_passed = (
                    car_name_counter % 250.0 == 0
                )
                cars_passed = counter % (60.0 / cars_per_second) == 0
                if log_threshold_passed and cars_passed:
                    message_dict = {"cars_simulated": car_name_counter}
                    total_cars_log.info(message_dict)
                if len(left_intersection_cars_log) > 1:
                    left_intersection_log.info(
                        [car.to_json() for car in left_intersection_cars_log]
                    )
            if graphic_environment:
                events = pygame.event.get()
                supervisor_car = get_supervisor(cars.values())
                if coordinator_fail(events) and supervisor_car:
                    supervisor_car.attack_supervisor = True
                if coordinator_lies(events) and supervisor_car:
                    supervisor_car.supervisor_lies = True
                iteration = not check_close_application(events)
                collision_wait = continue_simulation(events) or collision_wait
                screen.blit(background, (0, 0))
                screen.blit(intersection_background, (0, 0))
                for car in cars.values():
                    screen.blit(car.rotated_image, car.screen_car)
                    display_info_on_car(car, screen, font, 1)
                if show_virtual_caravan:
                    show_caravan(
                        cars.values(),
                        screen,
                        font,
                        collided_cars,
                        screen_width
                    )
                pygame.display.update(screen.get_rect())
        else:
            if print_collision_message:
                print_collision_message = False
                supervisor_car = get_supervisor(cars.values())
                # if supervisor_car is not None:
                #     sys.stdout.write(
                #         "\r{}".format(
                #             supervisor_car.get_transmitter_receiver_dict()
                #         )
                #     )
                # sys.stdout.flush()
                display_time_counter = 0
            events = pygame.event.get()
            iteration = not check_close_application(events)
            collision_wait = not continue_simulation(events)
            if not collision_wait:
                print_collision_message = True
    if graphic_environment:
        pygame.display.quit()
    print (
        "\nLast record. Total collisions: {}\nNot created vehicles: {}\nNumber"
        " of ticks: {}"
    ).format(collisions, not_created_vehicles, counter)
    return 0
def generate_coordination_info_from_file(coordination_file):
    """
    Generates the cars that were present when a car was created. Used for
    collision simulation purposes.
    :param coordination_file: file with the json information.
    :return: dict with list of car. The key is the car that was created.
    """
    coordination_info = {}
    for line in coordination_file:
        try:
            coordination = JSONDecoder().decode(
                line[:len(line) - 2].replace("None", "-1")
            )['message']
            coordination_info[coordination["coordinated_car"]["name"]] = []
            for car_information in coordination["car_order"]:
                car = Car(
                    car_information["name"],
                    pos_x=car_information[
                        "actual_coordinates"]["x_coordinate"],
                    pos_y=car_information[
                        "actual_coordinates"]["y_coordinate"],
                    absolute_speed=car_information["speed"],
                    direction=car_information[
                        "actual_coordinates"]["direction"],
                    lane=car_information["lane"],
                    intention=car_information["intention"],
                    creation_time=car_information["creation_time"]
                )
                car.set_origin_coordinates(car.get_lane())
                car.set_registered_caravan_depth(
                    car_information["actual_caravan_depth"]
                )
                car.set_following(True)
                coordination_info[
                    coordination["coordinated_car"]["name"]].append(car)
            same_car = Car(
                coordination["coordinated_car"]["name"],
                pos_x=coordination[
                    "coordinated_car"]["actual_coordinates"]["x_coordinate"],
                pos_y=coordination[
                    "coordinated_car"]["actual_coordinates"]["y_coordinate"],
                absolute_speed=coordination["coordinated_car"]["speed"],
                direction=coordination[
                    "coordinated_car"]["actual_coordinates"]["direction"],
                lane=coordination["coordinated_car"]["lane"],
                intention=coordination["coordinated_car"]["intention"],
                creation_time=coordination["coordinated_car"]["creation_time"]
            )
            same_car.set_origin_coordinates(same_car.get_lane())
            same_car.set_registered_caravan_depth(
                coordination["coordinated_car"]["actual_caravan_depth"]
            )
            same_car.set_following(True)
            coordination_info[
                coordination["coordinated_car"]["name"]].append(same_car)
        except KeyError:
            print line
    return coordination_info