Esempio n. 1
0
    def update(self, dt, global_velocity=(0, 0)):
        velocity = vector.add(global_velocity, vector.multiply(self.force, dt))
        self.force = vector.multiply(self.force, FORCE_DRAG)
        self.position = vector.add(self.position,
                                   vector.multiply(velocity, dt * self.speed))

        self.bounce_from_boundaries()
Esempio n. 2
0
def update_order(Vx,Vy,dt):
    global t, v_init, has_scored, colli_point, START_POS, has_colli, score_point
    if v_init[1] > 0:
        if t > v_init[1]/abs(G): # is falling
            ball.group = mid     # change gourp
            basket[1].group = front
            #if check_collision() != None:   # if collide
                #reset_time()
                #reset_ball()
                #time.sleep(0.2)
            if check_collision() == colli_point[0]:
                has_colli = True
                reset_time()
                vec1 = vector.sub([ball.x, ball.y],colli_point[0])
                vec1 = vector.vec_x_float(vec1,2)
                v_init = vector.add(vec1,[Vx,Vy])
                v_init = vector.vec_x_float(v_init,5)
                START_POS[0] = ball.x
                START_POS[1] = ball.y
            elif check_collision() == colli_point[1]:
                has_colli = True
                reset_time()
                vec1 = vector.sub([ball.x, ball.y],colli_point[1])
                vec1 = vector.vec_x_float(vec1,2)
                v_init = vector.add(vec1,[Vx,Vy])
                v_init = vector.vec_x_float(v_init,5)
                START_POS[0] = ball.x
                START_POS[1] = ball.y
            if vector.distance([ball.x,ball.y],score_point) <= 50:
                has_scored = True
        else:
            ball.group = front
            basket[1].group = mid
Esempio n. 3
0
def display_grid(img, squares, cam_rot, base_object_points):
    """
    Display the output of find_grid in a pretty way.
    :param img: the image in which the grid was found
    :param squares: the squares in the image
    :param cam_rot: the deduced camera orientation
    :param base_object_points: ??
    :return: nothing
    """
    
    birds_view = np.zeros([1000, 1000, 3], dtype=np.uint8)
    cv2.circle(birds_view,
               (int(birds_view.shape[0] / 2), int(birds_view.shape[1] / 2)), 5,
               (255, 255, 0), -1)

    if cam_rot != 0:
        cam_line = vec.add(vec.scalar_mult(cam_rot, 50),
                                [birds_view.shape[0] / 2,
                                 birds_view.shape[0] / 2, 0])

        cv2.line(birds_view, (int(cam_line[0]), int(cam_line[1])),
                 (int(birds_view.shape[0] / 2), int(birds_view.shape[1] / 2)),
                 (0, 0, 255), 1, cv2.LINE_AA)

    for square in squares:
        for edge_index in range(4):
            temp_draw_vec = vec.add(square.location,
                                         base_object_points[edge_index])
            temp_draw_vec2 = vec.add(square.location,
                                          base_object_points[edge_index - 1])

            cv2.line(birds_view, (int(temp_draw_vec[0] + birds_view.shape[0] / 2),
                                  int(temp_draw_vec[1] + birds_view.shape[1] / 2)),
                     (int(temp_draw_vec2[0] + birds_view.shape[0] / 2),
                      int(temp_draw_vec2[1] + birds_view.shape[1] / 2)),
                     (255, 255, 255), 3, cv2.LINE_AA)

        x = sum(point[0][0] for point in square.corners) // 4
        y = sum(point[0][1] for point in square.corners) // 4

        cv2.putText(img, '{} {}'.format(int(abs(square.location[2])),
                                        int(square.score * 100)), (x, y), FONT,
                    1, (255, 255, 255), 1, cv2.LINE_AA)

        cv2.polylines(img, [square.corners], True, (255, 0, 0))
        cv2.drawContours(img, square.contour, True, (0, 255, 0))

    if len(squares) > 0:
        cam_line2 = vec.add(vec.scalar_mult(cam_rot, 50),
                            [birds_view.shape[0] / 2,
                             birds_view.shape[0] / 2, 0])

        cv2.line(birds_view, (int(cam_line2[0]), int(cam_line2[1])),
                 (int(birds_view.shape[0] / 2), int(birds_view.shape[1] / 2)),
                 (255, 0, 255), 1, cv2.LINE_AA)

    cv2.imshow("Squares", img)
    cv2.imshow("Birds eye view", birds_view)
Esempio n. 4
0
def display_grid(img, squares, cam_rot, base_object_points):
    """
    Display the output of find_grid in a pretty way.
    :param img: the image in which the grid was found
    :param squares: the squares in the image
    :param cam_rot: the deduced camera orientation
    :param base_object_points: ??
    :return: nothing
    """
    birds_view = np.zeros([1000, 1000, 3], dtype=np.uint8)
    cv2.circle(birds_view,
               (int(birds_view.shape[0] / 2), int(birds_view.shape[1] / 2)), 5,
               (255, 255, 0), -1)

    if cam_rot != 0:
        cam_line = vec.add(vec.scalar_mult(cam_rot, 50),
                                [birds_view.shape[0] / 2,
                                 birds_view.shape[0] / 2, 0])

        cv2.line(birds_view, (int(cam_line[0]), int(cam_line[1])),
                 (int(birds_view.shape[0] / 2), int(birds_view.shape[1] / 2)),
                 (0, 0, 255), 1, cv2.LINE_AA)

    for square in squares:
        for edge_index in range(4):
            temp_draw_vec = vec.add(square.location,
                                         base_object_points[edge_index])
            temp_draw_vec2 = vec.add(square.location,
                                          base_object_points[edge_index - 1])

            cv2.line(birds_view, (int(temp_draw_vec[0] + birds_view.shape[0] / 2),
                                  int(temp_draw_vec[1] + birds_view.shape[1] / 2)),
                     (int(temp_draw_vec2[0] + birds_view.shape[0] / 2),
                      int(temp_draw_vec2[1] + birds_view.shape[1] / 2)),
                     (255, 255, 255), 3, cv2.LINE_AA)

        x = sum(point[0][0] for point in square.corners) // 4
        y = sum(point[0][1] for point in square.corners) // 4

        cv2.putText(img, '{} {}'.format(int(abs(square.location[2])),
                                        int(square.score * 100)), (x, y), FONT,
                    1, (255, 255, 255), 1, cv2.LINE_AA)

        cv2.polylines(img, [square.corners], True, (255, 0, 0))
        cv2.drawContours(img, square.contour, True, (0, 255, 0))

    if len(squares) > 0:
        cam_line2 = vec.add(vec.scalar_mult(cam_rot, 50),
                            [birds_view.shape[0] / 2,
                             birds_view.shape[0] / 2, 0])

        cv2.line(birds_view, (int(cam_line2[0]), int(cam_line2[1])),
                 (int(birds_view.shape[0] / 2), int(birds_view.shape[1] / 2)),
                 (255, 0, 255), 1, cv2.LINE_AA)

    cv2.imshow("Squares", img)
    cv2.imshow("Birds eye view", birds_view)
Esempio n. 5
0
 def get_bbox(self):
     start = vector.add(self.pos, vector.multiply(self.size, -0.5))
     end = vector.add(self.pos, vector.multiply(self.size, 0.5))
     return (
         self.pos[0] - self.size[0] / 2,
         self.pos[1] - self.size[1] / 2,
         self.pos[0] + self.size[0] / 2,
         self.pos[1] + self.size[1] / 2
         )
Esempio n. 6
0
def update_enemy(position, malo_pos, delta_time, camera):
    '''
    Actualiza el estado de la calabaza
    '''
    vertex = [0, 0]
    malo_velocity = mult(normalizar(sub(position, malo_pos)),
                         SPEED * 0.25 * delta_time)
    orientacion = rotar.rot(camera, math.pi / 2)
    malo_pos = add(malo_pos, malo_velocity)
    vertex[0] = add(malo_pos, mult(orientacion, 12.5))
    vertex[1] = add(malo_pos, mult(orientacion, -12.5))
    return (vertex, malo_pos)
Esempio n. 7
0
    def flock(self, l, delta):

        v1 = vector.muls(self.cohesion(l), self.__cohesion_factor)
        v2 = vector.muls(self.separation(l), self.__separation_factor)
        v3 = vector.muls(self.rate(l), self.__rate_factor)

        self.velocity = vector.add(self.velocity, v1, v2, v3)

        self.velocity = vector.maxs(vector.mins(self.velocity, self.__velocity_max), -self.__velocity_max)

        self.direction = vector.dir(vector.add(self.velocity, (0, 192 / 6)))
        self.set_rotation(-math.degrees((self.direction - math.radians(90)) % math.radians(360)))
Esempio n. 8
0
    def line_of_sight(self,level,playerPos):

        #check all nodes between the player and the enemy to see if there
        #is a wall in the way

        rel = vector.normalized(vector.add([playerPos[1],playerPos[0]],vector.negative(self.pos)))
        checkPos = self.pos

        for i in 10 * range(int(math.floor(vector.distance([playerPos[1],playerPos[0]],self.pos))) - 1):
            checkPos = vector.add(checkPos,[rel[0] * 0.1,rel[1] * 0.1])
            if not level.map[int(math.floor(checkPos[1]))][int(math.floor(checkPos[0]))] == 0:
                return False
        return True
def stoch_descent(X, y, alpha, w):
    """
    Stochastic gradient descent
    :param X:
    :param y:
    :param alpha:
    :param w:
    :return:
    """
    global logs, logs_stoch
    logs = []
    logs_stoch = []
    random.seed(0)
    idx = list(range(len(X)))
    for epoch in range(1000):
        random.shuffle(idx)
        w_old = w
        for i in idx:
            loss = y[i] - vector.dot(X[i], w)
            gradient = vector.mul(loss, X[i])
            w = vector.add(w, vector.mul(alpha, gradient))
            logs_stoch += (w, alpha, sse(X, y, w))
        if vector.norm(vector.sub(w, w_old)) / vector.norm(w) < 1.0e-5:
            break
        logs += (w, alpha, sse(X, y, w))
    print("Epoch", epoch)
    return w
Esempio n. 10
0
    def draw_puck(self, bag):
        """
        Draws the puck into the image.
        :param bag:
        :return:
        """

        if 'position' in bag.puck:

            # draw puck itself
            color = ((255, 0, 0) if bag.puck.is_predicted_position else (0, 255, 0))
            cv2.circle(bag.image, bag.puck.position_pixel, bag.puck.radius_unscaled, color, 2)
            cv2.circle(bag.image, bag.puck.position_pixel, 2, (0, 0, 255), 3)

            if 'path' in bag.puck:

                # draw puck movement
                #direction_velocity = vector.mul_by(bag.puck.direction, bag.puck.velocity)
                #destination = vector.add(bag.puck.position, direction_velocity)
                #destination_pixel = vector.coord_to_image_space(destination, bag.table_boundaries)
                #cv2.line(bag.image, bag.puck.position_pixel, destination_pixel, (255, 0, 0))

                # draw path
                for i in xrange(0, len(bag.puck.path) - 1):
                    position = vector.coord_to_image_space(bag.puck.path[i][0], bag.table_boundaries)
                    destination = vector.coord_to_image_space(bag.puck.path[i + 1][0], bag.table_boundaries)
                    cv2.line(bag.image, position, destination, (255, 0, 0))
                    cv2.circle(bag.image, position, 1, (0, 0, 255), 2)
                position_pixel = vector.coord_to_image_space(bag.puck.path[-1][0], bag.table_boundaries)
                direction_velocity = vector.mul_by(bag.puck.path[-1][1], bag.puck.path[-1][2])
                destination = vector.add(bag.puck.path[-1][0], direction_velocity)
                destination_pixel = vector.coord_to_image_space(destination, bag.table_boundaries)
                cv2.line(bag.image, position_pixel, destination_pixel, (255, 0, 0))
Esempio n. 11
0
 def draw_angle(self):
     """Draw a line representing the angle """
     direction = vector.from_angle(self.angle)
     vect = vector.scalar_multiply(direction, 20)
     endpos = vector.add(self.rect.center, vect)
     return pygame.draw.line(self.level.screen, (255, 255, 0),
                             self.rect.center, endpos)
Esempio n. 12
0
def stoch_descent(X, y, alpha, w):
    """
    Stochastic gradient descent
    :param X:
    :param y:
    :param alpha:
    :param w:
    :return:
    """
    global logs, logs_stoch
    logs = []
    logs_stoch = []
    random.seed(0)
    idx = list(range(len(X)))
    for epoch in range(1000):
        random.shuffle(idx)
        w_old = w
        for i in idx:
            loss = y[i] - vector.dot(X[i], w)
            gradient = vector.mul(loss, X[i])
            w = vector.add(w, vector.mul(alpha, gradient))
            logs_stoch += (w, alpha, sse(X, y, w))
        if vector.norm(vector.sub(w, w_old)) / vector.norm(w) < 1.0e-5:
            break
        logs += (w, alpha, sse(X, y, w))
    print("Epoch", epoch)
    return w
Esempio n. 13
0
    def cohesion(self, l):
        v = (0, 0)
        for i in l:
            v = vector.add(v, i.rect.center)
        v = vector.divs(v, len(l))

        return self.steer(v)
Esempio n. 14
0
def require_tile(pos):
    global tile_offset
    global board
    (x, y) = vec.add(pos, tile_offset)
    width = len(board)
    height = len(board[0])
    if x < 0:
        tile_offset = (tile_offset[0] - x, tile_offset[1])
        board = [mk_tile_list(height) for i in range(-x)] + board
        x = 0
    elif x >= width:
        board += [mk_tile_list(height) for i in range(x - width + 1)]
    if y < 0:
        tile_offset = (tile_offset[0], tile_offset[1] - y)
        amt = -y
        for i in range(
                len(board)
        ):  # Cannot use 'width' here, possibly invalidated by x-axis expansion
            board[i] = mk_tile_list(amt) + board[i]
        y = 0
    elif y >= height:
        amt = y - height + 1
        for col in board:
            col += mk_tile_list(amt)
    return board[x][y]
Esempio n. 15
0
    def move_stick(self, bag):
        """
        Moves the stick.
        :param bag: The parameter bag.
        :return:
        """
        if 'position' not in bag.stick:
            bag.next.stick.position = strategy.SimpleStrategy.HOME_POSITION
            return
        if 'dest_position' not in bag.stick:
            position = bag.stick.position
        else:

            # move stick towards destination
            # ignore dest_direction and dest_velocity
            dist_moved = strategy.SimpleStrategy.STICK_MAX_SPEED * bag.time_diff
            direction = vector.from_to(bag.stick.position, bag.stick.dest_position)
            if dist_moved > vector.length(direction):
                position = bag.stick.dest_position
            else:
                direction = vector.mul_by(vector.normalize(direction), dist_moved * strategy.SimpleStrategy.STICK_MAX_SPEED)
                position = vector.add(bag.stick.position, direction)

        # set new position
        bag.next.stick.position = position
Esempio n. 16
0
    def _predict_position(self, bag, current_time):
        """
        Guesses the puck's position.
        :param bag: The parameter bag
        :param current_time: The current time.
        :return:
        """

        # only possible if we have a path and a velocity
        if len(self.last_path) > 0:

            # find path part in which the the puck should be by now
            path_part_index = 0
            while path_part_index < len(self.last_path):
                path_part = self.last_path[path_part_index]
                if path_part[3] > current_time:

                    # collision time is in future -> take last part
                    path_part_index -= 1
                    break
                path_part_index += 1
            path_part = self.last_path[path_part_index - 1]

            # predict position
            remaining_time = current_time - path_part[3]
            direction = vector.mul_by(path_part[1], path_part[2] * remaining_time)
            bag.puck.predicted_position = vector.add(path_part[0], direction)
            

        elif 'position' in bag.puck:

            # use actual position if found
            bag.puck.predicted_position = bag.puck.position
Esempio n. 17
0
 def draw(self, layer):
     for y in range(11):
         for x in range(15):
             map_position = vector.sub((x, y), self.model.player.position)
             sprite_id = layer[map_position[0]][map_position[1]]
             sprite_image = self.model.sprites.sprites[sprite_id]
             self.model.window.blit(sprite_image, vector.add((x * 32, y * 32), self.model.camera.offset))
Esempio n. 18
0
 def __shoot(self):
     shooting_blob = self.main_blob
     if shooting_blob.get_weight() >= 2*BLOB_INIT_WEIGHT:
         shooting_blob.add_weight(-BULLET_WEIGHT)
         position = vector.add(shooting_blob.get_position(), vector.multiply(self.velocity, shooting_blob.get_radius()))
         new_blob = BulletBlob(self.model, position, self.player_id, vector.multiply(vector.normalize(self.velocity), BLOB_SHOOT_STRENGTH))
         self.model.add_bullet_blob(new_blob)
Esempio n. 19
0
    def predict_puck_movement(self, bag):   #ausgefuehrt
        """
        Predicts the pucks movement.
        :param bag: The parameter bag.
        :return:
        """

        # need at least 2 points
        if len(self.buffer) < 2:
            return

        # loop over points
        direction_sum = (0, 0)
        for i in xrange(0, len(self.buffer) - 1):
            # get tuples and time diff

            current_tuple = self.buffer[i]
            next_tuple 	  = self.buffer[i+1]
            time_diff	  = next_tuple[2] - current_tuple[2]

            # get direction (length is velocity) and divide by time_diff
            direction = vector.mul_by(vector.from_to(current_tuple, next_tuple), 1.0 / time_diff)

            # sum up
            direction_sum = vector.add(direction_sum, direction)

        # averaging
        direction = vector.mul_by(direction_sum, 1.0 / self.buffer_size)

        # add puck direction (normalized) and velocity
        bag.puck.velocity = vector.length(direction)
        bag.puck.direction = vector.normalize(direction)
        bag.next.puck.olddirection = bag.puck.direction
Esempio n. 20
0
    def bound(self, area):
        v = (0, 0)
        diff = area.left - self.rect.left
        if diff > 0:
            v = vector.add(v, (diff, 0))
        diff = self.rect.right - area.right
        if diff > 0:
            v = vector.sub(v, (diff, 0))
        diff = area.top - self.rect.top
        if diff > 0:
            v = vector.add(v, (0, diff))
        diff = self.rect.bottom - area.bottom
        if diff > 0:
            v = vector.sub(v, (0, diff))

        self.velocity = vector.add(self.velocity, vector.muls(v, self.__bound_factor))
Esempio n. 21
0
    def explode(self):
        self.set_weight(int(self.get_weight() * BLOB_EXPLOSION_SHRINK + 0.5))
        has_divided = False

        while self.get_weight(
        ) >= 2 * BLOB_INIT_WEIGHT and self.blob_family.number_of_blobs(
        ) < BLOB_MAX_NUM:
            direction = vector.random_direction()
            position = vector.add(
                self.get_position(),
                vector.multiply(direction, self.get_radius()))

            shoot = random.randint(0, BLOB_EXPLOSION_SHOOT_CHANCE) == 0

            if shoot:
                self.add_weight(-BULLET_WEIGHT)
                bullet_blob = BulletBlob(
                    self.model, position, self.player_id,
                    vector.multiply(direction, BLOB_SHOOT_STRENGTH))
                self.model.add_bullet_blob(bullet_blob)
            else:
                weight = min(
                    random.randint(
                        BLOB_INIT_WEIGHT,
                        max(BLOB_INIT_WEIGHT, int(self.get_weight() / 4))),
                    self.get_weight() - BLOB_INIT_WEIGHT)
                self.add_weight(-weight)
                new_blob = Blob(self.model, position, self.player_id,
                                self.blob_family, (0, 0), weight)

                self.blob_family.add_blob(new_blob)
                self.model.add_blob(new_blob)
                has_divided = True

        if has_divided: self.blob_family.set_countdown()
Esempio n. 22
0
def fit_stoch(X, y, alpha, w, epochs=500, epsilon=1.0e-5):
    """
    Stochastic gradient descent
    :param X:
    :param y:
    :param alpha:
    :param w:
    :param epochs:
    :param epsilon:
    :return:
    """
    global logs, logs_stoch
    logs = []
    logs_stoch = []
    random.seed(0)
    idx = list(range(len(X)))
    for epoch in range(epochs):
        random.shuffle(idx)
        for i in idx:
            y_hat = predict([X[i]], w)[0]
            loss = y[i] - y_hat
            gradient = vector.mul(loss, X[i])
            w = vector.add(w, vector.mul(alpha, gradient))
            logs_stoch += (w, alpha, sse(X, y, w))
        if vector.norm(gradient) < epsilon:
            print('Gradient', vector.norm(gradient))
            break
        logs += (w, alpha, sse(X, y, w))
    print("Epoch", epoch)
    return w
Esempio n. 23
0
def step(points, t):
    """
Implementation of a single step of the de Casteljau algorithm
    :param points: list of n-dimensional points
    :param t: de-Casteljau scaling parameter, numerical value
    :return: the next set of points
    """
    return [vector.add(scal(1 - t, points[i]), scal(t, points[i + 1])) for i in range(len(points) - 1)]
Esempio n. 24
0
    def testAdd02(self):
        z = v.add(self.x, self.x)
        e = (self.x[0] + self.x[0], self.x[1] + self.x[1])
        for zk, ek in zip(z, e):
            self.assertEqual(zk, ek)

        del e
        del z
Esempio n. 25
0
    def separation(self, list):
        mean = (0.0, 0.0)
        for i in list:
            dist = vector.mag(vector.sub(self.rect.center, i.rect.center))
            if dist > 0 and dist < self.__separation_limit:
                mean = vector.add(mean, vector.divs(vector.sub(self.rect.center, i.rect.center), dist))

        return vector.divs(mean, len(list))
Esempio n. 26
0
def get_tile(pos):
    (x, y) = vec.add(pos, tile_offset)
    if x < 0 or x >= len(board):
        return invalid_tile
    row = board[x]
    if y < 0 or y >= len(row):
        return invalid_tile
    return row[y]
Esempio n. 27
0
    def testAdd01(self):
        z = v.add(self.x, self.y)
        expected = (self.x[0] + self.y[0], self.x[1] + self.y[1])
        for k in xrange(2):
            self.assertEqual(z[k], expected[k])

        del expected
        del z
def match_vector_sums_to(vector_dict, v):
    return set(
        vector.flatten2(
            [ x
              for x in vector.permutations_unordered_no_repeat(list(vector_dict))
              if vector.add(vector_dict[x[0]], vector_dict[x[1]]) == v
            ]
        )
    )
Esempio n. 29
0
 def move(self, offset):
     self.moves += 1
     toff = vector.scalar_multiply(self.velocity, self.moves)
     self.rect = self.original_rect.move(
         vector.add(toff, self.scroll_offset))
     self.maprect = self.original_maprect.move(toff)
     self.ttl -= 1
     if self.ttl <= 0:
         self.kill()
Esempio n. 30
0
 def get_locs_in_range(self):
     ret = []
     # Firstly, target anyone adjacent.
     # This is almost elegant, a list of angles offsets, as from MeleeUnit.
     for x in [0, -1, 1, -2, 2, -3]:
         angle = (6 + x * self.bias_flip + self.bias_angle) % 6
         ret.append(vec.add(self.pos, vec.units[angle]))
     # Next, target people at range 2.
     # This should favor the space "ahead" of us (according to bias_angle)
     # and work back (in even pairs, resolving by bias_flip);
     # unfortuately, I can't tink of an elegant way to do this :(
     range_2_vecs = [(2, 0), (1, 1), (2, -1), (0, 2), (2, -2), (-1, 2),
                     (1, -2), (-2, 2), (0, -2), (-2, 1), (-1, -1), (-2, 0)]
     for v in range_2_vecs:
         ret.append(
             vec.add(self.pos,
                     vec.transform(v, self.bias_flip, self.bias_angle)))
     return ret
Esempio n. 31
0
def draw_point(position):
    c = level[position[X]][position[Y]]
    position = vector.multiply(position, UNIT)
    if c == '.':
        pygame.draw.circle(
            surface, DOT_COLOR,
            vector.to_int(vector.add(position, vector.divide_scalar(UNIT, 2))),
            int(DOT_RADIUS))
    elif c == '|':
        pygame.draw.rect(surface, WALL_COLOR, position + UNIT)
Esempio n. 32
0
    def update(self, dt, level, playerPos):

        if self.timer > 0:
            self.timer -= 1 * dt
            if self.timer < 0:
                self.timer = 0

        relplayer = vector.add([playerPos[1], playerPos[0]],
                               vector.negative(self.pos))

        if self.line_of_sight(level, playerPos):
            #move directly at the player if they can be seen
            if vector.length(relplayer) > 0.2:
                reldir = vector.normalized(relplayer)
                self.pos = vector.add(
                    self.pos,
                    [reldir[0] * self.speed * dt, reldir[1] * self.speed * dt])

        else:

            #update the target position if the player moves to far away
            #from the original target position
            if len(self.nodes) == 0 or vector.distance(
                    self.pos, self.nodes[len(self.nodes) - 1]) > 2:
                self.find_path(level, playerPos)
            else:
                #get the direction to move in
                rel = vector.add(self.nodes[len(self.nodes) - 1],
                                 vector.negative(self.pos))

                #set the position to the vector if moving one step will cause
                #the enemy to move over the node
                if vector.length(rel) < self.speed * dt:
                    self.pos = self.nodes[len(self.nodes) - 1]
                    #return subset of original that doesn't include the first entry
                    self.nodes.remove(self.nodes[len(self.nodes) - 1])
                else:

                    #move towards the node
                    rel = vector.normalized(rel)
                    self.pos = vector.add(
                        self.pos,
                        [rel[0] * self.speed * dt, rel[1] * self.speed * dt])
Esempio n. 33
0
 def _shoot(self):
     self.ticks_to_fire -= 1
     if self.ticks_to_fire <= 0:
         direction = vector.from_angle(self.angle + 180)
         velocity = vector.scalar_multiply(direction, 3)
         location = vector.add(
             self.maprect.center,
             vector.scalar_multiply(direction, self.maprect.width / 2))
         self.level.add(TickShot(velocity=list(velocity)), location)
         self.ticks_to_fire = self.fps
Esempio n. 34
0
def pacman_loop():
    if level[pacman.position[X]][pacman.position[Y]] == '.':
        bite_sound.stop()
        bite_sound.play()
    level[pacman.position[X]][pacman.position[Y]] = ' '
    position = vector.add(pacman.position, pacman.direction)
    position = border(position)
    if get(position) == '|':
        return
    pacman.position = position
Esempio n. 35
0
    def _fits_on_screen(self, item):
        right, bottom = self._map_coord_to_screen(
            vector.substract(item.get_position(),
                             (item.get_radius(), item.get_radius())))
        left, top = self._map_coord_to_screen(
            vector.add(item.get_position(),
                       (item.get_radius(), item.get_radius())))
        screen_size = self.screen.get_size()

        return left >= 0 and top >= 0 and right <= screen_size[
            0] and bottom <= screen_size[1]
Esempio n. 36
0
 def extend(self, n):
     if n <= self.max_cache:
         return self.cache[:n + 1]
     result = self.cache
     row = self.cache[-1]
     for i in range(self.max_cache, n + 1):
         row = vector.add(row, vector.shift(row, 1))
         result.append(row)
     self.cache = result
     self.max_cache = n
     return result
Esempio n. 37
0
 def update(self):
     super(TickFactory, self).update()
     self.ticks_to_spawn -= 1
     if self.ticks_to_spawn <= 0:
         direction = vector.from_angle(self.angle + 180)
         velocity = vector.scalar_multiply(direction, 3)
         location = vector.add(
             self.maprect.center,
             vector.scalar_multiply(direction, self.maprect.width / 2))
         self.level.add(TickShip(velocity=list(velocity)), location)
         self.ticks_to_spawn = self.fps * 2.1
Esempio n. 38
0
    def line_of_sight(self, level, playerPos):

        #check all nodes between the player and the enemy to see if there
        #is a wall in the way

        rel = vector.normalized(
            vector.add([playerPos[1], playerPos[0]],
                       vector.negative(self.pos)))
        checkPos = self.pos

        for i in 10 * range(
                int(
                    math.floor(
                        vector.distance([playerPos[1], playerPos[0]],
                                        self.pos))) - 1):
            checkPos = vector.add(checkPos, [rel[0] * 0.1, rel[1] * 0.1])
            if not level.map[int(math.floor(checkPos[1]))][int(
                    math.floor(checkPos[0]))] == 0:
                return False
        return True
Esempio n. 39
0
def cast_ray(r):
    # walk the ray the distance to the nearest object
    start = r[0]
    for s in range(MAX_STEPS):
        if vector.length(vector.subtract(r[0], start)) > MAX_DISTANCE:
            break
        d, s = min_distance(r[0])
        if d < TOLERANCE:
            return ray_colour(r, s)
        r[0] = vector.add(r[0], vector.scale(r[1], d))
    return 0, 0, 0
Esempio n. 40
0
    def walls(self, width, height):
        """ Return all the walls which can be used for drawing the maze. """
        maze_width, maze_height = len(self.grid[0]), len(self.grid)

        scalex, scaley = width / maze_width, height / maze_height
        scale = min(scalex, scaley)

        centerx = (width -  scale * (maze_width  - 1)) / 2
        centery = (height - scale * (maze_height - 1)) / 2
        center = (centerx, centery)

        walls = []

        # Draw all the horizontal going walls.
        for y in range(maze_height):
            lines = ''.join(map(str, self.grid[y])).split(str(EMPTY))
            offset = 0
            for line in lines:
                if len(line) > 1:
                    start = add(center, mul((offset, y), scale))
                    end = add(center, mul(((offset + len(line)-1), y), scale))
                    walls.append(Wall(start, end))
                    offset += len(line) + 1
                else:
                    offset += 2

        # Draw all the vertical going walls.
        grid_transposed = [list(x) for x in zip(*self.grid)]
        for x in range(maze_width):
            lines = ''.join(map(str, grid_transposed[x])).split(str(EMPTY))
            offset = 0
            for line in lines:
                if len(line) > 1:
                    start = add(center, mul((x, offset), scale))
                    end = add(center, mul((x, (offset + len(line)-1)), scale))
                    walls.append(Wall(start, end))
                    offset += len(line) + 1
                else:
                    offset += 2

        return walls
Esempio n. 41
0
    def rate(self, list):
        mean = (0, 0)
        for i in list:
            mean = vector.add(mean, i.velocity)

        mean = vector.divs(mean, len(list))

        meandist = vector.mag(mean)
        if meandist > self.__force_max:
            mean = vector.muls(vector.divs(mean, meandist), self.__force_max)

        return mean
Esempio n. 42
0
 def train(self, training_input):
     wrong_predictions = 0
     for input, label in zip([item[1:] for item in training_input], [item[0] for item in training_input]):
         prediction = self.predict(input)
         if prediction != label:
             wrong_predictions += 1
         if label == 0 and prediction == 1:
             self.weights[1:] = vector.sub(self.weights[1:], vector.mul(self.learning_rate, input))
             self.weights[0] -= self.learning_rate
         if label == 1 and prediction == 0:
             self.weights[1:] = vector.add(vector.mul(self.learning_rate, input), self.weights[1:])
             self.weights[0] += self.learning_rate
Esempio n. 43
0
    def move(self, move, walls):
        angle_offset = 0
        if move == MOVE_EAST or move == MOVE_WEST:
            angle_offset = 90 if move == MOVE_WEST else -90
        elif move == MOVE_SOUTH:
            angle_offset = -180

        move_vector = atov(self.angle + 30 + angle_offset)
        newpos = add(self.pos, mul(move_vector, Player.AMPLIFIER_MOVE))
        if not intersect_segments(Line(self.pos, newpos), walls):
            self.pos = newpos
            for ray in self.rays: ray.update(newpos)
Esempio n. 44
0
def border(position):
    x = 0
    y = 0
    if position[X] < 0:
        x = WIDTH
    elif position[X] >= WIDTH:
        x = -WIDTH
    if position[Y] < 0:
        y = HEIGHT
    elif position[Y] >= HEIGHT:
        y = -HEIGHT
    return vector.add(position, (x, y))
Esempio n. 45
0
    def longBlit(self):
        if self.attacking:
            blit_pos = self.game.off(self.game.Player.getPos())
            blit_pos = vector.add(blit_pos, self.game.Player.getRigging())
            blit_pos = vector.sub(blit_pos, self.attack_image.get_size())

            #offset for left/back
            blit_pos[0] += self.x_offset
            blit_pos[1] += self.y_offset
            self.new_rect = self.game.screen.blit(self.mod_DAT, blit_pos)
            self.new_rect.center = self.attack_rect.center
            self.attack_rect = self.new_rect
Esempio n. 46
0
    def update(self,dt,level,playerPos):
        
        if self.timer > 0:
            self.timer -= 1 * dt
            if self.timer < 0:
                self.timer = 0
            
        relplayer = vector.add([playerPos[1],playerPos[0]],vector.negative(self.pos))

        if self.line_of_sight(level,playerPos):
            #move directly at the player if they can be seen
            if vector.length(relplayer) > 0.2:
              reldir = vector.normalized(relplayer)
              self.pos = vector.add(self.pos,[reldir[0] * self.speed * dt, reldir[1] * self.speed * dt])

        else:

            #update the target position if the player moves to far away
            #from the original target position
            if len(self.nodes) == 0 or vector.distance(self.pos,self.nodes[len(self.nodes) - 1]) > 2:
                self.find_path(level,playerPos)    
            else:
                #get the direction to move in
                rel = vector.add(self.nodes[len(self.nodes) - 1],vector.negative(self.pos))

                #set the position to the vector if moving one step will cause
                #the enemy to move over the node
                if vector.length(rel) < self.speed * dt:
                    self.pos = self.nodes[len(self.nodes) - 1]
                    #return subset of original that doesn't include the first entry
                    self.nodes.remove(self.nodes[len(self.nodes) - 1])
                else:
                    
                    #move towards the node
                    rel = vector.normalized(rel)
                    self.pos = vector.add(self.pos,[rel[0] * self.speed * dt,rel[1] * self.speed * dt])
Esempio n. 47
0
    def update(self, delta, view):
        """Updates Location"""
        super(Guppy, self).update(delta)

        # Move based on School
        if self.whirl:
            v = (self.target.centerx - self.rect.centerx, self.target.centery - self.rect.centery)
            mag = vector.mag(v)
            if mag < 300 * delta:
                self.rect.center = self.target.center
            else:
                v = vector.muls(vector.divs(v, vector.mag(v)), 300 * delta)
                self.move(v)
        else:
            self.rect.center = vector.add(self.rect.center, vector.muls(self.velocity, delta))
Esempio n. 48
0
    def build_puck_path(self, bag, remaining_forecast_time=None):    #ausgefuehrt
        """
        Checks for a collision with the table boundaries.
        :param bag: The parameter bag.
        :param remaining_forecast_time:
        :return:
        """
        if 'direction' not in bag.puck:
            return

        if remaining_forecast_time is None:
            remaining_forecast_time = const.CONST.TABLE_BOUNDARIES_COLLISION_FORECAST_TIME

        if 'path' not in bag.puck:
            bag.puck.path = []
        if len(bag.puck.path) == 0:
            bag.puck.path.append((bag.puck.position, bag.puck.direction, bag.puck.velocity, bag.puck.detection_time))

        # get position and direction for the current path part
        position = bag.puck.path[-1][0]
        direction = bag.puck.path[-1][1]
        velocity = bag.puck.path[-1][2]

        # follow puck movement for remaining time
        movement = vector.mul_by(direction, velocity)
        predicted_position = vector.add(position, vector.mul_by(movement, remaining_forecast_time))

        # check if position is out of bounds
        collision = self._check_collision(position, predicted_position, movement)
        if collision is not None:

            # add to path
            bag.puck.path.append((collision[0], vector.normalize(collision[1]), velocity, bag.puck.path[-1][3] + collision[2]))

            # continue building path
            remaining_forecast_time -= collision[2]
            #print("Velocity: " + str(velocity))
            #print(remaining_forecast_time)
            #if len(bag.puck.path) > 20:
            #    exit()
            if remaining_forecast_time > 0:
                self.build_puck_path(bag, remaining_forecast_time)

        # save path
        #print("done, path: " + str(bag.puck.path))
        self.last_path = bag.puck.path
Esempio n. 49
0
def batch_descent(X, y, alpha, w):
    """
    Batch gradient descent
    :param X:
    :param y:
    :param alpha:
    :param w:
    :return:
    """
    global logs
    logs = []
    alpha /= len(X)
    for epoch in range(1, 1000):
        loss = vector.sub(y, vector.mul_mat_vec(X, w))
        gradient = vector.mul_mat_vec(vector.transpose(X), loss)
        w_old = w
        w = vector.add(w, vector.mul(alpha, gradient))
        logs += (w, alpha, sse(X, y, w))
        if vector.norm(vector.sub(w, w_old)) / vector.norm(w) < 1.0e-5:
            break
    print("Epoch", epoch)
    return w
Esempio n. 50
0
def intermingle(communities):
    # each race is a dimension, each mix is a vector
    pops, mixes = [], []
    for community in communities:
        pops.append(community.thousands)
        mixes.append(community.racial_mix)
    dimensions = sorted(
        {c.heritage for mix in mixes for c in mix.contributions if c.fraction > 0},
        key=lambda h: h.name)
    totals = []
    for mix_index in range(len(mixes)):
        mix = mixes[mix_index]
        total = [0 for _ in dimensions]
        for c in mix.contributions:
            for i in range(len(dimensions)):
                if c.heritage == dimensions[i]:
                    total[i] = c.fraction
                    break
        totals.append(total)

    # find the average of all communities, weighted by population
    centroid = vector.centroid(totals, pops)

    # differences to the mean from each mix
    diffs = [vector.diff(centroid, total) for total in totals]

    # the smallest community changes the most, up to 2 percentage points
    # everything else scaled to that
    smallest_index = min(range(len(pops)), key=lambda i: pops[i])
    scaled = [vector.scalemax(diffs[i], .02 * pops[smallest_index]/pops[i]) for i in range(len(pops))]
    new_mixes = [vector.add(totals[i], scaled[i]) for i in range(len(pops))]

    return [Community(communities[i].thousands, communities[i].nationality, 
                      people.racial_mix.RacialMix(
                          [people.racial_mix.RaceContribution(new_mixes[i][j], dimensions[j])
                           for j in range(len(dimensions)) if new_mixes[i][j] > 0]),
                      communities[i].language, communities[i].culture)
            for i in range(len(communities))]
Esempio n. 51
0
 def move(self):
     self.pos = vector.add(self.pos, self.velocity)
Esempio n. 52
0
def find_grid(img, cam_rot_guess):
    """
    Takes an undistorted image and a camera rotation guess and finds the position
    of the camera relative to the grid, as well as identifying all visible
    squares in the grid.
    :param img: The image to process
    :param cam_rot_guess:
    :return: (squares, cam_rot, base_object_points)
    """

    birds_view = np.zeros([1000, 1000, 3], dtype=np.uint8)
    cv2.circle(birds_view,
               (int(birds_view.shape[0] / 2), int(birds_view.shape[1] / 2)), 5,
               (255, 255, 0), -1)
    squares, cam_rot_guess = grid.get_square_stats(img, camera_matrix,
                                                   np.array([[]]),
                                                   cam_rot_guess)

    cam_rot = cam_rot_guess

    glued_square_corners = []
    glued_square_coords = []
    square_length = 28.5
    square_gap = 2
    base_object_points = [[-square_length / 2, -square_length / 2, 0],
                          [-square_length / 2, square_length / 2, 0],
                          [square_length / 2, square_length / 2, 0],
                          [square_length / 2, -square_length / 2, 0]]

    for square in squares:
        temp_vec = vec.sub(square.location, squares[0].location)

        temp_vec[0] = (square_length + square_gap) * round(
            temp_vec[0] / (square_length + square_gap), 0)
        temp_vec[1] = (square_length + square_gap) * round(
            temp_vec[1] / (square_length + square_gap), 0)
        temp_vec[2] = 0

        for i in base_object_points:
            glued_square_coords.append(
                [[vec.add(i, temp_vec)[0]], [vec.add(i, temp_vec)[1]],
                 [vec.add(i, temp_vec)[2]]])

        for i in vec.denumpify(square.corners):
            glued_square_corners.append([[i[0]], [i[1]]])

    if len(squares) > 0:
        glued_square_corners = np.asarray(glued_square_corners).astype(float)
        glued_square_coords = np.asarray(glued_square_coords).astype(float)
        glued_square_corners.reshape(len(glued_square_corners), 2, 1)
        glued_square_coords.reshape(len(glued_square_coords), 3, 1)

        # Where the magic happens. Gets vector from camera to center of square
        inliers, full_r_vec, full_t_vec = cv2.solvePnP(glued_square_coords,
                                                       glued_square_corners,
                                                       camera_matrix,
                                                       distortion_coefficients,
                                                       squares[0].rvec,
                                                       squares[0].tvec, True)

        rot_matrix = cv2.Rodrigues(full_r_vec)
        camera_pos = np.multiply(cv2.transpose(rot_matrix[0]), -1).dot(
            full_t_vec)

        cam_to_grid_transform = np.concatenate(
            (cv2.transpose(rot_matrix[0]), camera_pos), axis=1)

        cam_rot = list(cam_to_grid_transform.dot(np.array([0, 0, 1, 0])))

    return squares, cam_rot, base_object_points
Esempio n. 53
0
 def move(self, direction):
     """direction should be a 2D vector"""
     
     self.rect.center = add(self.rect.center, scale(direction, self.speed))
Esempio n. 54
0
#!/usr/bin/env python2

import vector
import math

v1 = [36.886, 53.177, 21.887]
v2 = [38.323, 52.817, 21.996]
v3 = [38.493, 51.553, 22.830]
v4 = [39.483, 50.748, 22.463]

n1 = vector.normalize(v1)
n2 = vector.normalize(v2)

v1 = n1 = 1,2,3
v2 = n2 = 3,4,5

print vector.add(v1, v2)
print vector.subtract(v1, v2)
print vector.normalize(v1)
print vector.dot(n1, n2)
print vector.cross(n1, n2)
print vector.torsion(v1, v2, v3, v4)
Esempio n. 55
0
    def _calculate_collision_point(self, bag):
        """
        Calculates the collision point between the puck and the stick.
        :param bag: The parameter bag.
        :return:
        """

        # NOTE: First attempt, ignoring stick and puck acceleration, puck radius and stick radius here

        # OK, math first:
        #
        # S = stick position
        # C = point of collision
        # v = max speed of the stick
        # P = puck position
        # p = puck direction * velocity
        #
        # Points which the stick can reach in time t build a circle around him:
        # 1. (Cx - Sx)^2 + (Cy - Sy)^2 = r = v * t
        #
        # Points which the puck reaches in time t are on the line:
        # 2. Px + px * t = Cx
        # 3. Py + py * t = Cy
        #
        # Approach:
        # - replace Cx and Cy in 1. with 2. and 3.
        # - bracket the square terms (Px + px * t - Sx)^2 and (Py + py * t - Sy)^2
        # - outline t^2 and t to get a formula like t^2*(...) + t*(...) + (...)
        # - name (...) a, b and c
        # - use the quadratic formula to get t
        # - use puck movement and t to get collision point
        # - use stick position and collision point
        # - gg

        Sx = bag.stick.position[0]
        Sy = bag.stick.position[1]
        Px = bag.puck.position[0]
        Py = bag.puck.position[1]
        px = bag.puck.direction[0] * bag.puck.velocity
        py = bag.puck.direction[1] * bag.puck.velocity
        v = self.STICK_MAX_SPEED

        # calculate a, b and c
        a = px*px + py*py - v*v
        b = 2*Px*px - 2*Sx*px + 2*Py*py - 2*Sy*py
        c = Px*Px - 2*Px*Sx + Sx*Sx + Py*Py - 2*Py*Sy + Sy*Sy

        # calculate t
        inner_sqrt = b*b - 4*a*c
        if inner_sqrt < 0:
            print("Going home, inner sqrt: " + str(inner_sqrt))

            # no chance to get that thing, go home
            self.go_home(bag)
            return

        # use + first, since a is negative (Vpuck - Vstick)
        # (... / 2 * a) -> shortest time needed
        sqrt_b2_4ac = math.sqrt(inner_sqrt)
        t = (-b + sqrt_b2_4ac) / 2*a
        print("Vp: "+str(bag.puck.velocity))
        print("t:  "+str(t))
        if t < 0:

            # too late for that chance, use other result
            t = (-b - sqrt_b2_4ac) / 2*a
            print("t2: "+str(t))

        # get collision point
        C = vector.add((Px, Py), vector.mul_by((px, py), t))
        s = vector.from_to((Sx, Sy), C)

        # save
        bag.stick.dest_position = C
        bag.stick.dest_direction = vector.normalize(s)
        bag.stick.dest_velocity = self.STICK_MAX_SPEED
        bag.stick.dest_time = time.time() + t
Esempio n. 56
0
 def get_bbox(self):
     start = vector.add(self.pos, vector.multiply(self.size, -0.5))
     end = vector.add(self.pos, vector.multiply(self.size, 0.5))
     return start + end
Esempio n. 57
0
 def test_add_vector(self):
     result = vector.add((10,20),(30,40))
     self.assertEqual(result, (40,60))
from math import trunc, sqrt
import GF2

# version code ef5291f09f60+
coursera = 1
# Please fill out this stencil and submit using the provided submission script.

# Some of the GF2 problems require use of the value GF2.one so the stencil imports it.

from GF2 import one

## 1: (Problem 1) Vector Addition Practice 1
#Please express each answer as a list of numbers
p1_v = [-1, 3]
p1_u = [0, 4]
p1_v_plus_u = vector.add(p1_v, p1_u)
p1_v_minus_u = vector.minus(p1_v, p1_u)
p1_three_v_minus_two_u = vector.minus(vector.scalar_mult(3, p1_v), vector.scalar_mult(2, p1_u))

## 2: (Problem 2) Vector Addition Practice 2
p2_u = [-1,  1, 1]
p2_v = [ 2, -1, 5]
p2_v_plus_u = vector.add(p2_v, p2_u)
p2_v_minus_u = vector.minus(p2_v, p2_u)
p2_two_v_minus_u = vector.minus(vector.scalar_mult(2, p2_v), p2_u)
p2_v_plus_two_u = vector.add(p2_v, vector.scalar_mult(2, p2_u))

## 3: (Problem 3) Vector Addition Practice 3
p3_v = [GF2.zero, GF2.one, GF2.one]
p3_u = [GF2.one, GF2.one, GF2.one]
p3_vector_sum_1 = vector.add(p3_v, p3_u)