Ejemplo n.º 1
0
    def calculate_start(sprite, mouse_location):
        mouse_x, mouse_y = mouse_location
        sprite_center = [sprite.rect.centerx, sprite.rect.centery]
        move_vector = [
            mouse_x - sprite.rect.centerx, mouse_y - sprite.rect.centery
        ]
        # normalize the move vector
        unit_move_vector = [
            move_vector[0] / vector.length(move_vector),
            move_vector[1] / vector.length(move_vector)
        ]
        # calculate distance between the center of the player and the potential bullet start point
        distance = vector.distance(sprite_center, [
            sprite_center[0] + unit_move_vector[0],
            sprite_center[1] + unit_move_vector[1]
        ])
        # One number above the radius of the circle circumscribing the player sprite
        radius = hitbox_radius = math.ceil(
            (sprite.image.get_width() / 2) * math.sqrt(2))
        # ensure that the bullet starts outside of the player hitbox
        while distance < hitbox_radius:
            move_vector = vector.multiply_scalar(unit_move_vector, radius)
            distance = vector.distance(sprite_center, [
                sprite_center[0] + move_vector[0],
                sprite_center[1] + move_vector[1]
            ])
            radius += 1  # raise me to lower iterations but possibly increase start distance

        return sprite_center[0] + move_vector[0], sprite_center[
            1] + move_vector[1]
Ejemplo n.º 2
0
def check_collision():
    global colli_point
    vecd0 = vector.sub(colli_point[0],[ball.x, ball.y])
    vecd1 = vector.sub(colli_point[1],[ball.x, ball.y])
    if vector.distance(colli_point[0], [ball.x,ball.y]) <= 60:
            return colli_point[0]
    elif vector.distance(colli_point[1], [ball.x,ball.y]) <= 60:
            return colli_point[1]
    else:
        return None
Ejemplo n.º 3
0
 def test_distance(self):
     vec1 = Vector2f(1.0, 0.0)
     vec2 = Vector2f(0.0, 1.0)
     self.assertEqual(distance(vec1, vec2), sqrt(2), "Dist1 failed")
     vec1 = Vector2f(0.0, 0.0)
     vec2 = Vector2f(0.0, 0.0)
     self.assertEqual(distance(vec1, vec2), 0.0, "Dist2 failed")
     vec1 = Vector2f(0.2314320, 0.3242123)
     vec2 = Vector2f(-0.2342343, 0.0324121)
     self.assertEqual(round(distance(vec1, vec2), 5), 0.54954,
                      "Dist3 failed")
Ejemplo n.º 4
0
def detectLines(frame):
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, 10, 100, apertureSize=3)

    linesTemp = cv2.HoughLinesP(edges,
                                2,
                                np.pi / 180,
                                100,
                                maxLineGap=20,
                                minLineLength=150)

    lines = []
    middlePoints = []

    for i in range(0, len(linesTemp)):
        x1, y1, x2, y2 = linesTemp[i][0]
        lines.insert(len(lines), linesTemp[i][0])
        middlePoints.insert(len(middlePoints),
                            ((x2 + x1) / 2, (y2 + y1) / 2, i))

    ## Trazimo dve linije cija je udaljenost sredisnjih tacaka najveca

    longestDist = 0
    firstLine = 0
    secondLine = 0

    for i in range(0, len(middlePoints)):
        for j in range(i, len(middlePoints)):
            x1, y1, pointNum1 = middlePoints[i]
            x2, y2, pointNum2 = middlePoints[j]
            longDistTemp = ((x2 - x1)**2 + (y2 - y2)**2)**(1 / 2.0)
            if longDistTemp > longestDist:
                firstLine = pointNum1
                secondLine = pointNum2
                longestDist = longDistTemp

    linesFinal = {}

    x1, y1, x2, y2 = lines[firstLine]
    firstMidPoint = ((x2 + x1) / 2, (y2 + y1) / 2)
    linesFinal['add'] = ((x1, y1), (x2, y2))
    x1, y1, x2, y2 = lines[secondLine]
    secondMidPoint = ((x2 + x1) / 2, (y2 + y1) / 2)
    linesFinal['sub'] = ((x1, y1), (x2, y2))

    if distance((20, 450), firstMidPoint) < distance(
        (20, 450), secondMidPoint):
        linesFinal['add'], linesFinal['sub'] = linesFinal['sub'], linesFinal[
            'add']

    return linesFinal
Ejemplo n.º 5
0
def data_mean():
    for d, vectors in g_dataSet.items():
        for g in range (35):
            s = sample(g_dataSet_modify[d],3)
            v = vector_mean(s)
            g_dataSet_modify[d].append(v)
            g_dataSet[d].append(v)
        g_dataSet_modify[d] = g_dataSet_modify[d][-35:]
        g_dataSet[d] = g_dataSet[d][-35:]
        for i in range(2, len(g_dataSet[d])):
            distance_1 = distance(g_dataSet[d][i], g_dataSet[d][i - 1])
            distance_2 = distance(g_dataSet[d][i], g_dataSet[d][i - 2])
            if distance_1 > 8 and distance_2 > 8:
                g_dataSet_modify[d].remove(g_dataSet[d][i])
    return g_dataSet_modify
Ejemplo n.º 6
0
 def da_li_le_u_Rasponu(self, item):
     retVal = []
     for obj in self.elements:
         distanca = distance(item['center'], obj['center'])
         if (distanca < 21):
             retVal.append(obj)
     return retVal
Ejemplo n.º 7
0
def inRange(r, item, items):
    # print item
    retVal = []
    for obj in items:
        if (distance(item['center'], obj['center']) < r):
            retVal.append(obj)
    return retVal
Ejemplo n.º 8
0
def update_ball(dt):
    global t, v_init, can_play, Vx, Vy, has_colli, score_point, has_scored
    t += dt
    if has_colli is False:
        y = START_POS[1] + v_init[1]*t + 1/2*G*t*t
        if y < 0:
            y = 0
        x = START_POS[0] + v_init[0]*t
        ball.y = y
        ball.x = x
        if v_init[1] > 0:
            Vy = (v_init[1] + G*t)/4
            Vx = (v_init[0])/4
            update_order(Vx,Vy,dt)
        if t > 2*v_init[1]/abs(G) and v_init[1] > 0:
            reset_ball()
            reset_time()
    else:
        y = START_POS[1] + v_init[1]*t + 1/2*G*t*t
        if y < 0:
            y = 0
        x = START_POS[0] + v_init[0]*t
        ball.y = y
        ball.x = x
        if vector.distance([ball.x,ball.y],score_point) <= 50:
            has_scored = True
        if ball.y < 20 or t > 1.5:
            reset_ball()
            reset_time()
            has_colli = False
Ejemplo n.º 9
0
 def move(self):
     # Get target from behind the leader
     target = self.leader.getPos() - normalize(
         self.leader.getV()) * self.params.followDist
     # Calculate desired direction
     steer = trunc(target - self.pos, self.params.maxF)
     # Truncate final steering vector and convert to acceleration
     steer = trunc(steer + self.repulsionF, self.params.maxF)
     acc = steer / self.params.mass * self.gParams.speed
     # Truncate final speed, slow down if necessary
     self.v = trunc(self.v + acc, self.params.maxV)
     dist = distance(self.pos, target)
     if dist < self.params.slowingD:
         self.v *= dist / self.params.slowingD
     # Calculate new position
     self.pos += self.v * self.gParams.speed
     # Update grid if necessary
     newLoc = Vector2f(
         floor(self.pos.x / 32) + 1,
         floor(self.pos.y / 32) + 1)
     if newLoc.x != self.loc.x or newLoc.y != self.loc.y:
         self.grid.remove(self, self.loc.x, self.loc.y)
         self.loc = newLoc
         self.grid.insert(self, self.loc.x, self.loc.y)
     # Set current angle for drawing
     self.orientation = self.v.angle() * 180 / pi
Ejemplo n.º 10
0
def inRange(r, item, items):
    retVal = []
    for obj in items:
        mdist = distance(item['center'], obj['center'])
        if (mdist < r):
            retVal.append(obj)
    return retVal
Ejemplo n.º 11
0
 def setView(self, bbox, side="front"):
     """Sets the camera looking at one of the sides of the bbox"""
     self.makeCurrent()
     center = (bbox[0] + bbox[1]) / 2
     self.camera.setCenter(*center)
     size = bbox[1] - bbox[0]
     # print "size=",size
     if side == "front":
         hsize, vsize, depth = size[0], size[1], size[2]
         long, lat = 0.0, 0.0
     elif side == "back":
         hsize, vsize, depth = size[0], size[1], size[2]
         long, lat = 180.0, 0.0
     elif side == "right":
         hsize, vsize, depth = size[2], size[1], size[0]
         long, lat = 90.0, 0.0
     elif side == "left":
         hsize, vsize, depth = size[2], size[1], size[0]
         long, lat = 270.0, 0.0
     elif side == "top":
         hsize, vsize, depth = size[0], size[2], size[1]
         long, lat = 0.0, 90.0
     elif side == "bottom":
         hsize, vsize, depth = size[0], size[2], size[1]
         long, lat = 0.0, -90.0
     elif side == "iso":
         hsize = vsize = depth = vector.distance(bbox[1], bbox[0])
         long, lat = 45.0, 45.0
     # go to a distance to have a good view with a 45 degree angle lens
     dist = max(0.6 * depth, 1.5 * max(hsize / self.aspect, vsize))
     self.camera.setEye(long, lat, dist)
     self.camera.setLens(45.0, self.aspect)
     self.camera.setClip(0.1 * dist, 10 * dist)
     self.camera.loadProjection()
Ejemplo n.º 12
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
Ejemplo n.º 13
0
def knn_classify(k: int, labeled_points: List[LabeledPoint],
                 new_point: Vector) -> str:
    by_distance = sorted(labeled_points,
                         key=lambda lp: distance(lp.point, new_point))

    k_nearest_labels = [lp.label for lp in by_distance[:k]]

    return majority_vote(k_nearest_labels)
Ejemplo n.º 14
0
def predict_by_knn_dist(p_v1, p_k=7):
    near = []
    for digit in g_data_set:
        for v2 in g_data_set[digit]:
            dist = distance(p_v1, v2)
            near.append((dist, digit))
    near.sort()
    return knn_by_majority(near[:p_k])
Ejemplo n.º 15
0
 def __init__(self, terrain):
     pos = terrain.start.origin
     tiles = terrain.surrounding_tiles(terrain.start, multiplier=2)
     for tile in tiles:
         if tile.color == colors['road']:
             direction = vector.unit(
                 vector.distance(tile.pos, terrain.start.pos))
     super().__init__(pos, 1, direction, 10, 20, colors['blue'])
Ejemplo n.º 16
0
 def enemies_on_range(self):
     on_range = []
     for enemy in self.terrain.enemy_group:
         distance_vector = vector.distance(enemy.origin, self.origin)
         mag = vector.mag(distance_vector)
         if mag < self.range + enemy.radius:
             on_range.append(enemy)
     return on_range
Ejemplo n.º 17
0
    def calculate_start(sprite, mouse_location):
        mouse_x, mouse_y = mouse_location
        sprite_center = [sprite.rect.centerx, sprite.rect.centery]
        move_vector = [mouse_x - sprite.rect.centerx, mouse_y - sprite.rect.centery]
        # normalize the move vector
        unit_move_vector = [move_vector[0] / vector.length(move_vector), move_vector[1] / vector.length(move_vector)]
        # calculate distance between the center of the player and the potential bullet start point
        distance = vector.distance(sprite_center, [sprite_center[0] + unit_move_vector[0], sprite_center[1] + unit_move_vector[1]])
        # One number above the radius of the circle circumscribing the player sprite
        radius = hitbox_radius = math.ceil((sprite.image.get_width()/2) * math.sqrt(2))
        # ensure that the bullet starts outside of the player hitbox
        while distance < hitbox_radius:
            move_vector = vector.multiply_scalar(unit_move_vector, radius)
            distance = vector.distance(sprite_center, [sprite_center[0] + move_vector[0], sprite_center[1] + move_vector[1]])
            radius += 1  # raise me to lower iterations but possibly increase start distance

        return sprite_center[0] + move_vector[0], sprite_center[1] + move_vector[1]
Ejemplo n.º 18
0
def inRange(
    r, item, items
):  # inRange fja proverava da li ima brojeva u okolini trenutnog broja
    retVal = []
    for obj in items:
        mdist = distance(item['center'], obj['center'])
        if (mdist < r):
            retVal.append(obj)
    return retVal
Ejemplo n.º 19
0
def predict_by_knn_or(p_v1, k=1):
    global g_new_data_set
    all_dist = []
    g_new_data_set = data_by_or()
    for digit in g_new_data_set:
        dist = distance(p_v1, g_new_data_set[digit][0])
        all_dist.append((dist, digit))
    all_dist.sort()
    return all_dist[0][1]
Ejemplo n.º 20
0
 def rotate_cannon(self, enemy):
     distance_vector = vector.distance(enemy.origin, self.origin)
     angle = vector.angle(self.barrel_axis, distance_vector)
     if distance_vector[0] > 0:
         angle *= -1
     rot_image = pygame.transform.rotate(self.original_cannon_image, angle)
     rot_rect = self.original_cannon_image_rect.copy()
     rot_rect.center = rot_image.get_rect().center
     rot_image = rot_image.subsurface(rot_rect).copy()
     self.rotated_cannon = rot_image
Ejemplo n.º 21
0
	def radar(self, object):
		"""
		Returns all objects within a certain radius of a position
		
		@param position: Position of the object to get radar
		@param range: Range of the radar
		"""
		pings = []
		for x in self.objects.itervalues():
			if hasattr(x, 'owner'):
				if x.owner != object.owner:
					if distance(object.position, x.position) <= \
							Constants.scan_range:
						pings.append(x)
			else:
				if distance(object.position, x.position) <= \
					Constants.scan_range:
					pings.append(x)
		return pings
Ejemplo n.º 22
0
def inRange(r, item):
    retVal = []
    for obj in global_contours:
        x1, y1, w1, h1 = cv2.boundingRect(item)
        x2, y2, w2, h2 = cv2.boundingRect(obj)
        mdist = distance((x1, y1), (x2, y2))

        if (mdist < r):
            return True
    global_contours.append(item)
    return False
Ejemplo n.º 23
0
def shouldFireProjectile(window):
    '''Returns true on mouse click (which is > 10px away from last click)'''
    mousePoint = window.checkMouse()
    if mousePoint != None:
        x1 = shouldFireProjectile.oldPos.x
        x2 = mousePoint.x
        y1 = shouldFireProjectile.oldPos.y
        y2 = mousePoint.y
        if vector.distance(x1, y1, x2, y2) > 10:
            shouldFireProjectile.oldPos = mousePoint
            return True, mousePoint
    return False, shouldFireProjectile.oldPos
Ejemplo n.º 24
0
def find_eigenvector(A, tolerance=0.00001):
    guess = [1 for __ in A]

    while True:
        result = matrix_operate(A, guess)
        length = magnitude(result)
        next_guess = scalar_multiply(1 / length, result)

        if distance(guess, next_guess) < tolerance:
            return next_guess, length  # eigenvector, eigenvalue

        guess = next_guess
Ejemplo n.º 25
0
    def compare_square_normals(self, square, dim):
        """
        Increments the score of two squares based on how parallel their normal
        vectors are.
        :param square:
        :param dim: the dimensions of the image
        :return: nothing
        """

        # Using 1-cross product due to larger change of sin when parallel
        temp_cross = cross(self.normal, square.normal)

        edge = False
        for point in square.corners:
            if point[0][0] < 1 or point[0][0] > dim[1] - 2 or point[0][1] < 1 \
                    or point[0][1] > dim[0] - 2:
                # Contours on the edge don't improve scores
                edge = True

        if not edge:
            # Increment the score
            self.score += 1 - abs(distance(temp_cross) / (distance(square.normal)*distance(self.normal)))
Ejemplo n.º 26
0
 def move(self):
     if self.controlled:
         self.v = normalize(self.v) * self.params.maxV
     elif self.seeking:
         self.seek()
     else:
         self.wander()
     # New position is simply last position plus velocity (times simulation speed)
     self.pos += self.v * self.gParams.speed
     if self.seeking and distance(self.pos, self.target) < 10.0:
         self.seeking = False
     # Set current angle for drawing
     self.orientation = self.v.angle() * 180 / pi
Ejemplo n.º 27
0
 def calcRepulsion(self, followers):
     self.repulsionF = Vector2f(0.0, 0.0)
     collisionChecks = 0
     # Calculate evasion from neighbours that are too close
     for i in self.grid.getNeighbours(self.loc.x, self.loc.y):
         d = distance(self.pos, i.pos)
         collisionChecks += 1
         if d < self.params.separationD and d != 0.0:
             self.repulsionF += (self.pos -
                                 i.getPos()) * self.params.separationD / d
     # Evade leader if necessary
     fLeader = self.leader.getPos() + normalize(
         self.leader.getV()) * self.params.followDist
     d = distance(self.pos, fLeader)
     if d < self.params.followDist and d != 0.0:
         self.repulsionF += (self.pos -
                             fLeader) * self.params.followDist / d
     d = distance(self.pos, self.leader.getPos())
     if d < self.params.followDist and d != 0.0:
         self.repulsionF += (self.pos - self.leader.getPos()
                             ) * 2 * self.params.followDist / d
     return collisionChecks
Ejemplo n.º 28
0
	def repair_ship(self, ship_id):
		"""
		Repair a ship, adding repair_percent ship health per turn used.
		
		@type ship: Ship object
		@param ship: A ship object to add health to
		"""
		from game_instance import game
		ship = game.game_map.ships[ship_id]
		if distance(self.position, ship.position) < Constants.base_repair_radius:
			ship.health += Constants.repair_percent * Constants.ship_health
			if ship.health > Constants.ship_health:
				ship.health = Constants.ship_health
Ejemplo n.º 29
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
Ejemplo n.º 30
0
	def create_ship(self, position):
		"""
		Construct a ship.
		
		@type: tuple
		@param position: location the player wants the object at
		"""
		# if outside build radius, move position in
		if distance(self.planet.position, position) > Constants.build_radius:
			mag = hypot(*position)
			position = (position[0]*(Constants.build_radius/mag),
						position[1]*(Constants.build_radius/mag))
		new_ship = Ship(position, self.owner)
		self.owner.resources -= Constants.ship_price
		return new_ship
Ejemplo n.º 31
0
    def compare_square_normals(self, square, dim):
        """
        Increments the score of two squares based on how parallel their normal
        vectors are.
        :param square:
        :param dim: the dimensions of the image
        :return: nothing
        """

        # Using 1-cross product due to larger change of sin when parallel
        temp_cross = cross(self.normal, square.normal)

        edge = False
        for point in square.corners:
            if point[0][0] < 1 or point[0][0] > dim[1] - 2 or point[0][1] < 1 \
                    or point[0][1] > dim[0] - 2:
                # Contours on the edge don't improve scores
                edge = True

        if not edge:
            # Increment the score
            self.score += 1 - abs(
                distance(temp_cross) /
                (distance(square.normal) * distance(self.normal)))
def nadjiNajblizi2(broj, odgovarajuciBrojevi):

    minDistance = math.hypot(
        broj['center'][0] - odgovarajuciBrojevi[0]['center'][0],
        broj['center'][1] - odgovarajuciBrojevi[0]['center'][1])
    najblizi = odgovarajuciBrojevi[0]

    for br in odgovarajuciBrojevi:
        dist = math.hypot(br['center'][0] - broj['center'][0],
                          br['center'][1] - broj['center'][1])
        if dist < minDistance:
            najblizi = br
            minDistance = distance(br['center'], broj['center'])

    return najblizi
Ejemplo n.º 33
0
    def collides(self, other):
        """Checks if this shape collides with another

        Args:
            other: the shape to test collision against
        Returns:
            True if the two shapes collide, False if they do not
        """
        # Start with a bounding circle test, using the effective
        # lengths as radii for the circles. If we don't at least
        # pass this, then the shapes don't collide, and we skip
        # doing the more computationally expensive collision test
        if distance(self.pos, other.pos) > (self.effective_length +
                                            other.effective_length):
            return False

        # We passed the bounding circle test, so we now need to do the
        # more accurate test for collision, using the separating axis
        # theorem

        # First grab the transformed (world-space) vertices of each
        # shape. Then, grab the axes, which are normalized vectors
        # perpendicular to each side
        verts1 = self._get_transformed_verts()
        verts2 = other._get_transformed_verts()
        axes1 = generate_axes(verts1)
        axes2 = generate_axes(verts2)

        # Loop over each set of axes, and project both shapes onto
        # each axis. If they don't overlap on the axis, the shapes do
        # not collide
        for axis in axes1:
            proj1 = project(verts1, axis)
            proj2 = project(verts2, axis)

            if not proj1.overlaps(proj2):
                return False

        for axis in axes2:
            proj1 = project(verts1, axis)
            proj2 = project(verts2, axis)

            if not proj1.overlaps(proj2):
                return False

        # If we got this far, the shapes overlap on each axis,
        # and the shapes collide
        return True
Ejemplo n.º 34
0
 def update(self, targetLocation, targetAim, targetMomentum, shooting):
     for index, effect in enumerate(self.statusEffects):
         effect.update(self, 
                       targetLocation, 
                       targetAim, 
                       targetMomentum, 
                       shooting,
                       effectIndex=index)
     self.weapon.cool()
     d = distance(targetLocation, self.position)
     if d  < FORMATION_LOCK_DISTANCE:
         self.lock()
     else:
         self.unlock()
     def easeMomentum(targetMomentum, c):
         goalmomentum = self.momentum.mult(1-c) + targetMomentum.mult(c)
         diff = goalmomentum - self.momentum
         diff.crop_ip(self.thrust)
         self.propel(diff)
     def easePosition(target, c):
         newpos = self.position.mult(1-c) + target.mult(c)
         self.position = newpos
     if not self.islocked:
         #when not already locked into formation, move toward the assigned position
         goal = targetLocation - self.position 
         timeestimate = sqrt(d/max(self.momentum.magnitude,self.maxSpeed/2))
         goal += (targetMomentum - self.momentum).mult(timeestimate)
         easeMomentum(goal, 0.2)
         if d > (4 * FORMATION_LOCK_DISTANCE):
             #when close to locking into formation, aim in the assigned direction
             goalaimvector = goal.unit
             self.aim = goalaimvector.direction
         else:
             #otherwise aim toward destination
             self.aim = targetAim
     if self.islocked:
         self.momentum = targetMomentum
         self.aim = targetAim
         easePosition(targetLocation,0.5)
         if shooting:
             self.shoot()
     #update image based on new aim
     self.image = pygame.transform.flip(pygame.transform.rotate(self.originalimage,degrees(float(self.aim))),False,True)
     self.rect = self.image.get_rect()
     self.position += self.momentum
Ejemplo n.º 35
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])
Ejemplo n.º 36
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
Ejemplo n.º 37
0
def predict(p_vec):
    knn=[]
    for d,vectors in g_dataSet_modify.items():
        cnt = 0
        for v in vectors:
            dist = distance(v, p_vec)
            if dist > 15:
                cnt = cnt + 1
                if cnt > 2:
                    break
            knn.append((dist, d))
    knn.sort()
    nearest = knn[:9]
    nearest_data = []
    for i in nearest:
        nearest_data.append(i[1])
    c = Counter(nearest_data)
    for i in c.most_common(1):
        nearest_number = i[0]
    return nearest_number
Ejemplo n.º 38
0
def K_NN(p_dataset, test_vector, n, flag):
    data_list = sorted(list(p_dataset.items()))
    judge_list = []
    for i in data_list:
        for j in i[1]:
            vec_dis = distance(j, test_vector)
            judge_list.append((vec_dis, i[0]))

    judge_list.sort()
    # For testing
    # print(len(judge_list))

    if flag == 'f':
        answer_list = []
        for m in range(n):
            answer_list.append(judge_list[m][1])

        return answer_list[0]
    elif flag == 'm':
        answer_list = []
        for m in range(n):
            answer_list.append(judge_list[m][1])

        con_list = Counter(answer_list)
        return con_list.most_common()[0][0]
    elif flag == 'a':
        answer_list = []
        answer_dict = {}
        for m in range(n):
            answer_list.append(judge_list[m])

        for a in answer_list:
            if answer_dict.get(a[1], 0) == 0:
                answer_dict[a[1]] = [a[0]]
            else:
                answer_dict[a[1]].append(a[0])

        answer_list = [(sum(answer_dict[k]) / len(answer_dict[k]), k)
                       for k in sorted(answer_dict.keys())]
        answer_list.sort()
        return answer_list[0][1]
Ejemplo n.º 39
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])
Ejemplo n.º 40
0
def validate_base_action(action, player, turn, resource_counter):
    """
	Validate an action performed by a base

	@param action: Action to validate
	@param player: The player that requested the action
	"""
    # make sure a base action h as all required keys
    attrs = ["command", "obj_id", "args"]
    for attr in attrs:
        if attr not in action.keys():
            return {"success": False, "message": "base action requires a %s attribute" % attr}

            # attempt to coerce the obj_id to int
    try:
        obj_id = action["obj_id"]
    except:
        return {"success": False, "message": "invalid base id"}

        # check if base exists
    base = None
    for planet in game.game_map.planets.itervalues():
        if obj_id == id(planet.base):
            base = planet.base
    if base == None:
        return {"success": False, "message": "base does not exist"}

        # make sure the player owns the base
    if base.owner != player:
        return {"success": False, "message": "not authenticated for that base"}

        # check to see if base is active
    if base.built > 0:
        return {"success": False, "message": "base is under construction"}

        # check if the base is busy
    if base.busy != 0:
        return {"success": False, "message": "base is busy"}

        # make sure args is a dict
    if not isinstance(action["args"], dict):
        return {"success": False, "message": "args must be a object"}

    if action["command"] == "create_ship":
        if "position" not in action["args"].keys():
            return {"success": False, "message": "create_ship requires position arg"}
        elif not isinstance(action["args"]["position"], list):
            return {"success": False, "message": "position must be list"}
        elif resource_counter - Constants.ship_price < 0:
            return {"success": False, "message": "not enough resources"}
        position = action["args"]["position"]
        if distance(position, base.position) > Constants.base_build_radius:
            return {"success": False, "message": "too far away to build ship"}
        else:
            position = action["args"]["position"]
            try:
                (a, b) = (position[0], position[1])
            except:
                return {"success": False, "message": "invalid position values"}
            result = {"object": base, "method": action["command"], "params": extract(["position"], action["args"])}
            with game.action_list_lock:
                game.actions[turn][player.auth].append(result)
            base.busy = Constants.base_build_busy
            resource_counter -= Constants.ship_price
            return {"success": True, "message": "success"}

    elif action["command"] == "salvage_ship":
        if "ship_id" not in action["args"].keys():
            return {"success": False, "message": "salvage_ship requires ship_id arg"}
        else:
            ship_id = action["args"]["ship_id"]
            if not isinstance(ship_id, int):
                return {"success": False, "message": "ship must be int"}
            ship = game.game_map.ships[ship_id]
            if distance(ship.position, base.position) > Constants.base_salvage_radius:
                return {"success": False, "message": "too far away to salvage ship"}
            result = {"object": base, "method": action["command"], "params": extract(["ship_id"], action["args"])}
            with game.action_list_lock:
                game.actions[turn][player.auth].append(result)
            base.busy = Constants.base_salvage_busy
            return {"success": True, "message": "success"}

    elif action["command"] == "repair_ship":
        if "ship_id" not in action["args"].keys():
            return {"success": False, "message": "repair_ship requires ship_id arg"}
        else:
            ship_id = action["args"]["ship_id"]
            if not isinstance(ship_id, int):
                return {"success": False, "message": "ship must be int"}
            ship = game.game_map.ships[ship_id]
            if distance(ship.position, base.position) > Constants.base_repair_radius:
                return {"success": False, "message": "too far away to repair ship"}
            elif ship.health == Constants.base_health:
                return {"success": False, "message": "ship already at full health"}
            result = {"object": base, "method": action["command"], "params": extract(["ship_id"], action["args"])}
            with game.action_list_lock:
                game.actions[turn][player.auth].append(result)
            base.busy = Constants.base_repair_busy
            return {"success": True, "message": "success"}

    elif action["command"] == "destroy":
        result = {"object": base, "method": action["command"], "params": {}}
        with game.action_list_lock:
            game.actions[turn][player.auth].append(result)
        return {"success": True, "message": "success"}

    else:
        return {"success": False, "message": "invalid base command"}
Ejemplo n.º 41
0
 def intersection(self, segment):
     closest_point = segment.closest_point(self.center)
     if distance(closest_point, self.center) <= self.radius:
         return closest_point
     else:
         return None
Ejemplo n.º 42
0
                #rotate the direction and the plane so that it stays perpendicular to the direction
                player.dir = vector.rotate(player.dir,turnSpeed * dt)
                player.plane = vector.rotate(player.plane,turnSpeed * dt)

            if keys_pressed[K_RIGHT]:
                #rotate the direction and the plane so that it stays perpendicular to the direction                
                player.dir = vector.rotate(player.dir,-turnSpeed * dt)
                player.plane = vector.rotate(player.plane,-turnSpeed * dt)

        for entity in level.entities:

          #enter the shop if the player goes close enough to the object that represents it
          if health > 0 and wave_num < len(waves):
              if not entity.__class__.__name__ == "Explosion" and entity.type == 3:
                  #allow the player to move away from the shop once they exit the shop gameState
                  if vector.distance(entity.pos, [player.pos[1],player.pos[0]]) < 0.5:
                      if shop == False:
                          shop = True
                          gameState = 'shop'
                  else:
                      shop = False
            
          if entity.__class__.__name__ == "Explosion" and entity.life == 0 and entity.timer == 0:
              #the first frame that the explosion is updated
              #damage the player if they are too close to te explosion
              if vector.distance(entity.pos, [player.pos[1],player.pos[0]]) < 1.5:
                  if health >= 8 / (defense_multiplyer * (1.05 ** defense_upgrades)):
                      health -= 8 / (defense_multiplyer * (1.05 ** defense_upgrades))
                  else:
                      health = 0
                  dmg_timer = 0.35
Ejemplo n.º 43
0
                #rotate the direction and the plane so that it stays perpendicular to the direction
                player.dir = vector.rotate(player.dir, turnSpeed * dt)
                player.plane = vector.rotate(player.plane, turnSpeed * dt)

            if keys_pressed[K_RIGHT]:
                #rotate the direction and the plane so that it stays perpendicular to the direction
                player.dir = vector.rotate(player.dir, -turnSpeed * dt)
                player.plane = vector.rotate(player.plane, -turnSpeed * dt)

        for entity in level.entities:

            #enter the shop if the player goes close enough to the object that represents it
            if health > 0 and wave_num < len(waves):
                if not entity.__class__.__name__ == "Explosion" and entity.type == 3:
                    #allow the player to move away from the shop once they exit the shop gameState
                    if vector.distance(entity.pos,
                                       [player.pos[1], player.pos[0]]) < 0.5:
                        if shop == False:
                            shop = True
                            gameState = 'shop'
                    else:
                        shop = False

            if entity.__class__.__name__ == "Explosion" and entity.life == 0 and entity.timer == 0:
                #the first frame that the explosion is updated
                #damage the player if they are too close to te explosion
                if vector.distance(entity.pos,
                                   [player.pos[1], player.pos[0]]) < 1.5:
                    if health >= 8 / (defense_multiplyer *
                                      (1.05**defense_upgrades)):
                        health -= 8 / (defense_multiplyer *
                                       (1.05**defense_upgrades))
Ejemplo n.º 44
0
	def fire(self, direction):
		from game_instance import game
		"""Fire at angle relative to the ship's direction.  The laser is
		instant and is a rectangle with a width of 10 and a length of
		self.weapon_strength. Any object that intersects that rectatngle
		takes damage.

		@param direction: vector to fire at 
		"""
		from asteroid import Asteroid
		from planet import Planet
		from ship import Ship
		width = Constants.weapon_width
		length = self.weapon_range
		mag = hypot(*direction)
		if mag != 0:
			normalized = (direction[0]*(length/mag),direction[1]*(length/mag))
		else: normalized = (0,0)
		angle = atan2(*direction)
		w = width/2
		# Four points, counter clockwise
		p_0 = (self.position[0] + w * cos(angle),
				self.position[1] + w * -sin(angle))
		p_3 = (self.position[0] + w * -cos(angle),
				self.position[1] + w * sin(angle))
		p_1 = (p_0[0] + length * sin(angle), p_0[1] + length * cos(angle))
		p_2 = (p_3[0] + length * sin(angle), p_3[1] + length * cos(angle))

		# rectangle of laser beam
		beam = (p_0, p_1, p_2, p_3)
		within_beam = [] # list for objects in beam
		for obj in game.game_map.objects.itervalues():
			hit = circle_in_rect((obj.position, obj.size), beam)
			if hit and obj != self:
				within_beam.append(obj)
		if len(within_beam) == 0:
			# No object hit
			self.events.append({'type':'shot','hit': None})
		else:
			cmp_dist = lambda a: distance(self.position, a.position)
			within_beam.sort(key=cmp_dist)
			for o in within_beam:
				if isinstance(o, Planet) or isinstance(o, Asteroid):
					if hasattr(o,'base') and o.base != None:
						if o.base.owner == self.owner:
							within_beam.remove(o)
					if hasattr(o, 'refinery') and o.refinery != None:
						if o.refinery.owner == self.owner:
							within_beam.remove(o)
			if len(within_beam) == 0:
			# No object hit
				self.events.append({'type':'shot','hit': None})	
			else:	
				# Hit first in line, record id
				hit = within_beam[0]
				for o in within_beam:
					for i in within_beam:
						if isinstance(o, Ship) and o != i:
							if circle_collision((o.position, o.size),(i.position, i.size)):
								hit = o
				if hasattr(hit, 'base') and hit.base != None:
					hit = hit.base
				if hasattr(hit, 'refinery') and hit.refinery != None:
					hit = hit.refinery
				self.events.append({'type':'shot', 'hit': id(hit),'obj_type':hit.__class__.__name__})
			# register damage with hit object
				diagonal = distance(self.position, p_2)
				dist = distance(self.position, hit.position)
				damage_amt = Constants.weapon_strength
				hit.events.append({'type':'damage',
								   'amount':damage_amt,
								   'hit_by':id(self)})
				with game.lasers_shot_lock:
					game.lasers_shot[game.turn].append({'start': self.position, 'direction':normalized})
Ejemplo n.º 45
0
def validate_ship_action(action, player, turn, resource_counter):
    """Valide an action performed by a ship

	@param action: Action to validate
	@param player: The player that requested the action
	"""
    # make sure a ship action has all required keys
    attrs = ["command", "obj_id", "args"]
    for attr in attrs:
        if attr not in action.keys():
            return {"success": False, "message": "ship action requires a %s attribute" % attr}

            # attempt to coerce the obj_id to int
    try:
        obj_id = action["obj_id"]
    except:
        return {"success": False, "message": "invalid ship id"}

        # check if ship exiss
    if obj_id in game.game_map.ships.keys():
        ship = game.game_map.ships[obj_id]
    else:
        return {"success": False, "message": "ship does not exist"}

        # make sure the player owns the ship
    if ship.owner != player:
        return {"success": False, "message": "not authenticated for that ship"}

        # make sure args is a dict
    if not isinstance(action["args"], dict):
        return {"success": False, "message": "args must be a object"}

        # validate commands
    if action["command"] == "thrust":
        if ship.methods_used["thrust"]:
            return {"success": False, "message": "thrust action already used"}
        elif "direction" not in action["args"].keys():
            return {"success": False, "message": "thrust requires direction arg"}
        elif not isinstance(action["args"]["direction"], list):
            return {"success": False, "message": "direction must be list"}
        elif "speed" not in action["args"].keys():
            return {"success": False, "message": "thrust requires speed arg"}
        elif not isinstance(action["args"]["speed"], Number):
            return {"success": False, "message": "speed must be Number"}
        else:
            accel = action["args"]["direction"]
            try:
                (a, b) = (accel[0], accel[1])
            except:
                return {"success": False, "message": "invalid direction values"}
            result = {
                "object": ship,
                "method": action["command"],
                "params": extract(["direction", "speed"], action["args"]),
            }
            with game.action_list_lock:
                game.actions[turn][player.auth].append(result)
            ship.methods_used["thrust"] = True
            return {"success": True, "message": "success"}

    elif action["command"] == "fire":
        if ship.methods_used["fire"]:
            return {"success": False, "message": "fire action already used"}
        elif "direction" not in action["args"].keys():
            return {"success": False, "message": "fire requires direction arg"}
        else:
            direction = action["args"]["direction"]
            if not isinstance(direction, list):
                return {"success": False, "message": "direction must be a list"}
            result = {"object": ship, "method": action["command"], "params": extract(["direction"], action["args"])}
            with game.action_list_lock:
                game.actions[turn][player.auth].append(result)
            ship.methods_used["fire"] = True
            return {"success": True, "message": "success"}

    elif action["command"] == "create_refinery":
        if ship.methods_used["create_refinery"]:
            return {"success": False, "message": "create_refinery action already used"}
        elif resource_counter - Constants.refinery_price < 0:
            return {"success": False, "message": "not enough resources"}
        elif "asteroid_id" not in action["args"].keys():
            return {"success": False, "message": "create_refinery requires asteroid_id arg"}
        elif player.resources < Constants.refinery_price:
            return {"success": False, "message": "not enough resources!"}
        else:
            asteroid_id = action["args"]["asteroid_id"]
            if not isinstance(asteroid_id, int):
                return {"success": False, "message": "asteroid_id must be int"}
            asteroid = game.game_map.asteroids[asteroid_id]
            if distance(ship.position, asteroid.position) > Constants.ship_build_radius:
                return {"success": False, "message": "too far away from asteroid"}
            if asteroid.refinery != None:
                return {"success": False, "message": "asteroid already has a refinery"}
            result = {"object": ship, "method": action["command"], "params": extract(["asteroid_id"], action["args"])}
            # TODO Check if another ship has built a base/refinery
            with game.action_list_lock:
                game.actions[turn][player.auth].append(result)
            ship.methods_used["create_refinery"] = True
            resource_counter -= Constants.refinery_price
            return {"success": True, "message": "success"}

    elif action["command"] == "create_base":
        if ship.methods_used["create_base"]:
            return {"success": False, "message": "create_base action already used"}
        elif turn == 0:
            return {"success": False, "message": "create_base action can't be used first turn"}
        elif resource_counter - Constants.base_price < 0:
            return {"success": False, "message": "not enough resources"}
        elif "planet_id" not in action["args"].keys():
            return {"success": False, "message": "create_base requires planet_id arg"}
        else:
            planet_id = action["args"]["planet_id"]
            if not isinstance(planet_id, int):
                return {"success": False, "message": "planet must be int"}
            planet = game.game_map.planets[planet_id]
            if distance(ship.position, planet.position) > Constants.ship_build_radius:
                return {"success": False, "message": "too far away from planet"}
            if planet.base != None:
                return {"success": False, "message": "planet already has a base"}
            result = {"object": ship, "method": action["command"], "params": extract(["planet_id"], action["args"])}
            with game.action_list_lock:
                game.actions[turn][player.auth].append(result)
            ship.methods_used["create_base"] = True
            resource_counter -= Constants.base_price
            return {"success": True, "message": "success"}

    else:
        return {"success": False, "message": "invalid ship command"}