Esempio n. 1
0
    def updateMoveButton(self):
        if self.moveButton1:
            moveDir = Vector(self.moveButton1.targetPos) - Vector(
                self.moveButton1.pos)
            moveDist = moveDir.length()
            moveVel = self.vMoveVel * self.fFrameTime
            if moveVel > moveDist:
                self.moveButton1.pos = self.moveButton1.targetPos
                self.moveButton1 = None
            else:
                moveDir = moveDir.normalize()
                moveDir *= moveVel
                self.moveButton1.pos = (self.moveButton1.pos[0] + moveDir[0],
                                        self.moveButton1.pos[1] + moveDir[1])

        if self.moveButton2:
            moveDir = Vector(self.moveButton2.targetPos) - Vector(
                self.moveButton2.pos)
            moveDist = moveDir.length()
            moveVel = self.vMoveVel * self.fFrameTime
            if moveVel > moveDist:
                self.moveButton2.pos = self.moveButton2.targetPos
                self.moveButton2 = None
            else:
                moveDir = moveDir.normalize()
                moveDir *= moveVel
                self.moveButton2.pos = (self.moveButton2.pos[0] + moveDir[0],
                                        self.moveButton2.pos[1] + moveDir[1])
Esempio n. 2
0
 def avoid_obstacles_vector(self, entity_id, position):
     entities = self.gameworld.entities
     ship_system = entities[entity_id].ship_system
     obstacles_to_avoid = ship_system.in_view
     sum_avoidance = Vector(0, 0)
     ob_count = 0
     for obstacle in obstacles_to_avoid:
         if obstacle != entity_id:
             obstacle = entities[obstacle]
             if not hasattr(obstacle, 'cymunk_physics') or hasattr(
                     obstacle, 'boundary_system'):
                 continue
             ob_location = obstacle.position
             dist = Vector((ob_location.x, ob_location.y)).distance(
                 (position.x, position.y))
             scale_factor = (150. - dist) / 150.
             avoidance_vector = Vector((position.x, position.y)) - Vector(
                 (ob_location.x, ob_location.y))
             avoidance_vector = avoidance_vector.normalize()
             avoidance_vector *= scale_factor
             sum_avoidance += avoidance_vector
             ob_count += 1
     if ob_count > 0:
         sum_avoidance /= float(ob_count)
     sum_avoidance *= ship_system.max_speed
     return sum_avoidance
Esempio n. 3
0
def circleToCircle(a, b):
	v = Vector(a.pos) - Vector(b.pos)

	if v.length() < a.r+b.r:
		return (True, None, v.normalize())
	
	return (False, None, None)
Esempio n. 4
0
 def avoid_obstacles_vector(self, entity_id, position):
     entities = self.gameworld.entities
     ship_system = entities[entity_id].ship_system
     obstacles_to_avoid = ship_system.in_view
     sum_avoidance = Vector(0, 0)
     ob_count = 0
     for obstacle in obstacles_to_avoid:
         if obstacle != entity_id:
             obstacle = entities[obstacle]
             if not hasattr(obstacle, 'cymunk_physics') or hasattr(
                 obstacle, 'boundary_system'):
                 continue
             ob_location = obstacle.position
             dist = Vector((ob_location.x, ob_location.y)).distance(
                 (position.x, position.y))
             scale_factor = (150.-dist)/150.
             avoidance_vector = Vector(
                 (position.x, position.y)) - Vector(
                 (ob_location.x, ob_location.y))
             avoidance_vector = avoidance_vector.normalize()
             avoidance_vector *= scale_factor
             sum_avoidance += avoidance_vector
             ob_count += 1
     if ob_count > 0:
         sum_avoidance /= float(ob_count)
     sum_avoidance *= ship_system.max_speed
     return sum_avoidance
Esempio n. 5
0
class Ball(Widget):
	r = 30 / 2
	r2 = r**2

	trail_pts = []
	g_trail = "trail"

	def setup(self):
		self.pos = (cx, cy+cy/2)
		self.velocity = Vector(0,5)

	def move(self, dt):
		self.canvas.remove_group(self.g_trail)
		with self.canvas:
			Color(1, 1, 1, 0.5, mode='rgba', group=self.g_trail)
			Line(points=sum(self.trail_pts, []), group=self.g_trail)

		to_center = (Vector(cx, cy) - Vector(self.pos))

		l = self.velocity.length()
		cen_d = to_center.length()
		self.velocity = self.velocity * 0.99 + to_center.normalize() * sqrt(cen_d) * 0.04

		if l > 25:
			self.velocity = self.velocity.normalize() * 20
		self.pos = Vector(self.pos) + self.velocity * dt * 30

		if len(self.trail_pts) == 0:
			self.trail_pts = [self.pos]
		else:
			self.trail_pts.insert(0, self.pos)

		while len(self.trail_pts) > 30:
			self.trail_pts.pop()
Esempio n. 6
0
    def update(self, dt):
        """Updates the position and the velocity of the shell.

        Moves the shell based on it's current velocity and the time passed (`dt`).
        Updates the velocity based on `self.gravity`, `self.wind`, `self.drag_coef` and the time passed.

        Args:
            dt: Delta t, the change of time the shell should be updated by.
        """
        # move the shell based on the current velocity and change of time
        self.center = Vector(*self.center) + Vector(*self.velocity) * dt
        # apply gravitational acceleration
        self.velocity_y -= self.gravity * dt

        air_vel = Vector(self.velocity_x - self.wind, self.velocity_y)

        # based on https://en.wikipedia.org/wiki/Drag_equation
        # hides the density, area and other constants for the shell into the drag coefficient
        drag = air_vel.normalize() * self.drag_coef * air_vel.length2()
        vel_vec = Vector(*self.velocity) - (drag / self.mass)
        self.velocity = (vel_vec.x, vel_vec.y)

        # bounce off the walls
        if (self.x < 0) or (self.right > self.parent.width):
            self.velocity_x *= -1
            self.right = clamp(self.right, 0, self.parent.width)
            self.x = clamp(self.x, 0, self.parent.width)

        if self.top > self.parent.height:
            self.velocity_y *= -1
            self.top = clamp(self.top, 0, self.parent.height)
Esempio n. 7
0
def circleToCircle(a, b):
    v = Vector(a.pos) - Vector(b.pos)

    if v.length() < a.r + b.r:
        return (True, None, v.normalize())

    return (False, None, None)
Esempio n. 8
0
class Ball(Widget):
    r = 30 / 2
    r2 = r**2

    trail_pts = []
    g_trail = "trail"

    def setup(self):
        self.pos = (cx, cy + cy / 2)
        self.velocity = Vector(0, 5)

    def move(self, dt):
        self.canvas.remove_group(self.g_trail)
        with self.canvas:
            Color(1, 1, 1, 0.5, mode='rgba', group=self.g_trail)
            Line(points=sum(self.trail_pts, []), group=self.g_trail)

        to_center = (Vector(cx, cy) - Vector(self.pos))

        l = self.velocity.length()
        cen_d = to_center.length()
        self.velocity = self.velocity * 0.99 + to_center.normalize() * sqrt(
            cen_d) * 0.04

        if l > 25:
            self.velocity = self.velocity.normalize() * 20
        self.pos = Vector(self.pos) + self.velocity * dt * 30

        if len(self.trail_pts) == 0:
            self.trail_pts = [self.pos]
        else:
            self.trail_pts.insert(0, self.pos)

        while len(self.trail_pts) > 30:
            self.trail_pts.pop()
Esempio n. 9
0
    def update(self, dt):
        self.ball.move(dt)
        col = self.paddle.collide_widget(self.ball)

        if col[0]:
            #print dt,"bam"
            self.sounds["hit_2"].play()
            d = self.ball.r + self.paddle.r - (
                Vector(self.ball.pos) - Vector(self.paddle.pos)).length()
            #print d
            self.ball.pos = Vector(self.ball.pos) + col[2] * d
            v = self.ball.velocity
            v_n = v.normalize()
            normal = col[2]
            m = max((280 - v.length2()) / 100, 1)
            v = v - normal * 2 * (normal.dot(v)) * m

            self.ball.velocity = v

        killspace_col_paddle = self.killspace.collide_widget(self.ball)

        # WE DIED!
        if killspace_col_paddle[0]:
            self.sounds["die"].play()
            self.start()

        for w in self.blocks:
            col = w.collide_widget(self.ball)

            if col[0]:
                self.sounds["hit"].play()

                closest = col[1]
                circle = self.ball
                mtd = Vector(circle.pos[0], circle.pos[1]) - closest
                mtd = mtd.normalize()
                pos = closest + mtd * 1.05 * self.ball.size[0] / 2
                self.ball.pos = pos

                v = self.ball.velocity
                normal = col[2]
                v = v - normal * 2 * (normal.dot(v))
                self.ball.velocity = v

                self.remove_widget(w)
                self.blocks.remove(w)

                self.score += 5 + 2 * self.level_num

                self.best_score = max(self.score, self.best_score)

                if len(self.blocks) == 0:
                    self.n_rings += 1
                    self.level_num += 1
                    self.ball.setup()
                    self.generate_level()

                break
Esempio n. 10
0
	def update(self, dt):
		self.ball.move(dt)
		col = self.paddle.collide_widget(self.ball)

		if col[0]:
			#print dt,"bam"
			self.sounds["hit_2"].play()
			d = self.ball.r + self.paddle.r - (Vector(self.ball.pos) - Vector(self.paddle.pos)).length()
			#print d
			self.ball.pos = Vector(self.ball.pos) + col[2] * d
			v = self.ball.velocity
			v_n = v.normalize()
			normal = col[2]
			m = max((280-v.length2())/100,1)
			v = v - normal * 2 * (normal.dot(v)) * m

			self.ball.velocity = v

		killspace_col_paddle = self.killspace.collide_widget (self.ball)

		# WE DIED!
		if killspace_col_paddle[0]:
			self.sounds["die"].play()
			self.start()

		for w in self.blocks:
			col = w.collide_widget(self.ball)

			if col[0]:
				self.sounds["hit"].play()

				closest = col[1]
				circle = self.ball
				mtd = Vector(circle.pos[0], circle.pos[1]) - closest
				mtd = mtd.normalize()
				pos = closest + mtd * 1.05 * self.ball.size[0]/2
				self.ball.pos = pos

				v = self.ball.velocity
				normal = col[2]
				v = v - normal * 2 * (normal.dot(v))
				self.ball.velocity = v

				self.remove_widget (w)
				self.blocks.remove(w)

				self.score += 5 + 2 * self.level_num

				self.best_score = max(self.score, self.best_score)

				if len(self.blocks) == 0:
					self.n_rings += 1
					self.level_num += 1
					self.ball.setup()
					self.generate_level()

				break
Esempio n. 11
0
    def update_last_touch(self, touch):
        tx, ty = self.last_touches[touch.uid]
        v = Vector(touch.x - tx, touch.y - ty)
        v1 = v
        if 0 < v.length() < self.stroke_error_margin:
            v = Vector(0, 0)

        if v.length() > 0:
            self.stroke_list[touch.uid][-1] = self.round_vector(v.normalize())
    def update_line(self, startPt, endPt, loop):
        startPt = Vector(startPt)
        endPt = Vector(endPt)
        if not loop:
            line_vec = Vector(endPt) - Vector(startPt)
            line_vec_unit = line_vec.normalize()
            orth_unit_vec = Vector(-line_vec[1], line_vec[0]).normalize()
            arrow_pt = Vector(endPt)
            other_pt = -line_vec_unit * 12 + Vector(endPt)

            self.mainLine.bezier = (startPt[0], startPt[1], endPt[0], endPt[1])
            self.arrowColor.r = 1
            self.arrowColor.g = 1
            self.arrowColor.b = 0
            self.arrow.points = (other_pt[0] - orth_unit_vec[0] * 10,
                                 other_pt[1] - orth_unit_vec[1] * 10,
                                 arrow_pt[0], arrow_pt[1],
                                 other_pt[0] + orth_unit_vec[0] * 10,
                                 other_pt[1] + orth_unit_vec[1] * 10)
        else:
            angle = (180 / math.pi) * math.atan2(endPt[1] - startPt[1],
                                                 endPt[0] - startPt[0]) - 90
            loop_width = Vector(40, 0).rotate(angle)
            width_orth_unit_vec = Vector(-loop_width[1],
                                         loop_width[0]).normalize()
            loop_start_pt = startPt - loop_width / 2
            loop_end_pt = startPt + loop_width / 2
            self.loop_ctrl_pt = startPt + width_orth_unit_vec * 125

            self.mainLine.bezier = (loop_start_pt[0], loop_start_pt[1],
                                    self.loop_ctrl_pt[0], self.loop_ctrl_pt[1],
                                    loop_end_pt[0], loop_end_pt[1])

            loop_width_unit = loop_width.normalize()
            arrow_pt = self.get_bezier_mid(loop_start_pt, self.loop_ctrl_pt,
                                           loop_end_pt) + loop_width_unit * 5
            arrow_left = arrow_pt + width_orth_unit_vec * 10 - loop_width_unit * 10
            arrow_right = arrow_pt - width_orth_unit_vec * 10 - loop_width_unit * 10

            self.arrowColor.r = .9
            self.arrowColor.g = .9
            self.arrowColor.b = .9
            self.arrow.points = (arrow_left[0], arrow_left[1], arrow_pt[0],
                                 arrow_pt[1], arrow_right[0], arrow_right[1])
Esempio n. 13
0
    def on_touch_up(self, touch):
        v = Vector(touch.pos) - Vector(touch.opos)
        if v.length < 20:
            return
        if abs(v.x) > abs(v.y):
            v.y = 0
        else:
            v.x = 0

        self.move(*v.normalize())
Esempio n. 14
0
    def on_touch_up(self, touch):
        v = Vector(touch.pos) - Vector(touch.opos)
        if v.length() < self.columns:
            return

        if abs(v.x) > abs(v.y):
            v.y = 0
        else:
            v.x = 0
        if not self.game_over:
            self.move(*v.normalize())
Esempio n. 15
0
    def on_touch_up(self, touch):
        v = Vector(touch.pos) - Vector(touch.opos)
        if v.length() < 20:
            return

        if abs(v.x) > abs(v.y):
            v.y = 0
        else:
            v.x = 0

        self.move(*v.normalize())
Esempio n. 16
0
	def updateMoveButton(self):
		if self.moveButton1:
			moveDir = Vector(self.moveButton1.targetPos) - Vector(self.moveButton1.pos)
			moveDist	 = moveDir.length()
			moveVel = self.vMoveVel * self.fFrameTime
			if moveVel > moveDist:
				self.moveButton1.pos = self.moveButton1.targetPos
				self.moveButton1 = None
			else:
				moveDir = moveDir.normalize()
				moveDir *= moveVel
				self.moveButton1.pos = (self.moveButton1.pos[0] + moveDir[0], self.moveButton1.pos[1] + moveDir[1])
				
		if self.moveButton2:
			moveDir = Vector(self.moveButton2.targetPos) - Vector(self.moveButton2.pos)
			moveDist	 = moveDir.length()
			moveVel = self.vMoveVel * self.fFrameTime
			if moveVel > moveDist:
				self.moveButton2.pos = self.moveButton2.targetPos
				self.moveButton2 = None
			else:
				moveDir = moveDir.normalize()
				moveDir *= moveVel
				self.moveButton2.pos = (self.moveButton2.pos[0] + moveDir[0], self.moveButton2.pos[1] + moveDir[1])
Esempio n. 17
0
    def _calculate_resistance_vector(self, affection_zone):
        """Calculate vector from self to widget

        :param affection_zone: bitmap of collission sector
        :type affection_zone: numpy.ones
        :returns: vector from self to widget
        :rtype: kivy.vector.Vector
        """
        resistance_vector = Vector(0, 0)
        for x in range(affection_zone.shape[0]):
            for y in range(affection_zone.shape[1]):
                if not affection_zone[x, y]:
                    resistance_vector += Vector(
                        x - (affection_zone.shape[0] - 1) / 2,
                        y - (affection_zone.shape[1] - 1) / 2).normalize()
        return resistance_vector.normalize()
Esempio n. 18
0
 def move(self, previousPart, magnitude):
     #moves an individual part
     #first calculates the previous part's position and vectorizes it
     previousPos = (previousPart.absolutePos[0],previousPart.absolutePos[1])
     destination = Vector(previousPos[0], previousPos[1])
     current = (self.absolutePos[0], self.absolutePos[1])
     velocity = Vector(destination.x-current[0],destination.y-current[1])
     #determines velocity based on destination and current position
     if destination.distance(current) < self.width:
         #realigns the part velocity so that parts don't outrun the head
         #when the head turns
         magnitude *= velocity.length() / self.width
     velocity = velocity.normalize() * magnitude
     self.absolutePos[0] += velocity.x
     self.absolutePos[1] += velocity.y
     self.wrapAround()
Esempio n. 19
0
    def on_touch_move(self, *args):
        # print("on_touch_down", args)
        touch = args[0]
        # print(touch.pos, self.center)
        # self.stick.center = touch.pos

        center2touch = Vector(*touch.pos) - Vector(*self.center)
        # print("center2touch", center2touch)
        dist = center2touch.length()
        # print("dist", dist)
        self.angle = -Vector(1, 0).angle(center2touch)
        # print("angle", self.angle)
        pos2center = Vector(*self.center) - Vector(*self.pos)
        if dist > self.max_dist:
            dist = self.max_dist
            center2touch = center2touch.normalize() * self.max_dist
        self.stick.center = center2touch + pos2center
        self.magnitude = dist / self.max_dist
Esempio n. 20
0
 def move(self, previousPart, magnitude):
     #moves an individual part
     #first calculates the previous part's position and vectorizes it
     previousPos = (previousPart.absolutePos[0],
                    previousPart.absolutePos[1])
     destination = Vector(previousPos[0], previousPos[1])
     current = (self.absolutePos[0], self.absolutePos[1])
     velocity = Vector(destination.x - current[0],
                       destination.y - current[1])
     #determines velocity based on destination and current position
     if destination.distance(current) < self.width:
         #realigns the part velocity so that parts don't outrun the head
         #when the head turns
         magnitude *= velocity.length() / self.width
     velocity = velocity.normalize() * magnitude
     self.absolutePos[0] += velocity.x
     self.absolutePos[1] += velocity.y
     self.wrapAround()
Esempio n. 21
0
 def calculate_desired_vector(self, target, location, ship_data, ship_ai_data):
     g_map = self.gameworld.systems['default_map']
     map_size_x = g_map.map_size[0]/1.9
     map_size_y = g_map.map_size[1]/1.9
     dist_x = math.fabs(target[0] - location[0])
     dist_y = math.fabs(target[1] - location[1])
     ship_ai_data['distance_to_target'] = Vector(target).distance2(location)
     max_speed = ship_data['max_speed']
     v = Vector(target) - Vector(location)
     v = v.normalize()
     v *= max_speed
     if ship_ai_data['ai_state'] == 'flee':
         v *= -1
     if dist_x > map_size_x:
         v[0] *=-1
     if dist_y > map_size_y:
         v[1] *=-1
     return v
Esempio n. 22
0
 def calculate_desired_vector(self, target, location, system_data):
     # g_map = self.gameworld.systems['default_map']
     # map_size_x = g_map.map_size[0]/1.9
     # map_size_y = g_map.map_size[1]/1.9
     dist_x = math.fabs(target[0] - location[0])
     dist_y = math.fabs(target[1] - location[1])
     system_data["distance_to_target"] = Vector(target).distance2(location)
     max_speed = system_data["max_speed"]
     v = Vector(target) - Vector(location)
     v = v.normalize()
     v *= max_speed
     if system_data["ai_state"] == "flee":
         v *= -1
     # if dist_x > map_size_x:
     # v[0] *=-1
     # if dist_y > map_size_y:
     # v[1] *=-1
     return v
Esempio n. 23
0
    def update_points(self):
        v = Vector(self.start_point[0] - self.end_point[0], self.start_point[1] - self.end_point[1])
        # orthogonal vector
        o_v = v.normalize().rotate(90) * self.thickness / 2.0
        self.quad_points = [
            self.start_point[0] + o_v[0],
            self.start_point[1] + o_v[1],
            self.start_point[0] - o_v[0],
            self.start_point[1] - o_v[1],
            self.end_point[0] - o_v[0],
            self.end_point[1] - o_v[1],
            self.end_point[0] + o_v[0],
            self.end_point[1] + o_v[1],
        ]

        self.x = min(self.quad_points[::2]) - self.thickness
        self.y = min(self.quad_points[1::2]) - self.thickness
        self.width = max(self.quad_points[::2]) - min(self.quad_points[::2]) + 2 * self.thickness
        self.height = max(self.quad_points[1::2]) - min(self.quad_points[1::2]) + 2 * self.thickness
Esempio n. 24
0
 def calculate_desired_vector(self, target, location, ship_data, ship_ai_data, is_player):
     g_map = self.gameworld.systems["default_map"]
     map_size_x = g_map.map_size[0] / 1.9
     map_size_y = g_map.map_size[1] / 1.9
     dist_x = math.fabs(target[0] - location[0])
     dist_y = math.fabs(target[1] - location[1])
     ship_ai_data["distance_to_target"] = Vector(target).distance2(location)
     max_speed = ship_data["max_speed"]
     v = Vector(target) - Vector(location)
     v = v.normalize()
     v *= max_speed
     if not is_player:
         if ship_ai_data["ai_state"] == "flee":
             v *= -1
         if dist_x > map_size_x:
             v[0] *= -1
         if dist_y > map_size_y:
             v[1] *= -1
     return v
Esempio n. 25
0
 def calculate_desired_vector(self, target, location, ship_data,
                              ship_ai_data):
     g_map = self.gameworld.systems['default_map']
     map_size_x = g_map.map_size[0] / 1.9
     map_size_y = g_map.map_size[1] / 1.9
     dist_x = math.fabs(target[0] - location[0])
     dist_y = math.fabs(target[1] - location[1])
     ship_ai_data['distance_to_target'] = Vector(target).distance2(location)
     max_speed = ship_data['max_speed']
     v = Vector(target) - Vector(location)
     v = v.normalize()
     v *= max_speed
     if ship_ai_data['ai_state'] == 'flee':
         v *= -1
     if dist_x > map_size_x:
         v[0] *= -1
     if dist_y > map_size_y:
         v[1] *= -1
     return v
Esempio n. 26
0
    def _update(self, dt):

        self.vel_x += self.acc_x * dt
        self.vel_y += self.acc_y * dt

        move_x = self.vel_x * dt
        move_y = self.vel_y * dt

        self.x += move_x
        self.y += move_y

        # reset force
        self.force_x.clear()
        self.force_y.clear()

        for other in self.parent.children:
            if other is not self and self.collide_widget(other):

                move_vector = Vector(move_x, move_y)
                move_normal = move_vector.normalize()
                move_x_normal, move_y_normal = move_normal

                # gradually move back to position where it is not collided with other
                while self.collide_widget(other):
                    self.x -= move_x_normal
                    self.y -= move_y_normal

                # recalculate velocity upon collision
                direction = self.direction_widget(other)
                if direction in HORIZONTAL:
                    self.vel_x = -self.vel_x * self.bounce
                    self.vel_y = self.vel_y * (1 - self.friction)
                elif direction in VERTICAL:
                    self.vel_x = self.vel_x * (1 - self.friction)
                    self.vel_y = -self.vel_y * self.bounce
                    if direction is DOWN:
                        if "normal" not in self.force_y:
                            self.force_y["normal"] = -self.force_y.get(
                                "gravity", 0)

                # prevent glitch when a block is stuck between multiple blocks
                break  # todo: a better solution for minor trembling
Esempio n. 27
0
 def avoid_obstacles_vector(self, entity_id, position):
     entities = self.gameworld.entities
     obstacles_to_avoid = self.query_physics_bb(position, 100)
     sum_avoidance = Vector(0, 0)
     ob_count = 0
     for obstacle in obstacles_to_avoid:
         if obstacle != entity_id:
             obstacle = entities[obstacle]
             ob_location = obstacle['cymunk-physics']['position']
             dist = Vector(ob_location).distance(position)
             scale_factor = (150. - dist) / 150.
             avoidance_vector = Vector(position) - Vector(ob_location)
             avoidance_vector = avoidance_vector.normalize()
             avoidance_vector *= scale_factor
             sum_avoidance += avoidance_vector
             ob_count += 1
     if ob_count > 0:
         sum_avoidance /= float(ob_count)
     sum_avoidance *= entities[entity_id]['ship_system']['max_speed']
     return sum_avoidance
Esempio n. 28
0
    def on_touch_up(self, touch):
        # Debug section
        self.touch_console_pos = self.con.get_console_pos((touch.x, touch.y))
        self.touch_info['pos'] = touch.pos
        self.touch_info['time_start'] = touch.time_start
        self.touch_info['time_update'] = touch.time_update
        self.touch_info['time_end'] = touch.time_end
        self.touch_info['triple_tap_time'] = touch.triple_tap_time
        self.touch_info['double_tap_time'] = touch.double_tap_time

        # Start of move code
        vec = Vector(touch.pos) - Vector(touch.opos)

        # If travel distance is short then it's probably a tap or click.
        if vec.length() < 50:
            return

        dx, dy = vec.normalize()
        self.player.move(round(dx), round(dy))
        self.update()
Esempio n. 29
0
class OVector:
    def __init__(self, p: Vector, v: Vector, color=Color(1, 1, 1, 1)):
        self.p = p
        self.v = v
        self.color = color

    def end(self):
        return self.p + self.v

    def len(self):
        return self.v.length()

    def normalize(self, unit):
        if self.is_inf():
            self.v = Vector(0, 0)
        else:
            self.v = self.v.normalize() * unit

    def is_inf(self):
        return self.v.x == inf or self.v.y == inf
Esempio n. 30
0
 def avoid_obstacles_vector(self, entity_id, position):
     entities = self.gameworld.entities
     obstacles_to_avoid = self.query_physics_bb(position, 100)
     sum_avoidance = Vector(0, 0)
     ob_count = 0
     for obstacle in obstacles_to_avoid:
         if obstacle != entity_id:
             obstacle = entities[obstacle]
             ob_location = obstacle['cymunk-physics']['position']
             dist = Vector(ob_location).distance(position)
             scale_factor = (150.-dist)/150.
             avoidance_vector = Vector(position) - Vector(ob_location)
             avoidance_vector = avoidance_vector.normalize()
             avoidance_vector *= scale_factor
             sum_avoidance += avoidance_vector
             ob_count += 1
     if ob_count > 0:
         sum_avoidance /= float(ob_count)
     sum_avoidance *= entities[entity_id]['ship_system']['max_speed']
     return sum_avoidance
Esempio n. 31
0
def circleToPolygon(circle, quad):
    cpos = Vector(circle.pos[0], circle.pos[1])

    x = cpos[0]
    y = cpos[1]
    r = circle.r
    r2 = circle.r2
    w = quad

    if (x + r > w.lowerx) and (x - r < w.upperx) and (y + r > w.lowery) and (
            y - r < w.uppery):
        quad = quad.pts
        #print random.randint(0,1000000)

        # for each edge
        best_closest = None
        normal = None
        best_d = None
        for i in range(4):
            edge_pt1 = Vector(float(quad[i * 2]), float(quad[(i * 2 + 1)]))
            edge_pt2 = Vector(float(quad[((i + 1) * 2) % 8]),
                              float(quad[((i + 1) * 2 + 1) % 8]))
            pt = closestPointOnEdge(cpos, edge_pt1, edge_pt2)

            d = pt.distance2(cpos)

            if d < r2 and (best_d is None or d < best_d):
                closest = pt
                normal = edge_pt2 - edge_pt1
                normal = Vector(-normal.y, normal.x).normalize()
                best_d = d
                #return (True, closest, normal)
        if best_d is not None:
            return (True, closest, normal)

        # if we still haven't gotten anything, try this test..
        if polygonContainsPoint(cpos, quad):
            #print "GRRRRRRR"
            return (True, cpos, cpos.normalize())

    return (False, None, None)
Esempio n. 32
0
    def on_touch_move(self, touch):
        if "vjtouch" not in touch.ud:
            return
        vec = Vector(touch.pos) - Vector(self.center)

        vlen = vec.length()

        if vlen > self.radius:
            vec = vec.normalize() * self.radius

        stripsize = 0.2
        try:
            if vlen < self.radius * stripsize or \
               self.radius * (1.0 + stripsize) > vlen > self.radius:
                vibrator.vibrate(0.005)
        except NotImplementedError:
            pass

        self.touch = Vector(self.center) + vec

        self.vec = vec / self.radius
Esempio n. 33
0
 def avoid_obstacles_vector(self, entity_id, position):
     entities = self.gameworld.entities
     obstacles_to_avoid = entities[entity_id]["ship_system"]["in_view"]
     sum_avoidance = Vector(0, 0)
     ob_count = 0
     for obstacle in obstacles_to_avoid:
         if obstacle != entity_id:
             obstacle = entities[obstacle]
             if "cymunk-physics" not in obstacle or "boundary_system" in obstacle:
                 continue
             ob_location = obstacle["cymunk-physics"]["position"]
             dist = Vector(ob_location).distance(position)
             scale_factor = (150.0 - dist) / 150.0
             avoidance_vector = Vector(position) - Vector(ob_location)
             avoidance_vector = avoidance_vector.normalize()
             avoidance_vector *= scale_factor
             sum_avoidance += avoidance_vector
             ob_count += 1
     if ob_count > 0:
         sum_avoidance /= float(ob_count)
     sum_avoidance *= entities[entity_id]["ship_system"]["max_speed"]
     return sum_avoidance
    def retreat(self):
        """Move the enemy to the beetle den.

        This method moves the enemy to the beetle den if it is dead.
        The enemy is set to not dead upon reaching the beetle den.
        This method should be called every frame in place of move if
        the enemy is dead.
        """

        beetle_den_center = self.game.level.beetle_den['center']
        beetle_den_center_coords = beetle_den_center.center
        direction_vector = Vector(beetle_den_center_coords) - Vector(self.center)
        direction_vector = direction_vector.normalize()

        if not self.collide_point(*beetle_den_center_coords):
            self.pos = (direction_vector * self.speed) + Vector(self.pos)
        else:
            self.center = beetle_den_center_coords
            # Reset here as rare bug sometimes happens where grid coordinates not set before move
            self.grid_position = beetle_den_center.coordinates
            self.dead = False
            self.frightened = False
Esempio n. 35
0
def circleToPolygon(circle, quad):
	cpos = Vector(circle.pos[0], circle.pos[1])

	x = cpos[0]
	y = cpos[1]
	r = circle.r
	r2 = circle.r2
	w = quad

	if (x+r > w.lowerx) and (x-r < w.upperx) and (y+r > w.lowery) and (y-r < w.uppery):
		quad = quad.pts
		#print random.randint(0,1000000)
		
		# for each edge
		best_closest = None
		normal = None
		best_d = None
		for i in range(4):
			edge_pt1 = Vector(float(quad[i*2]), float(quad[(i*2+1)]))
			edge_pt2 = Vector(float(quad[((i+1)*2)%8]), float(quad[((i+1)*2+1)%8]))
			pt = closestPointOnEdge(cpos, edge_pt1, edge_pt2)

			d = pt.distance2(cpos)

			if d < r2 and (best_d is None or d < best_d):
				closest = pt
				normal = edge_pt2 - edge_pt1
				normal = Vector(-normal.y, normal.x).normalize()
				best_d = d
				#return (True, closest, normal)
		if best_d is not None:
			return (True, closest, normal)
		
		# if we still haven't gotten anything, try this test..
		if polygonContainsPoint(cpos, quad):
			#print "GRRRRRRR"
			return (True, cpos, cpos.normalize())

	return (False, None, None)
Esempio n. 36
0
    def update_points(self):
        v = Vector(self.start_point[0] - self.end_point[0],
                   self.start_point[1] - self.end_point[1])
        # orthogonal vector
        o_v = v.normalize().rotate(90) * self.thickness / 2.
        self.quad_points = [
            self.start_point[0] + o_v[0],
            self.start_point[1] + o_v[1],
            self.start_point[0] - o_v[0],
            self.start_point[1] - o_v[1],
            self.end_point[0] - o_v[0],
            self.end_point[1] - o_v[1],
            self.end_point[0] + o_v[0],
            self.end_point[1] + o_v[1],
        ]

        self.x = min(self.quad_points[::2]) - self.thickness
        self.y = min(self.quad_points[1::2]) - self.thickness
        self.width = max(self.quad_points[::2]) - min(
            self.quad_points[::2]) + 2 * self.thickness
        self.height = max(self.quad_points[1::2]) - min(
            self.quad_points[1::2]) + 2 * self.thickness
Esempio n. 37
0
    def update(self, dt):
        """ 게임업데이트 """

        if not self.is_start:
            self.txupdate(dt)
            # tip label
            if self.tip_label.opacity <= 1.0:
                self.tip_label.opacity += 0.005

            return

        self.txupdate(dt)

        self.is_ycoll = False

        # Character's Move
        for brick in self.bricks:

            # meet Block
            if self.character.collide_widget(brick):
                z = Vector(self.character.center) - Vector(brick.center)

                if -0.70 < z.normalize()[0] < 0.70:
                    # down
                    if self.character_y_collision(brick):
                        self.is_jumping = False
                        self.is_ycoll = True
                else:
                    self.character_x_collision(brick)

        self.character.move()

        # y 충돌이면 떨어지지 않는다. // 표면보다 같거나 낮으면 떨어지지 않는다.
        if not self.is_ycoll and not self.character.y <= self.y:
            self.character.y -= 5.0

        # floor
        if self.character.y <= self.y and self.is_jumping:
            self.is_jumping = False
            self.character.y = self.y

        # next stage
        if self.character.center_x > self.width or self.character.center_x < 0:
            self.clear_stage()

        # monster
        for monster in self.monsters:
            if self.character.collide_widget(monster):

                if monster.status == 1:  # Food
                    anim = Animation(
                        size=[self.character.player_image.width * 1.2, self.character.player_image.height * 1.2], duration=.2)
                    if anim:
                        anim.stop(self.character.player_image)
                        anim.start(self.character.player_image)
                    # remove monster
                    self.remove_widget(monster)
                    self.monsters.remove(monster)
                    self.score += 1

                elif monster.status == 2:  # Enemy
                    monster.source_dir = "data/mouse_dead.png"
                    monster.status = 3

                    left = Animation(
                        center_x=monster.center_x + 10, duration=.2)
                    right = Animation(center_x=monster.center_x, duration=.2)
                    anim = left + right
                    if anim:
                        anim.stop(self)
                    anim.start(monster)
                    self.score += 2

                elif monster.status == 9:  # Boss
                    monster.source_dir = "data/spider_dead.png"
                    monster.status = 3
                    self.score += 3

                elif monster.status == 10:  # Girl
                    self.character.velocity = [0, 0]
                    self.character.y += 6
                    monster.y += 1
                    if self.center[1] < self.character.y:
                        self.clear_stage()

                # Letter
                elif monster.status in [12, 13, 14, 15, 16, 17, 18, 19, 20, 21]:
                    left = Animation(
                        center_y=monster.center_y + 400, duration=.2)
                    right = Animation(center_y=monster.center_y, duration=.2)
                    anim = left + right
                    if anim:
                        anim.stop(self)
                    anim.start(monster)
                    monster.status = 3
                    self.score += 1

                # Hurt
                elif monster.status in [30, 31, 32, 33, 34]:
                    left = Animation(
                        center_y=monster.center_y + 400, duration=.2)
                    right = Animation(center_y=monster.center_y, duration=.2)
                    anim = left + right
                    if anim:
                        anim.stop(self)
                    anim.start(monster)
                    monster.source_dir = monster.source_dir.replace(
                        "_hurt", "")
                    monster.status = 3
                    self.score += 2

                # 3. MESSAGE
                elif monster.status == 3:
                    pass
                # 4. JUMP - SONIC
                elif monster.status == 4:
                    self.character_jump(2)  # jump time x 2
                # 5. Gold Ring - SONIC
                elif monster.status == 5:
                    self.remove_widget(monster)
                    self.monsters.remove(monster)
                    self.score += 1
                # 6. speed up
                elif monster.status == 23:
                    self.remove_widget(monster)
                    self.monsters.remove(monster)
                    self.score += 1
                    self.character.velocity = [
                        self.character.velocity[0] * 2, 0]

                # 6,7. FLAGS - MARIO
                elif monster.status == 6:
                    self.character.velocity = [0, 0]
                    self.score += 1
                    monster.status = 3

                elif monster.status == 22:
                    self.character.velocity = [
                        self.block_size / self.speed_ratio, 0]

                # 8. Gold coin - MARIO
                elif monster.status in [8, 24]:
                    self.remove_widget(monster)
                    self.monsters.remove(monster)
                    self.score += 1
                self.is_jumping = False

        # trap
        for trap in self.traps:
            if self.character.collide_widget(trap):
                self.failed_stage()
Esempio n. 38
0
 def set_new_target(self, x, y):
     self.target = x, y
     v = Vector(self.target) - Vector(self.center)
     self.velocity = v.normalize() * self.speed