Exemplo n.º 1
0
 def __init__(self,
              img_dict,
              type,
              obj,
              position_or_angle,
              force,
              radius=30):
     if type == 'a':  # count start_position
         start = sum(
             obj.circle.center,
             multiply(angle_to_vector(position_or_angle),
                      obj.circle.radius + radius))
         angle = position_or_angle
         vector = angle_to_vector(angle)
     else:
         vector = inverse(perpendicular(normalise(obj.line.vector)))
         shift = multiply(obj.line.vector,
                          -position_or_angle / 100.0)  # side shift
         start = sum(
             sum(obj.line.start,
                 multiply(vector, PLATFORM.BORDER + radius + 3)), shift)
         angle = vector_to_angle(vector)
     self.circle = Circle(int(round(start[0])), int(round(start[1])),
                          radius)
     self.force = force
     self.force_vector = multiply(vector, force)
     self.img_list = []
     for i in img_dict['geyser'][obj.colour]:
         self.img_list.append(pygame.transform.rotozoom(i, -angle, 1.))
     self.frame = 0
     self.image = self.img_list[self.frame]
     self.frame_speed = BOOSTER.FRAME_SPEED + random.randint(-2, 2)
     image_offset = (-self.img_list[0].get_width() / 2,
                     -self.img_list[0].get_height() / 2)
     self.image_position = sum(self.circle.center, image_offset)
Exemplo n.º 2
0
 def createCircle(self, cx, cy, r, strokewidth=1,
                  stroke='black', fill='none'):
     """
     Creates a circle
     @type  cx: string or int
     @param cx:  starting x-coordinate
     @type  cy: string or int
     @param cy:  starting y-coordinate
     @type  r: string or int
     @param r:  radius
     @type  strokewidth: string or int
     @param strokewidth:  width of the pen used to draw
     @type  stroke: string (either css constants like "black" or numerical
      values like "#FFFFFF")
     @param stroke:  color with which to draw the outer limits
     @type  fill: string (either css constants like "black" or numerical
      values like "#FFFFFF")
     @param fill:  color with which to fill the element(default: no filling)
     @return:  a circle object
     """
     style_dict = {'fill': fill, 'stroke-width': strokewidth,
                   'stroke': stroke}
     myStyle = StyleBuilder(style_dict)
     c = Circle(cx, cy, r)
     c.set_style(myStyle.getStyle())
     return c
Exemplo n.º 3
0
def main() -> None:
    c1x, c1y, c1r = [int(x) for x in input().split()]
    c1 = Circle(Point(c1x, c1y), c1r)
    c2x, c2y, c2r = [int(x) for x in input().split()]
    c2 = Circle(Point(c2x, c2y), c2r)
    left, right = c1.cross_point_circle(c2)
    print("{:.8f} {:.8f} {:.8f} {:.8f}".format(left.x, left.y, right.x,
                                               right.y))
Exemplo n.º 4
0
 def test_cross_point_circle(self):
     self.assertTrue(
         Circle(Point(0, 0), 2).cross_point_circle(Circle(Point(2, 0), 2))
         == [Point(1.0, -1.7320508075),
             Point(1.0, 1.7320508075)])
     self.assertTrue(
         Circle(Point(0, 0), 2).cross_point_circle(Circle(Point(0, 3), 1))
         == [Point(0, 2), Point(0, 2)])
Exemplo n.º 5
0
 def test_cross_point_line(self):
     self.assertEqual(
         Circle(Point(2, 3),
                2).cross_point_line(Line(Point(0, 3), Point(1, 3))),
         [Point(0, 3), Point(4, 3)])
     self.assertEqual(
         Circle(Point(2, 3),
                2).cross_point_line(Line(Point(4, 0), Point(4, 6))),
         [Point(4, 3), Point(4, 3)])
Exemplo n.º 6
0
 def __init__(self, x, y, image):
     self.base_image = image
     radius = (image.get_width() + image.get_height()) / 4
     self.circle = Circle(x, y, radius)
     self.decay = False
     self.decay_time = STAR.DECAY_TIME
     self.image = self.base_image.copy()
     self.image_position = [
         x - image.get_width() / 2, y - image.get_height() / 2
     ]
Exemplo n.º 7
0
 def __init__(self, x, y, event, image, mouseover_image=None):
     self.circle = Circle(x, y, 30)
     self.event = event
     self.base_image = image.copy()
     self.was_pressed = False
     if mouseover_image:
         self.mouseover_image = mouseover_image.copy()
     else:
         self.mouseover_image = image.copy()
     self.image_position = [
         x - image.get_width() / 2, y - image.get_height() / 2
     ]
Exemplo n.º 8
0
def create_objects(form):
    """
        Create shapes.
    """
    message.clear()

    if form["shape_type"] == "Circle":
        circle = Circle(
            form["shape_type"],
            form["width"],
            form["height"],
            form["left"],
            form["top"],
            form["color"]
        )

        message.append(Circle.validate(circle))

        if Circle.validate(circle) == "Circle Added":
            shapes.append(circle)


    if form["shape_type"] == "Square":
        square = Square(
            form["shape_type"],
            form["width"],
            form["height"],
            form["left"],
            form["top"],
            form["color"]
        )

        message.append(Square.validate(square))

        if Square.validate(square) == "Square Added":
            shapes.append(square)


    if form["shape_type"] == "Triangle":
        triangle = Triangle(
            form["shape_type"],
            form["width"],
            form["height"],
            form["left"],
            form["top"],
            form["color"]
        )

        message.append(Triangle.validate(triangle))

        if Triangle.validate(triangle) == "Triangle Added":
            shapes.append(triangle)
Exemplo n.º 9
0
    def __init__(self, position, image_dict):
        self.circle = Circle(position[0], position[1], STAR.RADIUS)

        self.base_image = image_dict['star']
        self.image = self.base_image
        self.image_position = [
            position[0] - STAR.RADIUS, position[1] - STAR.RADIUS
        ]
        self.angle = 0
        self.d_angle = STAR.D_ANGLE
        self.d_d_angle = STAR.D_D_ANGLE
        self.decay = False
        self.decay_time = STAR.DECAY_TIME
Exemplo n.º 10
0
 def __init__(self, type, img_dict, bullets, obj, angle_from=0, angle_length=100):
     Monster.__init__(self)
     self.type = type
     self.direction = 1 # or -1
     self.pause_length = MONSTER.C.PAUSE
     self.infinite = False
     self.img_dict = img_dict['C']
     self.shift_constant = self.img_dict['move'][0].get_height()/2 - MONSTER.C.RADIUS
     self.went = 0
     self.state = MONSTER.C.MOVING
     self.bullets = bullets
     if type == MONSTER.TYPE_ANGLE: # from to clockwise
         center, radius = obj.circle.center, obj.circle.radius + MONSTER.C.RADIUS
         self.angle_from = angle_from
         self.angle = self.angle_from
         self.length = angle_length
         if angle_length == -1 or angle_length == 0:
             self.infinite = True
             if angle_length == 0:
                 self.direction = -1
         self.speed = to_degrees(MONSTER.C.SPEED/float(radius)) # degrees/second
         self.move_radius = radius
         self.center = center
         self.circle = Circle(center[0], center[1], MONSTER.C.RADIUS)
     else: # doesn't work properly, should check out later on
         start = obj.line.start
         end = obj.line.end
         fr = angle_from
         to = angle_length
         self.vector = inverse(normalise(obj.line.vector))
         self.start = sum(start, multiply(obj.line.vector, -fr/100.0))
         end = sum(start, multiply(obj.line.vector, -to/100.0))
         dist = subtract(self.start, end)
         self.length = pythagory(dist[0], dist[1])
         angle_vector =  normalise(perpendicular(self.vector)) # angle_from means rotation coefficient and is now 1 or -1
         self.angle = vector_to_angle(angle_vector)
         self.start = sum(self.start, multiply(angle_vector, PLATFORM.BORDER + MONSTER.C.RADIUS))
         self.speed = MONSTER.C.SPEED
         # prepare images
         d = {'move': [], 'reload': [], 'bullets': []}
         for i in self.img_dict['move']:
             d['move'].append(pygame.transform.rotozoom(i, -self.angle,1.))
         for i in self.img_dict['reload']:
             d['reload'].append(pygame.transform.rotozoom(i, -self.angle,1.))
         for i in self.img_dict['bullets']:
             d['bullets'].append(pygame.transform.rotozoom(i, -self.angle,1.))
         self.circle = Circle(self.start[0], self.start[1], MONSTER.C.RADIUS)
         self.img_dict = d
         self.image_offset = subtract(multiply(angle_vector, self.shift_constant), (img_dict['C']['move'][0].get_width()/2, img_dict['C']['move'][0].get_height()/2))
         self.image_position = sum(self.circle.center, self.image_offset)
     self.update_image(1)
Exemplo n.º 11
0
def init():

    pygame.init()
    Game.screen = pygame.display.set_mode(Game.screen_size)
    pygame.display.set_caption("physics engine 2d")
    Game.done = False
    Game.clock = pygame.time.Clock()

    #b = Body( Circle(20), 140, 50)
    #b = Body( Circle(100), 300, 600)
    #b.setStatic()
    #Game.bodies.append(b)
    b = Body(Circle(100), 100, 600)
    b.setStatic()
    Game.bodies.append(b)

    b = Body(Circle(20), 200, 350)
    b.setStatic()
    Game.bodies.append(b)

    #Game.target = b

    #b2 = Body( Circle(70), 100, 300)
    #b2 = Body( Circle(90), 50, 150)
    #b2.setStatic()
    #Game.bodies.append(b2)

    #b3 = Body( Circle(70), 200, 400)
    #b3 = Body( Circle(100), 220, 50)
    #b3.setStatic()
    #Game.bodies.append(b3)

    #b4 = Body( Circle(70), 350, 400)
    #b4 = Body( Circle(200), 600, 0)
    #b4.setStatic()
    #Game.bodies.append(b4)

    #verts = [Vec2(-17,10),Vec2(-33,-28),Vec2(-30,50),Vec2(10,20),Vec2(20,40),Vec2(17,-12), Vec2(-30,-10),Vec2(13,44)]

    #b5 = Body( Polygon(verts=verts), 300, 400, math.pi/3 )
    #b5 = Body( Polygon(boxHw=50, boxHh=100), 300, 400, math.pi/3 )
    #b5.shape.setBox(50, 100)
    #b5.setStatic()
    #Game.bodies.append(b5)

    b6 = Body(Polygon(boxHw=260, boxHh=10), 500, 300)
    b6.setOrient(0)
    b6.setStatic()
    Game.bodies.append(b6)
    Game.seasaw = b6
Exemplo n.º 12
0
 def __init__(self, player):
     position = player.circle.center
     self.center = [position[0], position[1]]
     self.offset = [0, 0]
     self.circle = Circle(position[0], position[1], CAMERA.RADIUS)
     self.rect = pygame.Rect(position[0], position[1],
                             SCREEN.WIDTH + CAMERA.RECT_OFFSET,
                             SCREEN.HEIGHT + CAMERA.RECT_OFFSET)
     self.position = [position[0], position[1]]
     self.x = position[0] - SCREEN.WIDTH / 2
     self.y = position[1] - SCREEN.HEIGHT / 2
     self.player = player  # used for collisions and angle
     self.shaking = False
     self.extra = [0, 0]
     self.shaking_amount = 0
Exemplo n.º 13
0
class Part:
    def __init__(self, x,y, image):
        self.base_image = image
        radius = (image.get_width() + image.get_height()) /4
        self.circle = Circle(x, y, radius)
        self.decay = False
        self.decay_time = STAR.DECAY_TIME
        self.image = self.base_image.copy()
        self.image_position = [x-image.get_width()/2, y-image.get_height() /2]
        
    def update(self, player, delta):
        if self.decay:
            self.decay_time -= delta
            if self.decay_time < 0:
                return True
            size = 1.0*self.decay_time/STAR.DECAY_TIME
            self.image = pygame.transform.rotozoom(self.base_image, 0, size)
            self.image_position = [self.circle.center[0] - self.image.get_width()/2, self.circle.center[1] - self.image.get_height()/2]
            self.image.set_alpha(size*255)
            return False
        else:
            if self.circle.collide_circle(player.circle):
                self.decay = True
                return True
            return False
Exemplo n.º 14
0
class Button:
    def __init__(self, x, y, event, image, mouseover_image=None):
        self.circle = Circle(x, y, 30)
        self.event = event
        self.base_image = image.copy()
        self.was_pressed = False
        if mouseover_image:
            self.mouseover_image = mouseover_image.copy()
        else:
            self.mouseover_image = image.copy()
        self.image_position = [
            x - image.get_width() / 2, y - image.get_height() / 2
        ]

    def update(self):
        x, y = pygame.mouse.get_pos()
        if self.circle.collide_point((x, y)):
            self.image = self.mouseover_image
            pressed = pygame.mouse.get_pressed()
            if pressed[0] and not self.was_pressed:
                self.was_pressed = True
                return self.event
            elif not pressed[0]:
                self.was_pressed = False
        else:
            self.image = self.base_image
Exemplo n.º 15
0
 def __init__(self, type, img_dict, obj, position_or_angle):
     Monster.__init__(self)
     self.type = type
     self.speed = 0
     self.circle = Circle(0, 0, MONSTER.I.RADIUS)
     self.state = MONSTER.I.PREPARING
     self.frame = 0
     self.position = 0 # linear expression of position (px)
     if self.type == MONSTER.TYPE_ANGLE: # count start_position
         self.start = sum(obj.circle.center, multiply(angle_to_vector(position_or_angle), obj.circle.radius + self.circle.radius))
         self.angle = position_or_angle
         self.vector = angle_to_vector(self.angle)
     else:
         self.vector = inverse(perpendicular(normalise(obj.line.vector)))
         shift = multiply(obj.line.vector, -position_or_angle/100.0) # side shift
         self.start = sum(sum(obj.line.start, multiply(self.vector, PLATFORM.BORDER + self.circle.radius)), shift)
         self.angle = vector_to_angle(self.vector)
     self.circle.center = self.start[0], self.start[1]
     self.img_list = []
     for i in img_dict['I']:
         self.img_list.append(pygame.transform.rotozoom(i, -self.angle,1.))
     self.shift_constant = img_dict['I'][0].get_height()/2 - MONSTER.I.RADIUS
     self.image_offset = subtract(multiply(self.vector, self.shift_constant), (self.img_list[0].get_width()/2, self.img_list[0].get_height()/2))
     self.image_position = sum(self.circle.center, self.image_offset)
     self.image = self.img_list[0]
Exemplo n.º 16
0
class Part:
    def __init__(self, x, y, image):
        self.base_image = image
        radius = (image.get_width() + image.get_height()) / 4
        self.circle = Circle(x, y, radius)
        self.decay = False
        self.decay_time = STAR.DECAY_TIME
        self.image = self.base_image.copy()
        self.image_position = [
            x - image.get_width() / 2, y - image.get_height() / 2
        ]

    def update(self, player, delta):
        if self.decay:
            self.decay_time -= delta
            if self.decay_time < 0:
                return True
            size = 1.0 * self.decay_time / STAR.DECAY_TIME
            self.image = pygame.transform.rotozoom(self.base_image, 0, size)
            self.image_position = [
                self.circle.center[0] - self.image.get_width() / 2,
                self.circle.center[1] - self.image.get_height() / 2
            ]
            self.image.set_alpha(size * 255)
            return False
        else:
            if self.circle.collide_circle(player.circle):
                self.decay = True
                return True
            return False
Exemplo n.º 17
0
 def __init__(self, img_dict, bullets, planet, altitude, angle_from, angle_length):
     Monster.__init__(self)
     self.direction = 1 # or -1
     self.pause_length = MONSTER.Q.PAUSE + random.randint(0,500)
     self.infinite = False
     self.img_list = img_dict['Q']
     self.img_dict = img_dict
     self.shift_constant = self.img_list[0].get_height()/2 - MONSTER.Q.RADIUS
     self.went = 0
     self.bullets = bullets
     self.shoot_counter = 0
     self.shoot_time = random.randint(MONSTER.Q.SHOOT_TIME_FROM, MONSTER.Q.SHOOT_TIME_TO)
     center = planet.circle.center
     radius = planet.circle.radius + MONSTER.Q.RADIUS + altitude
     self.angle_from = angle_from
     self.angle = self.angle_from
     self.length = angle_length
     if angle_length == -1 or angle_length == 0:
             self.infinite = True
             if angle_length == 0:
                 self.direction = -1
     self.speed = to_degrees(MONSTER.Q.SPEED/float(radius)) # degrees/second
     self.move_radius = radius
     self.center = center
     self.circle = Circle(center[0], center[1], MONSTER.Q.RADIUS)
     self.extra = 0
     self.update_image(1)
Exemplo n.º 18
0
def handle_event():
    for event in pygame.event.get():
        if event.type == QUIT:
            Game.done = True
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                Game.done = True
            elif event.key == K_LEFT:
                o = Game.seasaw.orient - 0.1
                Game.seasaw.setOrient(o)
            elif event.key == K_RIGHT:
                o = Game.seasaw.orient + 0.1
                Game.seasaw.setOrient(o)
        #elif event.type == MOUSEBUTTONDOWN:

    b1, b2, b3 = pygame.mouse.get_pressed()
    if b1:
        Game.counter += 1
        if Game.counter % 7 == 0:
            mouseX, mouseY = pygame.mouse.get_pos()
            #size =  randint(10,40)
            #b = Body(Circle(size), mouseX, Game.screen_size[1]-mouseY)
            #verts = []
            #vertCount = randint(3, Polygon.MAX_POLY_VERTEX_COUNT)
            #for i in range(vertCount):
            #    verts.append(Vec2(randrange(-40,40), randrange(-40,40)))
            hw = randrange(10, 40)
            hh = randrange(10, 40)

            #b = Body(Polygon(verts=verts), mouseX, Game.screen_size[1]-mouseY)
            b = Body(Polygon(boxHw=hw, boxHh=hh), mouseX, mouseY)
            #b.setOrient(1.5)

            Game.bodies.append(b)
            #print("vertices:",b.shape.vertices)
            #print("normals:", b.shape.normals)
    elif b2:
        Game.counter += 1
        if Game.counter % 7 == 0:
            mouseX, mouseY = pygame.mouse.get_pos()

            verts = []
            vertCount = randint(3, Polygon.MAX_POLY_VERTEX_COUNT)
            for i in range(vertCount):
                verts.append(Vec2(randrange(-40, 40), randrange(-40, 40)))

            b = Body(Polygon(verts=verts), mouseX, mouseY)

            Game.bodies.append(b)
            #print("vertices:",b.shape.vertices)
            #print("normals:", b.shape.normals)

    elif b3:
        Game.counter += 1
        if Game.counter % 7 == 0:
            mouseX, mouseY = pygame.mouse.get_pos()
            size = randint(10, 40)
            b = Body(Circle(size), mouseX, mouseY)
            Game.bodies.append(b)
Exemplo n.º 19
0
 def __init__(self, x,y, image):
     self.base_image = image
     radius = (image.get_width() + image.get_height()) /4
     self.circle = Circle(x, y, radius)
     self.decay = False
     self.decay_time = STAR.DECAY_TIME
     self.image = self.base_image.copy()
     self.image_position = [x-image.get_width()/2, y-image.get_height() /2]
Exemplo n.º 20
0
class Camera:
    def __init__(self, player):
        position = player.circle.center
        self.center = [position[0], position[1]]
        self.offset = [0, 0]
        self.circle = Circle(position[0], position[1], CAMERA.RADIUS)
        self.rect = pygame.Rect(position[0], position[1],
                                SCREEN.WIDTH + CAMERA.RECT_OFFSET,
                                SCREEN.HEIGHT + CAMERA.RECT_OFFSET)
        self.position = [position[0], position[1]]
        self.x = position[0] - SCREEN.WIDTH / 2
        self.y = position[1] - SCREEN.HEIGHT / 2
        self.player = player  # used for collisions and angle
        self.shaking = False
        self.extra = [0, 0]
        self.shaking_amount = 0

    def shake(self, amount=15):
        self.shaking = pygame.time.get_ticks()
        self.shaking_amount = amount

    def shift(self, vector):
        return (int(vector[0] - self.x), int(vector[1] - self.y))

    def update(self):
        av = self.player.angle_vector
        self.offset = [0, 0]  #av[0]*CAMERA.OFFSET, av[1]*CAMERA.OFFSET
        self.circle.center[0] = self.center[0] + self.offset[0]
        self.circle.center[1] = self.center[1] + self.offset[1]
        self.position[0] - SCREEN.WIDTH / 2
        if not self.circle.collide_point(self.player.circle.center):
            diff = subtract(self.player.circle.center, self.circle.center)
            l = pythagory(diff[0], diff[1])
            c = (l - self.circle.radius) / l
            self.center[0] += diff[0] * c
            self.center[1] += diff[1] * c
        diff = self.center[0] - self.position[0], self.center[
            1] - self.position[1]
        if 0:  #diff[0] + diff[1] > 1:
            self.position[0] += diff[0] * CAMERA.DELAY_RATIO
            self.position[1] += diff[1] * CAMERA.DELAY_RATIO
        else:
            self.position[0] = self.center[0]
            self.position[1] = self.center[1]
        #self.position = pl_center
        if self.shaking:
            time = pygame.time.get_ticks() - self.shaking
            if time > CAMERA.SHAKE_DURATION:
                self.shaking = None
                self.extra = [0, 0]
            else:
                ratio = time / float(CAMERA.SHAKE_DURATION)
                c = math.sin(ratio * 15) * (1 - ratio) * self.shaking_amount
                self.extra = av[0] * c, av[1] * c
        self.x = self.position[0] - SCREEN.WIDTH / 2 + self.extra[0]
        self.y = self.position[1] - SCREEN.HEIGHT / 2 + self.extra[1]
        self.rect.topleft = self.x - CAMERA.RECT_OFFSET / 2, self.y - CAMERA.RECT_OFFSET / 2
Exemplo n.º 21
0
 def __init__(self, position, angle, image_dict):
     image = random.choice(image_dict['Qbullets'])
     self.circle = Circle(position[0], position[1], MONSTER.Q.BULLET_RADIUS)
     self.speed = MONSTER.Q.BULLET_SPEED
     self.vector = angle_to_vector(angle)
     self.angle = angle
     self.image = pygame.transform.rotozoom(image, -self.angle,1.)
     self.image_offset = (-self.image.get_width()/2, -self.image.get_height()/2)
     self.image_position = sum(self.circle.center, self.image_offset)
Exemplo n.º 22
0
 def __init__(self, x, y, event, image, mouseover_image = None):
     self.circle = Circle(x,y,30)
     self.event = event
     self.base_image = image.copy()
     self.was_pressed = False
     if mouseover_image:
         self.mouseover_image = mouseover_image.copy()
     else:
         self.mouseover_image = image.copy()
     self.image_position = [x - image.get_width()/2, y - image.get_height()/2]
Exemplo n.º 23
0
 def __init__(self, x, y, image_dict, radius=FLAG.RADIUS):
     self.circle = Circle(x, y, radius)
     self.image_dict = image_dict
     self.image_list = []
     self.image_position = (x - radius, y - radius)
     self.state = 'uncapped'
     self.timer = 0
     for i in range(len(image_dict['flag'])):
         self.image_list.append(image_dict['flag'][i].copy())
     self.image = self.image_list[0]
Exemplo n.º 24
0
 def __init__(self, position, image_dict):
     self.circle = Circle(position[0], position[1], STAR.RADIUS)
     
     self.base_image = image_dict['star']
     self.image = self.base_image
     self.image_position = [position[0] - STAR.RADIUS, position[1] - STAR.RADIUS]
     self.angle = 0
     self.d_angle = STAR.D_ANGLE
     self.d_d_angle = STAR.D_D_ANGLE
     self.decay = False
     self.decay_time = STAR.DECAY_TIME
Exemplo n.º 25
0
class Camera:
    def __init__(self, player):
        position = player.circle.center
        self.center = [position[0], position[1]]
        self.offset = [0,0]
        self.circle = Circle(position[0], position[1], CAMERA.RADIUS)
        self.rect = pygame.Rect(position[0], position[1], SCREEN.WIDTH+CAMERA.RECT_OFFSET, SCREEN.HEIGHT+CAMERA.RECT_OFFSET)
        self.position = [position[0], position[1]]
        self.x = position[0]-SCREEN.WIDTH/2
        self.y = position[1]-SCREEN.HEIGHT/2
        self.player = player # used for collisions and angle
        self.shaking = False
        self.extra = [0,0]
        self.shaking_amount = 0
        
    def shake(self, amount = 15):
        self.shaking = pygame.time.get_ticks()
        self.shaking_amount = amount
        
    def shift(self, vector):
        return (int(vector[0] - self.x), int(vector[1] - self.y))
    
    def update(self):
        av = self.player.angle_vector
        self.offset = [0,0] #av[0]*CAMERA.OFFSET, av[1]*CAMERA.OFFSET
        self.circle.center[0] = self.center[0] + self.offset[0]
        self.circle.center[1] = self.center[1] + self.offset[1]
        self.position[0]-SCREEN.WIDTH/2
        if not self.circle.collide_point(self.player.circle.center):
            diff = subtract(self.player.circle.center, self.circle.center)
            l = pythagory(diff[0], diff[1])
            c = (l - self.circle.radius) / l
            self.center[0] += diff[0]*c
            self.center[1] += diff[1]*c
        diff = self.center[0] - self.position[0], self.center[1] - self.position[1]
        if 0: #diff[0] + diff[1] > 1:
            self.position[0] += diff[0] * CAMERA.DELAY_RATIO
            self.position[1] += diff[1] * CAMERA.DELAY_RATIO
        else:
            self.position[0] = self.center[0]
            self.position[1] = self.center[1]
        #self.position = pl_center
        if self.shaking:
            time = pygame.time.get_ticks() - self.shaking
            if time > CAMERA.SHAKE_DURATION:
                self.shaking = None
                self.extra = [0,0]
            else:
                ratio = time/float(CAMERA.SHAKE_DURATION)
                c = math.sin(ratio * 15)  * (1 - ratio) * self.shaking_amount
                self.extra = av[0] * c, av[1] * c
        self.x = self.position[0]-SCREEN.WIDTH/2 + self.extra[0]
        self.y = self.position[1]-SCREEN.HEIGHT/2 + self.extra[1]
        self.rect.topleft = self.x-CAMERA.RECT_OFFSET/2, self.y-CAMERA.RECT_OFFSET/2
Exemplo n.º 26
0
 def __init__(self, position, angle, image_dict):
     self.circle = Circle(position[0], position[1], MONSTER.C.BULLET_RADIUS)
     self.speed = MONSTER.C.BULLET_SPEED
     self.vector = angle_to_vector(angle)
     self.angle = angle
     self.frame = 0
     self.image_list = []
     for i in image_dict['bullets']:
         self.image_list.append(pygame.transform.rotozoom(i, -self.angle,1.))
     self.image = self.image_list[self.frame]
     self.image_offset = (-self.image.get_width()/2, -self.image.get_height()/2)
     self.image_position = sum(self.circle.center, self.image_offset)
Exemplo n.º 27
0
    def __init__(self, position, planets, platforms, image_dict):
        #super(Player, self).__init__()
        self.image_dict = image_dict['player']

        #        self.old_image = pygame.Surface([PLAYER.SIZE, PLAYER.SIZE])
        #        self.old_image.fill((255, 100, 0))
        #        self.old_image = self.old_image.convert_alpha()
        #        self.basic_old_image = self.old_image.copy()
        #        self.basic_image = self.image.convert_alpha()
        self.shift_constant = self.image_dict['body'][0].get_height(
        ) / 2 - PLAYER.SIZE / 2
        self.x = position[0]
        self.y = position[1]
        self.circle = Circle(self.x, self.y, PLAYER.SIZE / 2)
        self.image_position = [0, 0]
        self.last_center = position
        self.angle = 0  # up
        self.display_angle = self.angle
        self.angle_vector = [0, -1]
        self.display_angle_vector = [0, -1]
        self.gravity_angle = 0
        self.gravity_angle_vector = [0, -1]
        self.speed = [0, 0]  #x,y
        self.acc = [0, 0]
        self.planets = planets
        self.platforms = platforms
        self.on_ground = False
        self.closest_planet = planets[0]
        self.move_frame = 0  # for moving with body
        self.eye_frame = 0  # moving with eyes
        self.movement = False
        self.jump_available = False
        self.ground_speed = 0
        self.was_on_ground = False
        self.move_eyes = False
        self.vacuum_time = 0

        #self.keep_keys = {'l':None, 'r':None, 'j':None}
        self.keep_keys = []
        self.update_image(1)
Exemplo n.º 28
0
 def __init__(self, player):
     position = player.circle.center
     self.center = [position[0], position[1]]
     self.offset = [0,0]
     self.circle = Circle(position[0], position[1], CAMERA.RADIUS)
     self.rect = pygame.Rect(position[0], position[1], SCREEN.WIDTH+CAMERA.RECT_OFFSET, SCREEN.HEIGHT+CAMERA.RECT_OFFSET)
     self.position = [position[0], position[1]]
     self.x = position[0]-SCREEN.WIDTH/2
     self.y = position[1]-SCREEN.HEIGHT/2
     self.player = player # used for collisions and angle
     self.shaking = False
     self.extra = [0,0]
     self.shaking_amount = 0
Exemplo n.º 29
0
class Star:
    def __init__(self, position, image_dict):
        self.circle = Circle(position[0], position[1], STAR.RADIUS)

        self.base_image = image_dict['star']
        self.image = self.base_image
        self.image_position = [
            position[0] - STAR.RADIUS, position[1] - STAR.RADIUS
        ]
        self.angle = 0
        self.d_angle = STAR.D_ANGLE
        self.d_d_angle = STAR.D_D_ANGLE
        self.decay = False
        self.decay_time = STAR.DECAY_TIME

    def update(self, player, delta):
        if self.decay:
            return self.update_decay(player, delta)
        else:
            return self.update_normal(player, delta)

    def update_normal(self, player, delta):
        self.d_angle -= self.angle * self.d_d_angle * delta * 0.001
        self.angle += self.d_angle * delta * 0.001
        self.image = pygame.transform.rotozoom(self.base_image, self.angle,
                                               1.0)
        self.image_position = [
            self.circle.center[0] - self.image.get_width() / 2,
            self.circle.center[1] - self.image.get_height() / 2
        ]
        if self.circle.collide_circle(player.circle):
            self.decay = True
            self.d_d_angle = STAR.DECAY_D_D_ANGLE
            return True
        return False

    def update_decay(self, player, delta):
        self.decay_time -= delta
        if self.decay_time < 0:
            return True
        self.d_angle += self.angle * self.d_d_angle * delta * 0.001
        self.angle += self.d_angle * delta * 0.001
        size = 1.0 * self.decay_time / STAR.DECAY_TIME
        self.image = pygame.transform.rotozoom(self.base_image, self.angle,
                                               size)
        self.image_position = [
            self.circle.center[0] - self.image.get_width() / 2,
            self.circle.center[1] - self.image.get_height() / 2
        ]
        self.image.set_alpha(size * 255)
        return False
Exemplo n.º 30
0
 def __init__(self, x, y, radius, mass, gravity_radius, colour):
     self.circle = Circle(x, y, radius)
     self.colour = colour
     self.mass = mass
     self.gravity_radius = gravity_radius
     count = int(math.ceil(radius / 100.0) * 100)
     self.image = data.load_image(
         str(count) + 'x' + colour + '.png', True, 'planet')
     if radius % 100:
         c = float(radius) / count
         self.image = pygame.transform.smoothscale(self.image, (int(
             self.image.get_width() * c), int(self.image.get_height() * c)))
     self.image_position = x - self.image.get_width(
     ) / 2, y - self.image.get_height() / 2
Exemplo n.º 31
0
def main():
    rectangle = Rectangle(center_x=0.0, center_y=0.0, width=10.0, height=5.0)
    rectangle.draw()
    circle = Circle(x=0.0, y=0.0, radius=7.0)
    circle.draw()

    color = input("Enter the color to fill: 'red' or 'blue': ")
    if color.lower() == 'red':
        color_impl = RedImplementor.get_instance()
    elif color.lower() == 'blue':
        color_impl = BlueImplementor.get_instance()
    else:
        return
    rectangle.set_color_implementor(color_impl)
    rectangle.fill_color()
    circle.set_color_implementor(color_impl)
    circle.fill_color()
Exemplo n.º 32
0
class Star:
    def __init__(self, position, image_dict):
        self.circle = Circle(position[0], position[1], STAR.RADIUS)
        
        self.base_image = image_dict['star']
        self.image = self.base_image
        self.image_position = [position[0] - STAR.RADIUS, position[1] - STAR.RADIUS]
        self.angle = 0
        self.d_angle = STAR.D_ANGLE
        self.d_d_angle = STAR.D_D_ANGLE
        self.decay = False
        self.decay_time = STAR.DECAY_TIME
        
    def update(self, player, delta):
        if self.decay:
            return self.update_decay(player, delta)
        else:
            return self.update_normal(player, delta)
        
    def update_normal(self, player, delta):
        self.d_angle -= self.angle * self.d_d_angle * delta * 0.001
        self.angle += self.d_angle * delta * 0.001
        self.image = pygame.transform.rotozoom(self.base_image, self.angle, 1.0)
        self.image_position = [self.circle.center[0] - self.image.get_width()/2, self.circle.center[1] - self.image.get_height()/2]
        if self.circle.collide_circle(player.circle):
            self.decay = True
            self.d_d_angle = STAR.DECAY_D_D_ANGLE
            return True
        return False
        
    def update_decay(self, player, delta):
        self.decay_time -= delta
        if self.decay_time < 0:
            return True
        self.d_angle += self.angle * self.d_d_angle * delta * 0.001
        self.angle += self.d_angle * delta * 0.001
        size = 1.0*self.decay_time/STAR.DECAY_TIME
        self.image = pygame.transform.rotozoom(self.base_image, self.angle, size)
        self.image_position = [self.circle.center[0] - self.image.get_width()/2, self.circle.center[1] - self.image.get_height()/2]
        self.image.set_alpha(size*255)
        return False
Exemplo n.º 33
0
 def __init__(self, img_dict, type, obj, position_or_angle, force, radius = 30):
     if type == 'a': # count start_position
         start = sum(obj.circle.center, multiply(angle_to_vector(position_or_angle), obj.circle.radius + radius))
         angle = position_or_angle
         vector = angle_to_vector(angle)
     else:
         vector = inverse(perpendicular(normalise(obj.line.vector)))
         shift = multiply(obj.line.vector, -position_or_angle/100.0) # side shift
         start = sum(sum(obj.line.start, multiply(vector, PLATFORM.BORDER + radius + 3)), shift)
         angle = vector_to_angle(vector)
     self.circle = Circle(int(round(start[0])), int(round(start[1])), radius)
     self.force = force
     self.force_vector = multiply(vector, force)
     self.img_list = []
     for i in img_dict['geyser'][obj.colour]:
         self.img_list.append(pygame.transform.rotozoom(i, -angle,1.))
     self.frame = 0
     self.image = self.img_list[self.frame]
     self.frame_speed = BOOSTER.FRAME_SPEED + random.randint(-2,2)
     image_offset = (-self.img_list[0].get_width()/2, -self.img_list[0].get_height()/2)
     self.image_position = sum(self.circle.center, image_offset)
Exemplo n.º 34
0
    def __init__(self, position, planets, platforms, image_dict):
        #super(Player, self).__init__()
        self.image_dict = image_dict['player']

#        self.old_image = pygame.Surface([PLAYER.SIZE, PLAYER.SIZE])
#        self.old_image.fill((255, 100, 0))
#        self.old_image = self.old_image.convert_alpha()
#        self.basic_old_image = self.old_image.copy()
#        self.basic_image = self.image.convert_alpha()
        self.shift_constant = self.image_dict['body'][0].get_height()/2 - PLAYER.SIZE/2
        self.x = position[0]
        self.y = position[1]
        self.circle = Circle(self.x, self.y, PLAYER.SIZE/2)
        self.image_position = [0,0]
        self.last_center = position
        self.angle = 0 # up
        self.display_angle = self.angle
        self.angle_vector = [0,-1]
        self.display_angle_vector = [0,-1]
        self.gravity_angle = 0
        self.gravity_angle_vector = [0,-1]
        self.speed = [0,0] #x,y
        self.acc = [0,0]
        self.planets = planets
        self.platforms = platforms
        self.on_ground = False
        self.closest_planet = planets[0]
        self.move_frame = 0 # for moving with body
        self.eye_frame = 0 # moving with eyes
        self.movement = False
        self.jump_available = False
        self.ground_speed = 0
        self.was_on_ground = False
        self.move_eyes = False
        self.vacuum_time = 0
        
        #self.keep_keys = {'l':None, 'r':None, 'j':None}
        self.keep_keys = []
        self.update_image(1)
Exemplo n.º 35
0
class Button:
    def __init__(self, x, y, event, image, mouseover_image = None):
        self.circle = Circle(x,y,30)
        self.event = event
        self.base_image = image.copy()
        self.was_pressed = False
        if mouseover_image:
            self.mouseover_image = mouseover_image.copy()
        else:
            self.mouseover_image = image.copy()
        self.image_position = [x - image.get_width()/2, y - image.get_height()/2]
            
    def update(self):
        x, y = pygame.mouse.get_pos()
        if self.circle.collide_point((x,y)):
            self.image = self.mouseover_image
            pressed =  pygame.mouse.get_pressed()
            if pressed[0] and not self.was_pressed:
                self.was_pressed = True
                return self.event
            elif not pressed[0]:
                self.was_pressed = False
        else:
            self.image = self.base_image
Exemplo n.º 36
0
def test_area(data):
    c = Circle(data)
    assert c.area == pi * data * data
Exemplo n.º 37
0
def test_name(data):
    c = Circle(data)
    assert c.name == "Circle"
Exemplo n.º 38
0
 def test_nonintersecting_circle_and_rectangle(self):
     """Do non-intersecting circles and rectangles intersect?"""
     circle1 = Circle(4, 4, 2)
     rect1 = Rect(20, 20, 4, 4)
     self.assertFalse(circle1.intersect(rect1) and rect1.intersect(circle1))
Exemplo n.º 39
0
 def test_intersecting_circles(self):
     """Do intersecting circles intersect?"""
     circle1 = Circle(4, 4, 2)
     circle2 = Circle(5, 5, 2)
     self.assertTrue(circle1.intersect(circle2) and circle2.intersect(circle1))
Exemplo n.º 40
0
 def test_nonintersecting_circles(self):
     """Do non-intersecting circles intersect?"""
     circle1 = Circle(4, 4, 2)
     circle2 = Circle(14, 14, 2)
     self.assertFalse(circle1.intersect(circle2) and circle2.intersect(circle1))
Exemplo n.º 41
0
def test_angles(data):
    c = Circle(data)
    assert c.angles == 0
Exemplo n.º 42
0
    def generate_map(self):
        for count in range(C.DUNGEON_MAX_ROOMS):
            num_rooms = len(self.rooms)
            # 1/5 of rooms as circles
            if libtcod.random_get_int(0, 0, 5) == 4:
                r = libtcod.random_get_int(0, C.DUNGEON_ROOM_MIN_SIZE, C.DUNGEON_ROOM_MAX_SIZE / 2)
                x = libtcod.random_get_int(0, r, self.width - r - 2)
                y = libtcod.random_get_int(0, r, self.height - r - 2)
                new_room = Circle(x, y, r)
            else:
                w = libtcod.random_get_int(0, C.DUNGEON_ROOM_MIN_SIZE, C.DUNGEON_ROOM_MAX_SIZE)
                h = libtcod.random_get_int(0, C.DUNGEON_ROOM_MIN_SIZE, C.DUNGEON_ROOM_MAX_SIZE)
                x = libtcod.random_get_int(0, 1, self.width - w - 2)
                y = libtcod.random_get_int(0, 1, self.height - h - 2)
                new_room = Rect(x, y, w, h)

            # run through the other rooms and see if they intersect with this one
            failed = False
            for other_room in self.rooms:
                if new_room.intersect(other_room):
                    failed = True
                    break

            if not failed:
                # this means there are no intersections, so this room is valid
                # "paint" it to the map's tiles
                self.create_room(new_room)

                # center coordinates of new room, will be useful later
                (new_x, new_y) = new_room.center()

                # Display Room names for debugging
                if C.DEBUG:
                    debug_sprite_config = dict(
                        char=chr(65+num_rooms),
                        color=libtcod.white,
                        description="A debugging character."
                    )
                    room_no = Sprite(game.console, debug_sprite_config, (new_x, new_y), False)
                    game.sprites.insert(0, room_no)

                if num_rooms == 0:
                    # this is the first room, where the player starts at
                    self.starting_coords['x'] = new_x
                    self.starting_coords['y'] = new_y
                else:
                    # all rooms after the first:
                    # connect it to the previous room with a tunnel

                    # center coordinates of previous room
                    (prev_x, prev_y) = self.rooms[num_rooms-1].center()

                    # draw a coin (random number that is either 0 or 1)
                    if libtcod.random_get_int(0, 0, 1) == 1:
                        # first move horizontally, then vertically
                        self.create_h_tunnel(prev_x, new_x, prev_y)
                        self.create_v_tunnel(prev_y, new_y, new_x)
                    else:
                        # first move vertically, then horizontally
                        self.create_v_tunnel(prev_y, new_y, prev_x)
                        self.create_h_tunnel(prev_x, new_x, new_y)

                # finally, append the new room to the list
                self.rooms.append(new_room)
                num_rooms += 1
Exemplo n.º 43
0
def test_perimeter(data):
    c = Circle(data)
    assert c.perimeter == 2 * pi * data
Exemplo n.º 44
0
class Player:#(MovingObject):
    def __init__(self, position, planets, platforms, image_dict):
        #super(Player, self).__init__()
        self.image_dict = image_dict['player']

#        self.old_image = pygame.Surface([PLAYER.SIZE, PLAYER.SIZE])
#        self.old_image.fill((255, 100, 0))
#        self.old_image = self.old_image.convert_alpha()
#        self.basic_old_image = self.old_image.copy()
#        self.basic_image = self.image.convert_alpha()
        self.shift_constant = self.image_dict['body'][0].get_height()/2 - PLAYER.SIZE/2
        self.x = position[0]
        self.y = position[1]
        self.circle = Circle(self.x, self.y, PLAYER.SIZE/2)
        self.image_position = [0,0]
        self.last_center = position
        self.angle = 0 # up
        self.display_angle = self.angle
        self.angle_vector = [0,-1]
        self.display_angle_vector = [0,-1]
        self.gravity_angle = 0
        self.gravity_angle_vector = [0,-1]
        self.speed = [0,0] #x,y
        self.acc = [0,0]
        self.planets = planets
        self.platforms = platforms
        self.on_ground = False
        self.closest_planet = planets[0]
        self.move_frame = 0 # for moving with body
        self.eye_frame = 0 # moving with eyes
        self.movement = False
        self.jump_available = False
        self.ground_speed = 0
        self.was_on_ground = False
        self.move_eyes = False
        self.vacuum_time = 0
        
        #self.keep_keys = {'l':None, 'r':None, 'j':None}
        self.keep_keys = []
        self.update_image(1)
        
    def set_camera(self, cam):
        self.cam = cam    
    
    def respawn(self, position):
        self.circle.set_center(position[0], position[1])
        self.on_ground = False
        self.speed = [0,0]
        self.acc = [0,0]
        self.vacuum_time = 0
        
    def set_angle(self, angle):
        self.angle = angle
        self.angle_vector = angle_to_vector(angle)
        
    def set_angle_vector(self, vector):
        if vector != [0,0]:
            self.angle_vector = normalise(vector)
            self.angle = vector_to_angle(self.angle_vector)

    def set_gravity_angle(self, angle):
        self.gravity_angle = angle
        self.gravity_angle_vector = angle_to_vector(angle)
        
    def set_gravity_angle_vector(self, vector):
        if vector != [0,0]:
            self.gravity_angle_vector = normalise(vector)
            self.gravity_angle = vector_to_angle(vector)  
        
    def update(self, keys, delta, external):
        # move (use keys against PLAYER.CONTROLS)
        return self.move(keys, delta, external)

    def update_image(self, delta):
        diff = self.display_angle - self.angle
        while abs(diff) > 180:
            if diff > 0:
                diff -= 360
            else:
                diff += 360
        self.display_angle -= diff * PLAYER.TURN_RATIO * delta * 0.001
        if abs(diff) > delta * PLAYER.TURN_SPEED * 0.001:
            if diff > 0:
                self.display_angle -= delta * PLAYER.TURN_SPEED * 0.001
            else:
                self.display_angle += delta * PLAYER.TURN_SPEED * 0.001
        else:
            self.display_angle = self.angle
        movement = self.on_ground and self.movement
        if not movement and self.move_frame:
            c = 1
            if self.move_frame < PLAYER.MOVE_FRAMES/2:
                c = -1
            self.move_frame += delta * 0.001 * PLAYER.MOVE_FRAME_SPEED * c
            if self.move_frame < 0 or self.move_frame > PLAYER.MOVE_FRAMES:
                self.move_frame = 0
        if movement:
            self.move_frame += delta * 0.001 * PLAYER.MOVE_FRAME_SPEED
            if self.move_frame > PLAYER.MOVE_FRAMES:
                self.move_frame %= PLAYER.MOVE_FRAMES
        
        eye_frame = 0
        if self.move_eyes:
            self.eye_frame += delta * 0.001 * PLAYER.EYE_FRAME_SPEED
            if self.eye_frame > PLAYER.EYE_FRAMES:
                self.eye_frame = 0
                self.move_eyes = False
            eye_frame = int(round(self.eye_frame))
            if eye_frame >= PLAYER.EYE_FRAMES:
                eye_frame = eye_frame % PLAYER.EYE_FRAMES

        move_frame = int(round(self.move_frame))
        if move_frame >= PLAYER.MOVE_FRAMES:
            move_frame = move_frame % PLAYER.MOVE_FRAMES
        
        image = self.image_dict['eyes'][eye_frame].copy()
        image.blit(self.image_dict['body'][move_frame], (0,0))
        
        if diff:
            self.display_angle_vector = angle_to_vector(self.display_angle)
        self.image = pygame.transform.rotozoom(image, -self.display_angle,1.)
        self.image_position = subtract(sum(self.circle.center, multiply(self.display_angle_vector, self.shift_constant)), (self.image.get_width()/2, self.image.get_height()/2))
        
    def apply_keys(self, left, right, jump, delta):
        if self.on_ground and not self.was_on_ground:
            self.ground_speed = -tangent_size(self.speed, perpendicular(self.angle_vector))
            normal_speed = pythagory(self.speed[0], self.speed[1])
            if normal_speed > CAMERA.SHAKE_THRESHOLD:
                self.cam.shake((normal_speed - CAMERA.SHAKE_THRESHOLD)*CAMERA.SHAKE_RATIO)
            else:
                self.move_eyes = True
        if self.on_ground:
            self.was_on_ground = True
            self.movement = right or left
            if right:
                self.ground_speed += PLAYER.GROUND_ACCELERATION*delta*0.001
            if left:
                self.ground_speed -= PLAYER.GROUND_ACCELERATION*delta*0.001
            if self.ground_speed > PLAYER.MAX_GROUND_SPEED:
                self.ground_speed = PLAYER.MAX_GROUND_SPEED
            if self.ground_speed < -PLAYER.MAX_GROUND_SPEED:
                self.ground_speed = -PLAYER.MAX_GROUND_SPEED 
            if not right and not left:
                if self.ground_speed > 0:
                    self.ground_speed -= PLAYER.BRAKE_ACC*delta*0.001
                    if self.ground_speed < 0:
                        self.ground_speed = 0
                else:
                    self.ground_speed += PLAYER.BRAKE_ACC*delta*0.001
                    if self.ground_speed > 0:
                        self.ground_speed = 0
            self.speed[0] = (self.ground_speed) * -self.angle_vector[1]
            self.speed[1] = (self.ground_speed) * self.angle_vector[0]
            if jump and self.jump_available:
                self.jump_available = False
                self.speed[0] += PLAYER.JUMP_ACC * (self.angle_vector[0] + self.gravity_angle_vector[0]) /2
                self.speed[1] += PLAYER.JUMP_ACC * (self.angle_vector[1] + self.gravity_angle_vector[1]) /2
        else:
            self.was_on_ground = False
            if pythagory(self.speed[0], self.speed[1]) > PLAYER.MAX_AIR_SPEED:
                limiter = True
            else:
                limiter = False
            pom = 0
            if self.speed != [0,0]:
                pom = tangent_size([-self.gravity_angle_vector[1], self.gravity_angle_vector[0]], self.speed)
            if right and (not limiter or pom < 0):
                self.acc[0] += PLAYER.AIR_ACCELERATION * -self.gravity_angle_vector[1]
                self.acc[1] += PLAYER.AIR_ACCELERATION * self.gravity_angle_vector[0]
            if left and (not limiter or pom > 0):
                self.acc[0] += PLAYER.AIR_ACCELERATION * self.gravity_angle_vector[1]
                self.acc[1] += PLAYER.AIR_ACCELERATION * -self.gravity_angle_vector[0]
        if not jump:
            self.jump_available = True               
        
    
    def move(self, keys, delta, external):
        # calculate gravity
        strongest = None
        maximum = -1
        self.acc = [0.0, 0.0]
        for p in self.planets:
            gx, gy = gravity_circle_circle(self.circle, p.circle, p.mass, p.gravity_radius)
            if not self.on_ground:
                self.acc[0] += gx
                self.acc[1] += gy
            x,y = subtract(self.circle.center, p.circle.center)
            priority = pythagory(gx, gy) / pythagory(x,y) 
            if priority > maximum:
                maximum = priority
                self.closest_planet = p
        # check keys and add player acceleration
        left, right, jump = self.check_keys(keys)
        # determine speed based on given commands
        self.apply_keys(left, right, jump, delta)
        if self.on_ground:
            gx, gy = gravity_circle_circle(self.circle, self.closest_planet.circle, self.closest_planet.mass, self.closest_planet.gravity_radius)
            self.acc[0] += gx
            self.acc[1] += gy
        if self.acc == [0,0]:
            self.vacuum_time += delta
            if self.vacuum_time > PLAYER.VACUUM_TIME:
                return 'dead'
        self.speed[0] += self.acc[0]*delta*0.001
        self.speed[1] += self.acc[1]*delta*0.001 
        if external != [0,0]:
            diff = subtract(external, self.speed)
            self.speed = sum(self.speed, multiply(diff, PLAYER.BOOST_RATIO))       
        #move circle
        self.circle.move((self.speed[0]*delta*0.001, self.speed[1]*delta*0.001))
        
        if self.closest_planet:
            vector = gravity_circle_circle(self.circle, self.closest_planet.circle)
            self.set_gravity_angle_vector(inverse(vector))
            
        self.on_ground = False
        # checkout collision with surfaces
        self.colliding_planets = []
        for p in self.planets:
            if self.circle.collide_circle(p.circle):
                self.colliding_planets.append(p)

        self.colliding_platforms = []
        self.above_platform = None
        min_distance = 0
        for p in self.platforms:
            if self.circle.collide_line(p.line, PLATFORM.BORDER):
                self.colliding_platforms.append(p)
            is_above = collide_line_line(self.circle.center, self.closest_planet.circle.center, p.line.start, p.line.end)
            if is_above and self.above_platform == None:
                point = collide_line_line_extended(self.circle.center, self.closest_planet.circle.center, p.line.start, p.line.end)
                min_distance = pythagory(self.circle.center[0] - point[0], self.circle.center[1] - point[1])
                self.above_platform = p
            elif is_above:
                point = collide_line_line_extended(self.circle.center, self.closest_planet.circle.center, p.line.start, p.line.end)
                distance = pythagory(self.circle.center[0] - point[0], self.circle.center[1] - point[1])
                if min_distance > distance:
                    self.above_platform = p
                    min_distance = distance
        
        # workout angle
        
        if self.above_platform != None:
            vector = perpendicular(self.above_platform.line.vector)
            angle = vector_to_angle(vector)
            if 90 < abs(angle - self.gravity_angle) < 270:
                vector = inverse(vector)
            self.set_angle_vector(vector)
        else:
            self.set_angle(self.gravity_angle)
        
        self.handle_collision()

        self.update_image(delta)
        self.last_center = multiply(self.circle.center,1)
        
    def handle_collision(self):
        if len(self.colliding_platforms) == 1:
            self.handle_single_platform_collision(self.colliding_platforms[0])
        elif len(self.colliding_planets) == 1:
            planet = self.colliding_planets[0]
            vector = self.circle.collide_circle_extended(planet.circle)
            self.circle.move(vector)
            self.set_angle_vector(vector)
            self.on_ground = True           
        elif len(self.colliding_platforms) > 1:
            self.handle_multiple_collisions()
            
    def handle_single_platform_collision(self, platform):
        vector = self.circle.collide_line_extended(platform.line, PLATFORM.BORDER)
        if vector == [0,0]:
            return
        self.circle.move(vector)
        angle = vector_to_angle(vector)
        if PLATFORM.MIN_ANGLE < abs(angle - self.gravity_angle) < PLATFORM.MAX_ANGLE:
            self.on_ground = False
            if 90 < abs(angle - self.gravity_angle) < 270:
                x, y = tangent(vector, platform.line.vector)
                self.speed = [x,y]
        else:
            self.on_ground = True
        self.set_angle_vector(vector)
        self.ground_speed = -tangent_size(self.speed, perpendicular(self.angle_vector))
            
    def handle_multiple_collisions(self):
        platforms = []
        if len(self.colliding_platforms) == 0:
            return
        for platform in self.colliding_platforms:
            distance = 1
            if not self.circle.collide_line(platform.line, PLATFORM.BORDER):
                return
            vector = self.circle.collide_line_extended(platform.line, PLATFORM.BORDER)
            perpendicular_v = perpendicular(vector)
            if tangent_size(perpendicular_v, self.speed) < 0:
                perpendicular_v = inverse(perpendicular_v)
            pom = sum(self.circle.center, vector)
            point = collide_line_line_extended(self.last_center, self.circle.center, pom, subtract(pom, perpendicular_v))
            if point == self.last_center:
                distance = 0
            elif self.circle.center != self.last_center:
                distance = pythagory(point[0] - self.last_center[0], point[1] - self.last_center[1])/pythagory(self.circle.center[0] - self.last_center[0], self.circle.center[1] - self.last_center[1])
            platforms.append([platform, distance, point, perpendicular_v])
        platforms = sorted(platforms, key=lambda student: student[1])
        min_ground_speed = None
        for platform in platforms:
            self.handle_single_platform_collision(platform[0])
            if min_ground_speed == None:
                min_ground_speed = self.ground_speed
            elif abs(min_ground_speed) > abs(self.ground_speed):
                min_ground_speed = self.ground_speed
        self.ground_speed = min_ground_speed
            
    def check_keys(self, keys): # u,l,d,r
        d = {'u': keys[PLAYER.CONTROLS[0]],
             'l': keys[PLAYER.CONTROLS[1]],
             'd': keys[PLAYER.CONTROLS[2]],
             'r': keys[PLAYER.CONTROLS[3]]}
        left = right = jump = False
        jump_affected = False
        
        if self.keep_keys:
            if d[self.keep_keys[0]]:
                if self.keep_keys[2] == 'l':
                    left = True
                else:
                    right = True
                d[self.keep_keys[0]] = False
                
                # jump
                if d[self.keep_keys[1]]:
                    jump = True
                    d[self.keep_keys[1]] = False
            else:
                self.keep_keys = None

        if 315 <= self.angle or self.angle < 45 or 1:
            if d['u']:
                jump = True
            if d['l']:
                left = True
                self.keep_keys = ['l', 'u', 'l'] # the key to hold, jump key to remember and use, direction of movement
            if d['r']:
                right = True
                self.keep_keys = ['r', 'u', 'r']
            if d['d'] and not (right or left or jump):
                if 315 <= self.angle:
                    left = True
                    self.keep_keys = ['d', 'l', 'l']
                else:
                    right = True
                    self.keep_keys = ['d', 'r', 'r']
                
        elif 45 <= self.angle < 135:
            if d['r']:
                jump = True
            if d['u']:
                left = True
                self.keep_keys = ['u', 'r', 'l']
            if d['d']:
                right = True
                self.keep_keys = ['d', 'r', 'r']
            if d['l'] and not (right or left or jump):
                if self.angle < 90:
                    left = True
                    self.keep_keys = ['l', 'u', 'l']
                else:
                    right = True
                    self.keep_keys = ['l', 'd', 'r']
        elif 135 <= self.angle < 225:
            if d['d']:
                jump = True
            if d['r']:
                left = True
                self.keep_keys = ['r', 'd', 'l']
            if d['l']:
                right = True
                self.keep_keys = ['l', 'd', 'r']
            if d['u'] and not (right or left or jump):
                if self.angle < 180:
                    left = True
                    self.keep_keys = ['u', 'r', 'l']
                else:
                    right = True
                    self.keep_keys = ['u', 'l', 'r']
        elif 225 <= self.angle < 315:
            if d['l']:
                jump = True
            if d['d']:
                left = True
                self.keep_keys = ['d', 'l', 'l']
            if d['u']:
                right = True
                self.keep_keys = ['u', 'l', 'r']
            if d['r'] and not (right or left or jump):
                if self.angle < 270:
                    left = True
                    self.keep_keys = ['r', 'd', 'l']
                else:
                    right = True
                    self.keep_keys = ['r', 'u', 'r']
        return left, right, jump
Exemplo n.º 45
0
 def setUp(self):
     self.test_circle = Circle('Circle', 'Test Circle', -2)
Exemplo n.º 46
0
 def test_intersecting_circle_and_rectangle(self):
     """Do intersecting circles and rectangles intersect?"""
     circle1 = Circle(4, 4, 2)
     rect1 = Rect(0, 0, 4, 4)
     self.assertTrue(circle1.intersect(rect1) and rect1.intersect(circle1))