def read_source_file(file_name, weather_file_name):
    with open(file_name, 'r') as readCollision:  # r represent read model
        print("Start to read file: " + file_name +
              ". This may take a while...")
        file = csv.reader(readCollision)
        for row in file:
            if "COLLISION_ID" not in row[0]:
                collision = Collision()
                collision.collision_id = row[0]
                collision.location_key = row[1]
                collision.hour_key = row[2]
                collision.environment = row[3]
                collision.light = row[4]
                collision.surface_condition = row[5]
                collision.traffic_control = row[6]
                collision.traffic_control_condition = row[7]
                collision.collision_classification = row[8]
                collision.impace_type = row[9]
                collision.no_of_pedestrians = row[10]
                collision.date = row[11]
                collision.location = row[12]
                collision.is_intersection = row[13]
                collisions.append(collision)
    readCollision.close()

    with open(weather_file_name, 'r') as readWeather:  # r represent read model
        print("Start to read file: " + weather_file_name +
              ". This may take a while...")
        file = csv.reader(readWeather)
        key_ctr = 0
        for row in file:
            weathers.append(row)
            # print(row[0]+" @ "+row[24])
    readWeather.close()
Beispiel #2
0
 def __init__(self, obsX, obsY, obsWidth, obsHeight):
     self.obsX = obsX
     self.obsY = obsY
     self.obsWidth = obsWidth
     self.obsHeight = obsHeight
     self.collider = Collision(self.obsX, self.obsY, self.obsWidth, self.obsHeight)
     self.obsColor = self.OBS_COLOR[int(random(0,len(self.OBS_COLOR) ) )]
Beispiel #3
0
def accident_processor(collision_file_name, hour_file_name, location_file_name):
    """
    Retrieve data about the time, in hour, of the ottawa's collision record from a csv file.
    :param collision_file_name: The name of the collision file, which has been generated from preprocessor
    :param hour_file_name: The processed hour table file
    :param location_file_name: the processed location table file
    """
    global total_record
    global total_valid_record
    hours = []
    locations = []
    collisions = []
    with open(hour_file_name, 'r') as readHour:  # r represent read model
        print("Start to read file: " + hour_file_name + ". This may take a while...")
        file = csv.reader(readHour)
        for row in file:
            if "HOUR_ID" not in row[0]:
                hour_id = row[0]
                hours.append(hour_id)
    readHour.close()

    print("Finished reading data from hour table")

    with open(location_file_name, 'r') as readLocation:  # r represent read model
        print("Start to read file: " + location_file_name + ". This may take a while...")
        file = csv.reader(readLocation)
        for row in file:
            if "LOCATION_ID" not in row[0]:
                location_id = row[0]
                locations.append(location_id)
    readLocation.close()

    print("Finished reading data from location table")

    with open(collision_file_name, 'r') as readCollision:  # r represent read model
        print("Start to read file: " + collision_file_name + ". This may take a while...")
        file = csv.reader(readCollision)
        ptr = 0
        for row in file:
            if "COLLISION_ID" not in row[0]:
                collision = Collision()
                collision.collision_id = row[0]
                collision.location_id = locations[ptr]  # append corresponding id
                collision.hour_id = hours[ptr]  # append corresponding id
                collision.environment = row[6]
                collision.light = row[7]
                collision.surface_condition = row[8]
                collision.traffic_control = row[9]
                collision.traffic_control_condition = row[10]
                collision.collision_classification = row[11]
                collision.impace_type = row[12]
                collision.no_of_pedestrians = row[13]
                ptr = ptr + 1
                collisions.append(collision)
    readCollision.close()

    print("Finished processing collision table")

    return collisions
Beispiel #4
0
 def drawSelf(self):
     pushMatrix()
     rectMode(CENTER)
     fill(self.obsColor) 
     strokeWeight(3)
     stroke(self.OBS_STROKE)
     rect(self.obsX, self.obsY, self.obsWidth, self.obsHeight)
     self.collider = Collision(self.obsX, self.obsY, self.obsWidth, self.obsHeight)
     popMatrix()    
Beispiel #5
0
 def __init__(self, playerX, playerY, borderSize, playerSize=PLAYER_SIZE):
     self.xVariance = random(0, 4)
     self.yVariance = random(0, 4)
     self.PLAYER_SIZE = playerSize
     self.playerX = playerX - self.PLAYER_SIZE / 2
     self.playerY = playerY - self.PLAYER_SIZE / 2
     self.playerYBot = height - borderSize - self.PLAYER_SIZE / 2
     self.playerYTop = borderSize + self.PLAYER_SIZE / 2
     self.collider = Collision(self.playerX, self.playerY, self.PLAYER_SIZE,
                               self.PLAYER_SIZE)
Beispiel #6
0
 def drawPlayer(self):
     pushMatrix()
     fill(self.PLAYER_COLOR)
     strokeWeight(3)
     if (self.PLAYER_SIZE == 50):
         stroke(self.PLAYER_STROKE)
     else:
         noStroke()
     self.collider = Collision(self.playerX, self.playerY, self.PLAYER_SIZE,
                               self.PLAYER_SIZE)
     rect(self.playerX, self.playerY, self.PLAYER_SIZE, self.PLAYER_SIZE)
     popMatrix()
def read_source_file(file_name, hour_file_name):
    with open(file_name, 'r') as readCollision:  # r represent read model
        print("Start to read file: " + file_name +
              ". This may take a while...")
        file = csv.reader(readCollision)
        for row in file:
            if "COLLISION_ID" not in row[0]:
                collision = Collision()
                collision.collision_id = row[0]
                collision.location_key = row[1]
                collision.hour_key = row[2]
                collision.weather_key = row[3]
                collision.environment = row[4]
                collision.light = row[5]
                collision.surface_condition = row[6]
                collision.traffic_control = row[7]
                collision.traffic_control_condition = row[8]
                collision.collision_classification = row[9]
                collision.impace_type = row[10]
                collision.no_of_pedestrians = row[11]
                collision.date = row[12]
                collision.location = row[13]
                collision.is_intersection = row[14]
                collisions.append(collision)
    readCollision.close()

    with open(hour_file_name, 'r') as readHour:  # r represent read model
        print("Start to read file: " + hour_file_name +
              ". This may take a while...")
        file = csv.reader(readHour)
        for row in file:
            if "EVENT_ID" not in row[0]:
                event = Event()
                event.event_id = row[0]
                event.event_name = row[1]
                event.event_start_date = row[2]
                event.event_end_date = row[3]
                if int(event.event_start_date.split("-")[0]) > int(
                        event.event_end_date.split("-")[0]):
                    raise Exception(
                        "Wrong event time - event starting date must be earlier than event ending date: "
                        "START:" + event.event_start_date +
                        " compare to END:" + event.event_end_date)
                if int(event.event_start_date.split("-")[1]) > int(
                        event.event_end_date.split("-")[1]):
                    raise Exception(
                        "Wrong event time - event starting date must be earlier than event ending date: "
                        "START:" + event.event_start_date +
                        " compare to END:" + event.event_end_date)
                events.append(event)
    readHour.close()
Beispiel #8
0
    def __init__(self,
                 tyres,
                 sensors=[],
                 cameras=[],
                 timeframe=0.1,
                 car_speed=50):
        logger.debug("Car4W.__init__()")

        self.action_id = 0

        self.t = None
        self.camera = None
        self.timeframe = timeframe
        self.car_speed = car_speed

        if len(tyres) != 4:
            raise EnvironmentError("Car4W required four tyres")

        self.state = 0
        self.frontRight = tyres[0][1]
        self.frontLeft = tyres[1][1]
        self.backRight = tyres[2][1]
        self.backLeft = tyres[3][1]

        self.stop()  # Stop the car, reset pins.

        self.collision = Collision(sensors)
        self.collision.start()

        logger.debug("Waiting to collision sensor to get ready")
        while not self.collision.ready:
            sleep(0.5)
        logger.info("Collision sensors are ready.")

        logger.debug("Waiting to camera to get ready")
        self.cameras = cameras
        for camera in self.cameras:
            camera[1].start()
        logger.debug("Camera start called")
        for camera in self.cameras:
            while not camera[1].more():
                sleep(0.5)
            logger.debug(camera[0] + " is ready.")
        logger.info("Cameras are ready.")
def read_source_file(file_name, hour_file_name):
    with open(file_name, 'r') as readCollision:  # r represent read model
        print("Start to read file: " + file_name +
              ". This may take a while...")
        file = csv.reader(readCollision)
        for row in file:
            if "COLLISION_ID" not in row[0]:
                collision = Collision()
                collision.collision_id = row[0]
                collision.location_id = row[1]
                collision.hour_id = row[2]
                collision.environment = row[3]
                collision.light = row[4]
                collision.surface_condition = row[5]
                collision.traffic_control = row[6]
                collision.traffic_control_condition = row[7]
                collision.collision_classification = row[8]
                collision.impace_type = row[9]
                collision.no_of_pedestrians = row[10]
                collisions.append(collision)
    readCollision.close()

    with open(hour_file_name, 'r') as readHour:  # r represent read model
        print("Start to read file: " + hour_file_name +
              ". This may take a while...")
        file = csv.reader(readHour)
        for row in file:
            if "HOUR_ID" not in row[0]:
                hour = Hour()
                hour.hour_id = row[0]
                hour.hour_start = row[1]
                hour.hour_end = row[2]
                hour.date = row[3]
                hour.day_of_week = row[4]
                hour.day = row[5]
                hour.month = row[6]
                hour.year = row[7]
                hour.weekend = row[8]
                hour.holiday = row[9]
                hour.holiday_name = row[10]
                hours.append(hour)
    readHour.close()
def read_source_file(file_name, locoation_file_name):
    with open(file_name, 'r') as readCollision:  # r represent read model
        print("Start to read file: " + file_name +
              ". This may take a while...")
        file = csv.reader(readCollision)
        for row in file:
            if "COLLISION_ID" not in row[0]:
                collision = Collision()
                collision.collision_id = row[0]
                collision.location_id = row[1]
                collision.hour_key = row[2]
                collision.environment = row[3]
                collision.light = row[4]
                collision.surface_condition = row[5]
                collision.traffic_control = row[6]
                collision.traffic_control_condition = row[7]
                collision.collision_classification = row[8]
                collision.impace_type = row[9]
                collision.no_of_pedestrians = row[10]
                collision.date = row[11]
                collisions.append(collision)
    readCollision.close()

    with open(locoation_file_name,
              'r') as readLocation:  # r represent read model
        print("Start to read file: " + locoation_file_name +
              ". This may take a while...")
        file = csv.reader(readLocation)
        for row in file:
            if "LOCATION_ID" not in row[0]:
                location = Location()
                location.location_id = row[0]
                location.street_name = row[1]
                location.intersection_one = row[2]
                location.intersection_two = row[3]
                location.longitude = row[4]
                location.latitude = row[5]
                location.neighborhood = row[6]
                location.closest_weather_station = row[7]
                locations.append(location)
    readLocation.close()
Beispiel #11
0
    def run(self):

        nrLevel = 0
        pygame.init()
        sound = pygame.mixer.Sound("music/BackGround.wav")
        soundLose = pygame.mixer.Sound("music/Lose.wav")
        soundWin = pygame.mixer.Sound("music/Win.wav")
        sound.play(1)
        screen = pygame.display.set_mode(Setting.resolution, pygame.FULLSCREEN)

        pygame.display.set_caption('Croko')
        clock = pygame.time.Clock()
        main_loop = True
        collision = Collision()
        player = Player("img/PlayerUP.png", 1)
        players = pygame.sprite.Group()
        players.add(player)

        level = LevelHandler()

        level.loadFile(Setting.LEVELS[nrLevel])
        level.gen()
        playerBullets = pygame.sprite.Group()
        enemyBullets = pygame.sprite.Group()
        enemy = TigerTank(Setting.EnemySpawn[0])
        enemy1 = GhostTank(Setting.EnemySpawn[1])
        enemy2 = Enemy(Setting.EnemySpawn[2])
        enemy3 = Enemy(Setting.EnemySpawn[3])
        enem = EnemyHandler(enemyBullets)
        enem.tanks.add(enemy)
        enem.tanks.add(enemy1)
        enem.tanks.add(enemy2)
        enem.tanks.add(enemy3)
        credit = Credits()
        self.blocks = pygame.sprite.Group()
        self.blocks.remove(self.blocks)
        self.blocks = level.map()

        while main_loop:

            pygame.mouse.set_visible(False)
            player.getBlocks(self.blocks)
            enem.getBlocks(self.blocks)
            enem.getEnemyTanks()
            if (enem.count <= 0):
                if nrLevel is not Setting.LAST_LEVEL:
                    nrLevel += 1
                    self.blocks.remove(self.blocks)
                    level.loadFile(Setting.LEVELS[nrLevel])
                    level.gen()
                    enem.reset()
                else:
                    sound.stop()
                    soundWin.play(1)
                    pygame.time.wait(4500)
                    credit.run()
                    main_loop = False
            if (player.live <= 0):
                sound.stop()
                soundLose.play(1)
                pygame.time.wait(4500)
                main_loop = False
            for block in self.blocks:
                if isinstance(block, EaglBlock):
                    if block.life <= 0:
                        sound.stop()
                        soundLose.play(1)
                        pygame.time.wait(4500)
                        main_loop = False
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    main_loop = False
                    sound.stop()
                else:
                    player.reaction(event, playerBullets)
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_ESCAPE:
                            main_loop = False
                            sound.stop()

            screen.fill(CZARNY)

            collision.playerCollisionWithEnemy(players, enem.tanks)
            collision.SelfbulletsCollisionWithEnemy(enem.tanks, enemyBullets)
            collision.bulletsCollisionWithPlayer(players, enemyBullets)
            collision.bulletCollisionWithBlocks(playerBullets, self.blocks)
            collision.bulletCollisionWithBlocks(enemyBullets, self.blocks)
            collision.bulletsCollisionWithBullets(enemyBullets, playerBullets)
            enem.bulletsCollisionWithSelf(playerBullets)
            players.draw(screen)
            players.update()
            playerBullets.update()
            playerBullets.draw(screen)
            enem.tanks.draw(screen)
            enem.shot()
            enem.tanks.update()

            enemyBullets.draw(screen)

            enemyBullets.update()
            self.blocks.draw(screen)

            pygame.display.flip()
            clock.tick(30)
Beispiel #12
0
def findCollision(dt, e1, e2):
    """Returns a bool indicating if the two entities collided and a collision class which records the two entities and the lambda at which they collide"""

    da_x = 0
    da_y = 0
    if hasattr(e1.state, "accelerationComponent"):
        da_x += e1.state.accelerationComponent.ax
        da_y += e1.state.accelerationComponent.ay
    if hasattr(e2.state, "accelerationComponent"):
        da_x -= e2.state.accelerationComponent.ax
        da_y -= e2.state.accelerationComponent.ay

    dv_x = 0
    dv_y = 0
    if hasattr(e1.state, "velocityComponent"):
        dv_x += e1.state.velocityComponent.vx
        dv_y += e1.state.velocityComponent.vy
    if hasattr(e2.state, "velocityComponent"):
        dv_x -= e2.state.velocityComponent.vx
        dv_y -= e2.state.velocityComponent.vy

    dx0_rl = (e1.state.geometryComponent.location[0] + e1.state.geometryComponent.width) - e2.state.geometryComponent.location[0]
    dx0_lr = e1.state.geometryComponent.location[0] - (e2.state.geometryComponent.location[0] + e2.state.geometryComponent.width)
    dy0_tb = e1.state.geometryComponent.location[1] - (e2.state.geometryComponent.location[1] + e2.state.geometryComponent.height)
    dy0_bt = (e1.state.geometryComponent.location[1] + e1.state.geometryComponent.height) - e2.state.geometryComponent.location[1]

    if da_x != 0:
        test, lx = __findLForAccel(dt, da_x, dv_x, dx0_lr, dx0_rl)
    elif dv_x != 0:
        test, lx = __findLForVel(dt, dv_x, dx0_lr, dx0_rl)
    else:
        test, lx = __findLForPos(dt, dx0_lr, dx0_rl)

    if test == False:
        return False, None

    if da_y != 0:
        test, ly = __findLForAccel(dt, da_y, dv_y, dy0_tb, dy0_bt)
    elif dv_y != 0:
        test, ly = __findLForVel(dt, dv_y, dy0_tb, dy0_bt)
    else:
        test, ly = __findLForPos(dt, dy0_tb, dy0_bt)

    if test == False:
        return False, None

    L = 10 # L > 1 impies no collision

    for l1 in lx:
        if l1[0] > 1 or l1[1]<0:
            continue
        for l2 in ly:
            if l2[0] > 1 or l2[1]<0:
                continue
            if l1[0] <= l2[0] <= l1[1]:
                L = min(L, l2[0])
                axis = "y"
            if l2[0] <= l1[0] <= l2[1]:
                L = min(L, l1[0])
                axis = "x"

    if L < 0 or L > 1:
        return False, None
    else:
        print "collision found!!!"
        return True, Collision(e1, e2, L, axis)
Beispiel #13
0
    def tick(self, player, camera):
        speed = 2
        jump_speed = 45
        self.tickTimer += 1

        if self.tickTimer % 3 == 0:
            player.dv.add(self.accelerationDownwards.add(Vector(0, 1)))
            player.dv.y = 15 if player.dv.y > 10 else player.dv.y

        if self.tickTimer % 3 == 0:
            if player.pos.y + (player.w / 2) * 2 < camera.map_dimensions.y - (
                    camera.map_dimensions.y - camera.span[1]):
                player.dv.add(self.accelerationDownwards.add(Vector(0, 1)))
                player.dv.y = 15 if player.dv.y > 10 else player.dv.y
            elif player.pos.y + (player.w / 2) < camera.map_dimensions.y:
                camera.dv.add(self.accelerationDownwards.add(Vector(0, 1)))
                player.dv.add(self.accelerationDownwards.add(Vector(0, 1)))
                player.dv.y = 15 if player.dv.y > 10 else player.dv.y
                camera.dv.y = 15 if player.dv.y > 10 else player.dv.y
            else:
                # If the player has fallen off the map:
                player.revive(camera)

        interaction = Collision(player)
        interaction.update()
        if interaction.inCollisionDown:
            self.down = False
            player.dv.y = 0

        if self.left and player.pos.x - (player.w / 2) > camera.furthest + (
                player.w / 2) + 20:
            player.set_state(player.RUNNING)
            player.direction = player.LEFT
            player.dv.add(Vector(-speed, 0))
            camera.dv.add(Vector(-speed, 0))
            if camera.pos.x <= camera.furthest:
                camera.dv.x = 0
                camera.pos.x = camera.furthest
        elif self.left:
            self.accelerationDownwards = Vector(0, 0.5)
            player.dv.x = 0
            player.pos.x = camera.furthest + (player.w / 2) + 20
            camera.dv.x = 0
            camera.pos.x = camera.furthest

        if self.right and player.pos.x + (
                player.w / 2) < camera.furthest + camera.span[0]:
            player.set_state(player.RUNNING)
            player.direction = player.RIGHT
            if player.pos.x < camera.furthest + camera.span[0] / 2:
                player.dv.add(Vector(speed, 0))
            else:
                player.dv.add(Vector(speed, 0))
                camera.dv.add(Vector(speed, 0))
            if camera.pos.x >= camera.map_dimensions.x - camera.span[0] - (
                    Unit.UNIT * 2):
                camera.dv.x = 0
                camera.pos.x = camera.map_dimensions.x - camera.span[0] - (
                    Unit.UNIT * 2)
        elif self.right and camera.map_dimensions.x - 20:
            self.accelerationDownwards = Vector(0, 0.5)
            player.dv.x = 0
            player.pos.x = (
                (camera.furthest + camera.span[0]) - player.w / 2) - 20
            camera.dv.add(Vector(speed, 0))
        elif self.right:
            self.accelerationDownwards = Vector(0, 0.5)
            player.dv.x = 0
            player.pos.x = camera.dimensions.x - 20
            camera.pos.x = camera.dimensions.x - camera.span[0]

        if self.up and player.pos.y - (player.w / 2) > 1 and player.grounded:
            player.set_state(player.JUMPING)
            player.grounded = False
            self.up = False
            self.accelerationDownwards = Vector(0, 0.5)
            player.dv.add(Vector(0, -jump_speed))
            camera.dv.add(Vector(0, -jump_speed))
            if camera.pos.y <= 0:
                camera.dv.y = 0
                camera.pos.y = 0
        elif not (player.pos.y - (player.w / 2) > 1):
            self.accelerationDownwards = Vector(0, 0.5)
            player.dv.y = 0
            player.pos.y = 1 + (player.w / 2)
            camera.dv.y = 0
        if not (self.right or self.up or self.left) and player.grounded:
            player.set_state(player.IDLE)
            player.sprite_index = player.IDLE_START
        if not player.grounded and player.state != player.JUMPING:
            player.set_state(player.JUMPING)
        player.dv *= 0.8
        camera.dv *= 0.8
def collision_processor(file_name):
    """
    Retrieve data about the time, in hour, of the ottawa's collision record from a csv file.
    :param file_name: the file to retrieve data
    """
    global total_record
    global total_valid_record
    collisions = []
    key_ctr = 0
    with open(file_name, 'r') as readData:  # r represent read model
        print("Start to read file: " + file_name +
              ". This may take a while...")
        file = csv.reader(readData)
        canada_holiday = holidays.CA()
        for row in file:
            if "COLLISION_ID" not in row[0]:
                collision = Collision()
                collision.collision_id = key_ctr
                key_ctr = key_ctr + 1
                collision.location = row[1]
                collision.longtitude = row[4]
                collision.latitude = row[5]
                collision.date = row[6]
                collision.time = row[7]
                environment = row[8]
                if row[8] == "":
                    environment = "Unknown"
                collision.environment = remove_prefix(environment, "Unknown")
                light = row[9]
                if row[9] == "":
                    light = "Unknown"
                collision.light = remove_prefix(light, "Unknown")
                surface_condition = row[10]
                if row[10] == "":
                    surface_condition = "Unknown"
                collision.surface_condition = remove_prefix(
                    surface_condition, "Unknown")
                traffic_control = row[11]
                if row[11] == "":
                    traffic_control = "Unknown"
                collision.traffic_control = remove_prefix(
                    traffic_control, "Unknown")
                traffic_control_condition = row[12]
                if row[12] == "":
                    if collision.traffic_control == "No control":
                        traffic_control_condition = "N/A"
                        collision.traffic_control_condition = traffic_control_condition
                    else:
                        traffic_control_condition = "Unknown"
                        collision.traffic_control_condition = traffic_control_condition
                else:
                    collision.traffic_control_condition = remove_prefix(
                        traffic_control_condition, "Unknown")
                collision_classification = row[13]
                if row[13] == "":
                    collision_classification = "Unknown"
                collision.collision_classification = remove_prefix(
                    collision_classification, "Unknown")
                impact_type = row[14]
                if row[14] == "":
                    impact_type = "Unknown"
                collision.impace_type = remove_prefix(impact_type, "Unknown")
                no_of_pedestrians = row[15]
                if row[14] == "":
                    no_of_pedestrians = -1
                collision.no_of_pedestrians = no_of_pedestrians
                collisions.append(collision)
    return collisions
Beispiel #15
0
test2.add_component("physics", (20, 0, 0.005, True, False))
test3.add_component("image_renderer", "assets/block.png")
test3.add_component("collider",
                    (test3.transform.position.x -
                     test3.renderer.to_render.surface.get_width() / 2,
                     test3.transform.position.y +
                     test3.renderer.to_render.surface.get_height() / 2,
                     test3.renderer.to_render.surface.get_width(),
                     test3.renderer.to_render.surface.get_height()))
test3.add_component("physics", (20, 0, 0.005, True, False))
test.add_component("physics", (20, 0, 0.005, False, True))

polygon = Collision(
    [
        (-16, 16),
        # (16, 16),
        (16, -16),
        (-16, -16)
    ],
    pygame)
nope = Collision(
    [
        # (-16, 16),
        (16, 16),
        (16, -16),
        (-16, -16)
    ],
    pygame)
print(polygon.origin)
camera.target = test2
running = True
    def findCollisions(self, entityIDs):
        """Returns a bool indicating if the two entities collided and a collision class which records the two entities and the lambda at which they collide"""
        collisions = []
        for e1id, e2id in combinations(entityIDs, 2):
            if ((self.collsionComponents[e1id].category,
                 self.collsionComponents[e2id].category)
                    in self.interestingCollisions
                    or (self.collsionComponents[e2id].category,
                        self.collsionComponents[e1id].category)
                    in self.interestingCollisions):
                continue

            da_x = 0
            da_y = 0
            dv_x = 0
            dv_y = 0
            if e1id in self.accelerationComponents.keys():
                da_x += self.accelerationComponents[e1id].ax
                da_y += self.accelerationComponents[e1id].ay
                dv_x += self.velocityComponents[e1id].vx
                dv_y += self.velocityComponents[e1id].vy
            elif e1id in self.velocityComponents.keys():
                dv_x += self.velocityComponents[e1id].vx
                dv_y += self.velocityComponents[e1id].vy

            if e2id in self.accelerationComponents.keys():
                da_x -= self.accelerationComponents[e2id].ax
                da_y -= self.accelerationComponents[e2id].ay
                dv_x -= self.velocityComponents[e2id].vx
                dv_y -= self.velocityComponents[e2id].vy
            elif eid in self.velocityComponents.keys():
                dv_x -= self.velocityComponents[e2id].vx
                dv_y -= self.velocityComponents[e2id].vy

            loc1 = self.positionComponents[e1id]
            loc2 = self.positionComponents[e2id]
            geom1 = self.geometryComponents[e1id]
            geom2 = self.geometryComponents[e2id]

            dx0_rl = (loc1.x + geom1.width) - loc2.x
            dx0_lr = loc1.x - (loc2.x + geom2.width)
            dy0_tb = loc1.y - (loc2.y + geom1.height)
            dy0_bt = (loc1.y + geom1.height) - loc2.y

            if da_x != 0:
                test, lx = self.__findLForAccel(da_x, dv_x, dx0_lr, dx0_rl)
            elif dv_x != 0:
                test, lx = self.__findLForVel(dv_x, dx0_lr, dx0_rl)
            else:
                test, lx = self.__findLForPos(dx0_lr, dx0_rl)

            if test == False:
                continue

            if da_y != 0:
                test, ly = self.__findLForAccel(da_y, dv_y, dy0_tb, dy0_bt)
            elif dv_y != 0:
                test, ly = self.__findLForVel(dv_y, dy0_tb, dy0_bt)
            else:
                test, ly = self.__findLForPos(dy0_tb, dy0_bt)

            if test == False:
                continue

            L = 10  # L > 1 impies no collision

            for l1 in lx:
                if l1[0] > 1 or l1[1] < 0:
                    continue
                for l2 in ly:
                    if l2[0] > 1 or l2[1] < 0:
                        continue
                    if l1[0] <= l2[0] <= l1[1]:
                        L = min(L, l2[0])
                        axis = "y"
                    if l2[0] <= l1[0] <= l2[1]:
                        L = min(L, l1[0])
                        axis = "x"

            if L < 0 or L > 1:
                continue
            else:
                print "collision found!!!"
                collisions.append(Collision(e1id, e2id, L, axis))
        return collisions
Beispiel #17
0
    map.draw(score_activate=(car.last_score + 1) % 8)
    car.draw()
    label.text = str(car.score)
    label.draw()
    global glob_frame
    glob_frame += 1
    label2.text = str(glob_frame)
    label2.draw()
    if not car.player_play:
        f = car.rays(ai, net, map.in_map, map.out_map, True)
        keys.ai_keys(f)
    # print f
    fps_display.draw()


if __name__ == "__main__":
    fps_display = FPSDisplay(window)

    map = CarMap()
    ai = Ai()
    net = Net()
    device = torch.device('cpu')
    net.load_state_dict(
        torch.load('models/' + car_model + '.txt', map_location=device))
    net.double()
    car = Car()
    keys = Keyboard_helper()
    collision = Collision()
    pyglet.clock.schedule_interval(update_frames, 1 / 24.0)
    pyglet.app.run()
Beispiel #18
0
def process_collision_table():
    list = collision_processor("2014collisionsfinal.xls.csv")
    list1 = collision_processor("2016collisionsfinal.xls.csv")
    list2 = collision_processor("2015collisionsfinal.xls.csv")

    collisions = []

    with open("h2017collisionsfinal.csv",
              'r') as readData:  # r represent read model
        print(
            "Start to read file: h2017collisionsfinal.csv. This may take a while..."
        )
        file = csv.reader(readData)
        key_ctr = 0
        for row in file:
            if "Record" not in row[0]:
                collision = Collision()
                collision.collision_id = key_ctr
                key_ctr = key_ctr + 1
                collision.location = row[1]
                collision.longtitude = row[4]
                collision.latitude = row[5]
                collision.date = row[7]
                collision.time = row[8]
                environment = row[9]
                if row[9] == "":
                    environment = "Unknown"
                collision.environment = remove_prefix(environment, "Unknown")
                light = row[13]
                if row[13] == "":
                    light = "Unknown"
                collision.light = remove_prefix(light, "Unknown")
                surface_condition = row[10]
                if row[10] == "":
                    surface_condition = "Unknown"
                collision.surface_condition = remove_prefix(
                    surface_condition, "Unknown")
                traffic_control = row[11]
                if row[11] == "":
                    traffic_control = "Unknown"
                collision.traffic_control = remove_prefix(
                    traffic_control, "Unknown")
                collision.traffic_control_condition = "N/A"
                collision_classification = row[14]
                if row[14] == "":
                    collision_classification = "Unknown"
                collision.collision_classification = remove_prefix(
                    collision_classification, "Unknown")
                impact_type = row[15]
                if row[15] == "":
                    impact_type = "Unknown"
                collision.impace_type = remove_prefix(impact_type, "Unknown")
                collision.no_of_pedestrians = "N/A"
                collisions.append(collision)
    readData.close()

    # with open("2017collisionsfinal.xls.csv", 'w', newline='') as csvFile:
    #     print("Prepare to write the data into the file: h2017collisionsfinal.csv. It might take a while...")
    #     writer = csv.writer(csvFile)
    #     writer.writerow(["COLLISION_ID", "LOCATION", "LONGITUDE", "LATITUDE", "DATE", "TIME", "ENVIRONMENT",
    #                      "LIGHT", "SURFACE_CONDITION", "TRAFFIC_CONTROL", "TRAFFIC_CONTROL_CONDITION",
    #                      "COLLISION_CLASSIFICATION", "IMPACT_TYPE", "NO_OF_PEDESTRIANS"])
    #     for collision in collisions:
    #         writer.writerow([collision.collision_id, collision.location, collision.longtitude, collision.latitude,
    #                          collision.date, collision.time, collision.environment, collision.light,
    #                          collision.surface_condition, collision.traffic_control,
    #                          collision.traffic_control_condition, collision.collision_classification,
    #                          collision.impace_type, collision.no_of_pedestrians])
    # csvFile.close()

    list.extend(list1)
    list.extend(list2)
    list.extend(collisions)
    output_collision_data_from_list_to_new_csv("Collision_Table", list)