Exemplo n.º 1
0
def agent_update():

    temp_agent_array = []

    for i in range(len(shared.agent_array)):
        agent = shared.agent_array[i]
        temp_vel = (0, 0)
        cohesion_v = compute_cohesion(agent, i % 2)
        alignment_v = compute_alignment(agent, i % 2)
        seperation_v = compute_seperation(agent, i % 2)
        obstacle_dodge_v = compute_obstacle_dodge(agent)

        v_array = [
            agent.vel,
            v_mul(cohesion_v, COHESION_WEIGHT[i % 2]),
            v_mul(alignment_v, ALIGNMENT_WEIGHT[i % 2]),
            v_mul(seperation_v, SEPERATION_WEIGHT[i % 2]),
            v_mul(obstacle_dodge_v, OBSTACLE_DOGDGE_WEIGHT)
        ]

        temp_vel = v_array_sum(v_array)
        temp_vel = v_mul(temp_vel, shared.FPS)

        a = Agent(agent.pos, temp_vel)
        if i % 2:
            a.vel = limit(temp_vel,
                          DEFAULT_SPEED + 6 + shared.speed_adjustment)
        else:
            a.vel = limit(temp_vel, DEFAULT_SPEED + shared.speed_adjustment)
        # change_vel_if_zero(a)
        a.update_pos()
        temp_agent_array.append(a)

    shared.agent_array = temp_agent_array
Exemplo n.º 2
0
def agent_update():
    global agent_array
    temp_agent_array = []

    if freeze:
        return

    for i in xrange(0, len(agent_array)):
        agent = agent_array[i]
        temp_vel = (0, 0)
        cohesion_v = computeCohesion(agent, i % 2)
        alignment_v = computeAlignment(agent, i % 2)
        seperation_v = computeSeperation(agent, i % 2)
        obstacle_dodge_v = computeObscatleDodge(agent)

        v_array = [
            agent.vel,
            utils.v_mul(cohesion_v, COHESION_WEIGHT[i % 2]),
            utils.v_mul(alignment_v, ALIGNMENT_WEIGHT[i % 2]),
            utils.v_mul(seperation_v, SEPERATION_WEIGHT[i % 2]),
            utils.v_mul(obstacle_dodge_v, OBSTACLE_DOGDGE_WEIGHT)
        ]

        temp_vel = utils.v_array_sum(v_array)
        a = Agent(agent.pos, temp_vel)
        if i % 2:
            a.vel = utils.limit(temp_vel, DEFAULT_SPEED + 6 + speed_adjustment)
        else:
            a.vel = utils.limit(temp_vel, DEFAULT_SPEED + speed_adjustment)
        # utils.change_vel_if_zero(a)
        a.updatePos()
        temp_agent_array.append(a)

    agent_array = temp_agent_array
Exemplo n.º 3
0
async def run_spaceship(
        canvas, start_row, start_column, gun_activation_year=2020):
    row, column = start_row, start_column

    row_speed = column_speed = 0

    canvas_height, canvas_width = canvas.getmaxyx()

    while True:
        current_frame = spaceship_frame

        rows_direction, columns_direction, space_pressed = read_controls(
            canvas=canvas,
        )
        row_speed, column_speed = update_speed(
            row_speed=row_speed,
            column_speed=column_speed,
            rows_direction=rows_direction,
            columns_direction=columns_direction,
        )
        row += row_speed
        column += column_speed

        frame_height, frame_width = get_frame_size(current_frame)

        row = limit(
            value=row,
            min_value=1,
            max_value=canvas_height - frame_height - 1,
        )
        column = limit(
            value=column,
            min_value=1,
            max_value=canvas_width - frame_width - 1,
        )

        draw_frame(canvas, row, column, current_frame)

        if space_pressed and row > 1 and year >= gun_activation_year:
            coroutines.append(
                animate_gun_shot(
                    canvas=canvas,
                    start_row=row - 1,
                    start_column=column + 2,
                )
            )

        await sleep()
        draw_frame(canvas, row, column, current_frame, negative=True)

        for obstacle in obstacles:
            if obstacle.has_collision(
                    obj_corner_row=row, obj_corner_column=column):
                coroutines.append(
                    show_gameover(canvas=canvas),
                )
                return
Exemplo n.º 4
0
    def arrive(self, target):
        """
            Arrive Steering Behavior
        """
        # Calculates vector desired
        self.desired = (target - self.location)
        # get the distance to the target
        d = self.desired.magnitude()

        try:
            dist = copy.deepcopy(self.desired.normalize())  # obtem direção
        except:  # If the magnitude of desired is zero it cant be normalized
            dist = copy.deepcopy(self.desired)

        r = RADIUS_TARGET
        # Modulates the force
        if d < r:  # close to target it will reduce velocty till stops
            # interpolation
            dist *= self.max_speed * (1 + 1 / r * (d - r))
        else:
            dist *= self.max_speed

        # Steering force
        steer = dist - self.velocity
        #Limit the magnitude of the steering force.
        steer = limit(steer, self.max_force)
        # apply force to the vehicle
        self.applyForce(steer)
        # Simulates Wind - random Noise
        wind = vec2(random.uniform(-0.15, 0.15), random.uniform(-0.15, 0.15))
        self.applyForce(wind)
        # Draws current target as a point
        pg.draw.circle(self.window, self.color_target, target, 5, 0)
Exemplo n.º 5
0
    def col_bullet_walls(self, bullet):
        # Set of tiles that are passable by bullets.
        # TODO: If you want your Hazard to leave Bullets through
        #       insert Hazard.YourNewHazard
        can_pass = {Hazard.Empty}

        position = bullet.position

        tile_x = int(position[0] / TILE_SIZE)
        tile_x = utils.limit(tile_x, 0, Board.TILE_COUNT - 1)

        tile_y = int(position[1] / TILE_SIZE)
        tile_y = utils.limit(tile_y, 0, Board.TILE_COUNT - 1)

        if self.obstacleArray[tile_x][tile_y] not in can_pass:
            self.bullets.remove(bullet)
            return True

        return False
Exemplo n.º 6
0
def generate_rss():
    html_file = os.path.join(defs.STATIC_HTML_DIR, 'special', 'rss.xml')
    articles = utils.limit(fetch_articles_sorted(), defs.MAX_ARTICLES_RSS)
    last_updated = articles[0].published_date
    template_variables = {
        'articles': articles,
        'defs': defs,
        'last_updated': last_updated,
    }
    html = render_template('rss-articles.xml', template_variables)
    utils.write_file(html_file, html)
    return html_file
Exemplo n.º 7
0
    def calculate_robot(self, poll, robot):
        """Uses current position data of robot robot and acceleration values
        polled from the robot to calculate new position values.
        """

        # robot won't move while dead
        if robot.dead:
            return

        # unpack robot output
        a, a_alpha = poll

        # checks if acceleration is valid
        a = utils.limit(a, -robot.a_max, robot.a_max)

        # checks if angle acceleration is valid
        a_alpha = utils.limit(a_alpha, -robot.a_alpha_max, robot.a_alpha_max)

        # calculates velocities
        new_v = utils.limit(robot.v + a, -1 * robot.v_max, robot.v_max)
        new_v_alpha = utils.limit(robot.v_alpha + a_alpha,
                                  -1 * robot.v_alpha_max, robot.v_alpha_max)

        # calculate alpha and x and y component of v
        alpha = robot.alpha + new_v_alpha
        alpha = alpha % 360
        radian = ((alpha - 90) / 180 * math.pi)

        dx = new_v * math.cos(radian)
        dy = new_v * math.sin(radian)

        # calculates the new position - factors in collisions
        col_data = self.col_robots_walls(robot, dx, dy, new_v, new_v_alpha)
        dx_col, dy_col, v_col, v_alpha_col = col_data
        new_position_col = (robot.x + dx_col, robot.y + dy_col,
                            alpha, v_col, new_v_alpha)

        # finally, re-place the robot on the board
        Board.place_robot(robot, *new_position_col)
Exemplo n.º 8
0
 def collision_avoidance(self, all_positions, index):
     """
         Not working yet
     """
     aux = 0
     for p in all_positions:
         if ((self.location - p.location).length() <
                 AVOID_DISTANCE) and (aux != index):
             desired = vec2(self.max_speed, self.velocity.y)
             steer = desired - self.velocity
             steer = limit(steer, self.max_force)
             self.applyForce(steer)
             print(f'Alerta de colisão drone {index} com drone {aux}')
             break
         aux += 1
Exemplo n.º 9
0
def compute_cohesion(myAgent, t):
    compute_vel = (0, 0)
    neighbors_cnt = 0

    for i in range(len(shared.agent_array)):
        agent = shared.agent_array[i]
        if agent != myAgent and myAgent.distance_from(
                agent) < COHESION_RADIUS and t == i % 2:
            compute_vel = v_sub(agent.pos, myAgent.pos)
            neighbors_cnt += 1

    if neighbors_cnt == 0:
        return compute_vel

    compute_vel = v_div(compute_vel, neighbors_cnt)

    return limit(compute_vel, 0.05)
Exemplo n.º 10
0
def computeAlignment(myAgent, t):
    compute_vel = (0, 0)
    neighbors_cnt = 0

    for i in xrange(0, len(agent_array)):
        agent = agent_array[i]
        if agent != myAgent and myAgent.distanceFrom(
                agent) < ALIGNMENT_RADIUS and t == i % 2:
            compute_vel = v_add(compute_vel, agent.vel)
            neighbors_cnt += 1

    if neighbors_cnt == 0:
        return compute_vel

    compute_vel = v_div(compute_vel, neighbors_cnt)

    return utils.limit(compute_vel, 0.05)
Exemplo n.º 11
0
def computeCohesion(myAgent, t):
    compute_vel = (0, 0)
    neighbors_cnt = 0

    for i in xrange(0, len(agent_array)):
        agent = agent_array[i]
        if agent != myAgent and myAgent.distanceFrom(
                agent) < COHESION_RADIUS and t == i % 2:
            compute_vel = v_sub(agent.pos, myAgent.pos)
            neighbors_cnt += 1

    if neighbors_cnt == 0:
        return compute_vel

    compute_vel = v_div(compute_vel, neighbors_cnt)

    return utils.limit(compute_vel, 0.05)
Exemplo n.º 12
0
def compute_alignment(myAgent, t):
    compute_vel = (0, 0)
    neighbors_cnt = 0

    for i in range(len(shared.agent_array)):
        agent = shared.agent_array[i]
        if agent != myAgent and myAgent.distance_from(
                agent) < ALIGNMENT_RADIUS and t == i % 2:
            compute_vel = v_add(compute_vel, agent.vel)
            neighbors_cnt += 1

    if neighbors_cnt == 0:
        return compute_vel

    compute_vel = v_div(compute_vel, neighbors_cnt)

    return limit(compute_vel, 0.05)
Exemplo n.º 13
0
    def seek(self, target):
        """
            Seek Steering force Algorithm
        """
        try:
            self.desired = (target -
                            self.location).normalize() * self.max_speed
        except:  # if you try to normalize a null vector it will catch
            self.desired = (target - self.location) * self.max_speed

        # Calculates steering force
        steer = self.desired - self.velocity
        # Limit the magnitude of the steering force.
        steer = limit(steer, self.max_force)
        # Applies steering force to drone
        self.applyForce(steer)
        # Draws current target being seeked
        pg.draw.circle(self.window, self.color_target, target, 5, 0)
Exemplo n.º 14
0
async def animate_flying_garbage(canvas, column, garbage_frame, speed=0.5):
    """Animate garbage, flying from top to bottom.
    Сolumn position will stay same, as specified on start.
    """
    canvas_height, canvas_width = canvas.getmaxyx()

    frame_height, frame_width = get_frame_size(garbage_frame)

    column = limit(
        value=column,
        min_value=1,
        max_value=canvas_width - frame_width - 1,
    )
    row = 1

    while row < canvas_height - frame_height - 1:
        obstacle = Obstacle(
            row=row,
            column=column,
            rows_size=frame_height,
            columns_size=frame_width,
        )
        obstacles.append(obstacle)

        draw_frame(canvas, row, column, garbage_frame)
        await sleep()
        draw_frame(canvas, row, column, garbage_frame, negative=True)

        obstacles.remove(obstacle)

        if obstacle in obstacles_in_last_collisions:
            obstacles_in_last_collisions.remove(obstacle)

            await animate_explosion(
                canvas=canvas,
                center_row=row + 2 + frame_height // 2,
                center_column=column + frame_width // 2,
            )
            return

        row += speed
Exemplo n.º 15
0
    def update(self):
        """
            Standart Euler integration
            Updates bahavior tree
        """
        # updates behavior in machine state
        self.behavior.update(self)
        # Updates velocity at every step and limits it to max_speed
        self.velocity += self.acceleration * 1
        self.velocity = limit(self.velocity, self.max_speed)
        # updates position
        self.location += self.velocity
        # Prevents it from crazy spinning due to very low noise speeds
        if self.velocity.length() > 0.5:
            self.rotation = atan2(self.velocity.y, self.velocity.x)
        # Constrains position to limits of screen
        self.location = constrain(self.location, SCREEN_WIDTH, SCREEN_HEIGHT)
        self.acceleration *= 0

        # Memory of positions to draw Track
        self.memory_location.append((self.location.x, self.location.y))
        # size of track
        if len(self.memory_location) > SIZE_TRACK:
            self.memory_location.pop(0)
Exemplo n.º 16
0
def _apply_acceleration(speed, speed_limit, forward=True):
    """Change speed — accelerate or brake — according to force direction."""

    speed_limit = abs(speed_limit)

    speed_fraction = speed / speed_limit

    # if the spaceship is standing still, then we accelerate quickly
    # if the spaceship is already flying fast, then we accelerate slowly
    delta = math.cos(speed_fraction) * 0.75

    result_speed = speed + delta if forward else speed - delta

    result_speed = limit(
        value=result_speed,
        min_value=-speed_limit,
        max_value=speed_limit,
    )

    # if the speed of the spaceship is close to zero, then we stop it
    if abs(result_speed) < 0.1:
        result_speed = 0

    return result_speed
Exemplo n.º 17
0
 def move(self, di, dj):
     i, j = self.position
     i = limit(i + di, 0, self._table.height - 1)
     j = limit(j + dj, 0, len(self._table.table[i]) - 1)
     self.position = (i, j)
Exemplo n.º 18
0
def true_score(score):
	return utils.limit(score,OUTPUT_FACTOR)/OUTPUT_FACTOR*REDUCE_ONE
Exemplo n.º 19
0
import utils


def fibo(n):
    if n < 2:
        return n
    else:
        return fibo(n - 1) + fibo(n - 2)


@utils.bench
def run(n):
    return fibo(n)


n = 37
s = utils.limit("{}".format(run(n)), 10)
print('n={} fib={}'.format(n, s))