Example #1
0
 def __init__(self, surface, pos, vel, gravity, container, color='red'):
     """
     surface : Surface :  The Surface to draw on.
     pos : (x,y) : tuple\list x,y position at time of creation.
     vel : (x,y) : tuple\list x,y velocity at time of creation.
     gravity : (x,y) : tuple\list x,y gravity effecting the particle.
     container : list : The passed in list that contains all the particles to draw.
         Used so particles can be deleted.
     color : str : String color value, default 'red'.
     """
     self.surface = surface
     self.pos = Vec2d(pos)
     vel = [vel[0]+random.uniform(-3,3), vel[1]+random.uniform(-3,3)]
     self.vel = Vec2d(vel)
     # Clamp any huge velocities:
     if self.vel.length > 10:
         self.vel.length = 10
         
     self.gravity = Vec2d(gravity)
     self.container = container
     self.color = Color(color)
     
     self.radius = random.randint(4,16)
     self.connectDist = self.radius * 4
     self.surfSize = surface.get_size()
     self.drag = .9
     # This is updated each frame with a list of all other particles connected
     # to, which helps to define if lines should be drawn.
     self.connections = []
Example #2
0
    def updatePosition(self, add_to_trail=False):
        if USE_WEBCAM:
            self.position = Vec2d(webcam.findPlayer(self))

        self.surface_position = (int(self.position.x - PLAYER_RADIUS),
                                 int(self.position.y - PLAYER_RADIUS))
        self.surface.fill(CLEAR_COLOR)
        pygame.draw.circle(self.surface, GAME_BACKGROUNG_COLOR,
                           (PLAYER_RADIUS, PLAYER_RADIUS), PLAYER_RADIUS)
        circle_color = self.temp_color if self.temp_color else self.color.value
        pygame.draw.circle(self.surface, circle_color,
                           (PLAYER_RADIUS, PLAYER_RADIUS), PLAYER_RADIUS,
                           PLAYER_BORDER_WIDTH)

        distance_from_last_point = 0
        if self.last_position is not None:
            delta = self.position - self.last_position
            distance_from_last_point = delta.get_length()
            if self.creating_hole:
                self.hole_length_remaining -= distance_from_last_point
                if self.hole_length_remaining <= 0:
                    self.creating_hole = False
                    self.resetTimeToNextHole()
                    distance_from_last_point = 0

        if add_to_trail:
            self.trail.addPoint(Vec2d(self.position), self.creating_hole,
                                distance_from_last_point)

        self.last_position = Vec2d(self.position)
Example #3
0
 def render(self):
     # for smooth rendering
     # draw ships
     for ship in self.ships:
         ship.sprite.position = ship.position * 8 + Vec2d(4, 4)
         ship.sprite.draw()
     gl.glColor3f(1, 1, 0)
     # draw explosions TODO: Animate!
     for explosion in self.explosions:
         gl.glPointSize(8.0)
         pyglet.graphics.draw(
             1, pyglet.gl.GL_POINTS,
             ('v2i', (explosion.x * 8 + 4, explosion.y * 8 + 4))
         )
     laser_points = []
     # draw laser lines
     for shot in self.shots:
         startpos = shot.owner.position * 8 + Vec2d(4, 4)
         laser_points.append(startpos.x)
         laser_points.append(startpos.y)
         laser_points.append(shot.position.x * 8 + 4)
         laser_points.append(shot.position.y * 8 + 4)
     gl.glColor3f(1, 0, 0)
     pyglet.graphics.draw(
         len(self.shots) * 2, pyglet.gl.GL_LINES,
         ('v2i', laser_points)
     )
    def __init__(self, lvlMgr, type=0, pos=Vec2d(0, 0)):
        self.lvlMgr = lvlMgr
        self.entType = 1  #This is a projectile
        self.type = type  #0, 1, 2 = Rocket, Grenade, Homing
        self.pos = pos
        self.width = 16  #TEMP values based off type of projectile
        self.height = 19  #TEMP
        self.originPoint = Vec2d(self.width / 2, self.height)
        self.lifespan = 200  #Time until it just times out
        self.toRemove = False

        #Physics handler component
        self.physComp = PhysComp(self, self.width, self.height)
        #Rendering handler component
        if self.type == 0:
            self.drawComp = DrawComp(self, "projectile1.png", self.width,
                                     self.height)
        elif self.type == 1:
            self.drawComp = DrawComp(self, "projectile2.png", self.width,
                                     self.height)
        elif self.type == 2:
            self.drawComp = DrawComp(self, "projectile3.png", self.width,
                                     self.height)

        #Spawn the projectile
        self.physComp.setPos(self.pos)
    def tick(self, time, global_robots):

        movement = Vec2d(0, 0)

        if self.target is not None:
            self.speed = 1
            if self.position.get_distance(self.target) < 10:
                self.seek_target = False
                self.direction = Vec2d(0, 0)
                self.target = None
            else:
                self.seek_target = True
                self.direction = (self.target - self.position).normalized()

        robots = filter(lambda x: id(x) != id(self), global_robots)
        self.local_robots = map(self.transform_to_local, robots)

        collisions = [
            i for i in self.local_robots
            if -20 < i.position.x < 20 and 0 < i.position.y < 120
        ]

        if collisions:
            self.collision = True
            self.speed = 0.5
            closest = min(collisions, key=lambda x: x.position.length)
            if closest.position.x > 0:
                self.direction.rotate(20)
            else:
                self.direction.rotate(-20)
        else:
            self.collision = False

        movement += self.direction
        self.position += time * (movement * self.speed) * 0.1
Example #6
0
def draw_explosion(obj, _, t):
    if obj['id'] not in explosions:
        x = obj['x']
        y = obj['y']
        dx = obj['dx']
        dy = obj['dy']

        lines = []

        for line in xrange(0, 5 + random.randint(0, 5)):
            lines.append((
                Vec2d(x, y),
                Vec2d(dx + random.random() - 0.5, dy + random.random() - 0.5) *
                0.7,
                2 * pi * random.random(),  # rotation
                (random.random() - 0.5) * 0.1,  # rotation speed
                random.random() * 6,
                -random.random() * 6,
                t  # start time
            ))

        explosions[obj['id']] = {
            'start': t,
            'lines': lines,
        }

    for startpos, vel, r, dr, a, b, t0 in explosions[obj['id']]['lines']:
        dt = t - t0
        line = Vec2d(cos(r + dr * dt), sin(r + dr * dt))

        pos = startpos + vel * dt

        for piece in a, b:
            pygame.draw.line(screen, (194, 205, 0), screen_coord(pos),
                             screen_coord(pos + piece * line))
Example #7
0
    def action(self):
        self.move_counter += 1

        if self.next_target:
            # intensify forward firepower
            possible = [
                self.next_target + Vec2d(1, 0),
                self.next_target + Vec2d(-1, 0),
                self.next_target + Vec2d(0, 1),
                self.next_target + Vec2d(0, -1)
            ]
            # TODO: expose in_range for later use
            possible = [p for p in possible if self.in_range(p)]
            self.next_target = None  # we always want to check if we killed
            if not possible:
                return random.choice(list(Move))
            return Shot(random.choice(possible), self)

        # No targets? Scan for them. And spin in circles.
        if self.move_counter < self.diameter:
            return Scan.SCAN
        else:
            self.move_counter = 0
            d = self.movement_queue[0]
            self.movement_queue.remove(d)
            self.movement_queue.append(d)
            return d
 def __init__(self, owner, width, height):
     self.owner = owner
     self.pos = Vec2d(0,0)
     self.vel = Vec2d(0,0)
     self.force = Vec2d(0,0)
     self.width = width
     self.height = height
Example #9
0
def testSub():
    a = Vec2d(x=3, y=3)
    b = Vec2d(x=1, y=1)
    c = a - b
    assert c.x == 2
    assert c.y == 2
    assert isinstance(c, Vec2d)
    def __init__(self, pos, mass, scale):
        # Call the parent class (Sprite) constructor
        super().__init__()

        # Position vector
        self.pos = pos

        # Velocity vector, y-value is set to 150
        self.vel = Vec2d(0, 150)

        # Object mass
        self.mass = mass

        # Momentum vector
        self.mom = self.vel * self.mass

        # Force vector, y-value is a random integer from 50 to 500
        self.force = Vec2d(0, random.randrange(50, 250))

        # Image scale
        self.scale = scale

        # Image filename
        self.filename = ""

        # Load the image of the asparagus and draw the image
        self.set_image()

        # Fetch the rectangle object that has the dimensions of the image
        self.rect = self.image.get_rect()
    def __init__(self, pos, mass, scale):
        # Call the parent class (Sprite) constructor
        super().__init__()

        # Position vector
        self.pos = pos

        # Velocity vector, y-value is set to 100
        self.vel = Vec2d(0, 100)

        # Object mass
        self.mass = mass

        # Momentum vector
        self.mom = self.vel * self.mass

        # No force, asparagi moves with constant velocity
        self.force = Vec2d(0, 0)

        # Image scale
        self.scale = scale

        # Image filename
        self.filename = ""

        # Load the image of the asparagus and draw the image
        self.set_image()

        # Fetch the rectangle object that has the dimensions of the image
        self.rect = self.image.get_rect()
Example #12
0
    def integrator():
        pos = pos_at_t0
        ang = ang_at_t0
        vel = vel_at_t0

        if dt > 1000:
            print 'Bailing out from integration -- too far ahead'
            return pos, ang

        for i in xrange(dt):
            if engine_on:
                vel += 0.001 * Vec2d(cos(ang), sin(ang))

            damp = 0.999
            vel *= damp

            pos += vel
            ang += dang

        def bind(value, length):
            return (length * 1.5 + value % length) % length - length / 2

        bound_pos = Vec2d(bind(pos[0], game.board_width),
                          bind(pos[1], game.board_height))

        return bound_pos, ang
Example #13
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     shots = []
     for i in range(30):
         x, y = Vec2d(0, 5).rotated(12 * i)
         shots.append(Vec2d(int(x), int(y)))
     self.shots = deque(shots)
     self.shots.rotate(random.randint(-12, 12))
    def reset_pos(self, screen_width):
        # Reset sprite's position
        self.rect.y = random.randrange(-300, -40)
        self.rect.x = random.randrange(0, screen_width - 10)

        # Reset the object's position and momentum
        self.pos = Vec2d(self.rect.x, self.rect.y)
        self.vel = Vec2d(0, random.randrange(150, 200))
        self.mom = Vec2d(0, 0)
Example #15
0
 def line(self, color, start, end, thickness):
     if thickness != 1:
         return pygame.draw.line(self.screen, color,
                                 start + Vec2d(self.offset, 0),
                                 end + Vec2d(self.offset, 0), thickness)
     else:
         return pygame.draw.aaline(self.screen, color,
                                   start + Vec2d(self.offset, 0),
                                   end + Vec2D(self.offset, 0))
def make_polygon(radius, n, angle=0, factor=1, axis=Vec2d(1,0)):
    axis = axis.normalized()
    vec = Vec2d(0, -radius).rotated(180/n+angle)
    p = []
    for i in range(n):
        v = vec.rotated(360*i/n)
        v += v.dot(axis)*(factor-1)*axis
        p.append(v)
    return p
Example #17
0
def _velocity_and_direction(ship):
    if ship.direction == Move.UP:
        return Vec2d(0, 1), 0
    elif ship.direction == Move.DOWN:
        return Vec2d(0, -1), 180
    elif ship.direction == Move.RIGHT:
        return Vec2d(1, 0), 90
    elif ship.direction == Move.LEFT:
        return Vec2d(-1, 0), -90
Example #18
0
 def setEndpoints(self):
     x1 = self.center.x + self.length * math.cos(self.angle)
     x2 = self.center.x - self.length * math.cos(self.angle)
     y1 = self.center.y + self.length * math.sin(self.angle)
     y2 = self.center.y - self.length * math.sin(self.angle)
     self.end1 = Vec2d(x1, y1)
     self.end2 = Vec2d(x2, y2)
     dx = x2 - x1
     dy = y2 - y1
     self.normal = Vec2d(dy, -dx).normalized()
Example #19
0
 def __init__(self, center, angle, length, thickness):
     Matter.__init__(self, 2000000, center, Vec2d(0, 0))
     self.angle = math.radians(angle)
     self.thickness = thickness
     self.length = length
     self.color = WHITE
     self.end1 = Vec2d(0, 0)
     self.end2 = Vec2d(0, 0)
     self.normal = Vec2d(0, 0)
     self.setEndpoints()
def calculateCOMVel(planets):
    if (len(planets) == 0):
        return Vec2d(0, 0)
    else:
        totalMass = 0
        massVel = Vec2d(0, 0)
        for planet in planets:
            totalMass += planet.mass
            massVel += planet.mass * planet.vel
        return massVel / totalMass
def calculateCOM(planets):
    if (len(planets) == 0):
        return Vec2d(0, 0)
    else:
        totalMass = 0
        massPos = Vec2d(0, 0)
        for planet in planets:
            totalMass += planet.mass
            massPos += planet.mass * planet.center
        return massPos / totalMass
Example #22
0
 def _randomize_players_positions_and_direction_vectors(self):
     for player in self.players:
         MARGIN_FACTOR = 5
         WIDTH_MARGIN = GAME_WIDTH / MARGIN_FACTOR
         HIGHT_MARGIN = GAME_HIGHT / MARGIN_FACTOR
         x = random.randrange(WIDTH_MARGIN, GAME_WIDTH - WIDTH_MARGIN)
         y = random.randrange(HIGHT_MARGIN, GAME_HIGHT - HIGHT_MARGIN)
         direction_vector = Vec2d(1, 0)
         direction_vector.rotate(random.randrange(0, 360))
         player._set_position_and_direction_vector(Vec2d(x, y), direction_vector)
Example #23
0
	def __init__(self, scr, net):
		self.scr = scr
		self.sizex, self.sizey = 10, 10
		self.map = [[0 for ii in range(4)] for i in range(4)]
		self.players = [ (Vec2d(10, 10)),
						 (Vec2d(15, 15)),
						 (Vec2d(5,  5)),
						 (Vec2d(120, 120)) ]
		self.net = net
		self.net.subscribeChanges(self.netChanges)
Example #24
0
 def __init__(self, pos, normal, color, mass=1e99, vel=Vec2d(0, 0)):
     self.pos = pos.copy()
     self.normal = normal.normalized()  # makes a copy automatically
     self.pos = pos.copy()
     self.vel = vel.copy()
     self.mass = mass
     self.mom = self.vel * self.mass
     self.color = color
     self.force = Vec2d(0, 0)
     self.type = "wall"
Example #25
0
def testRotate():
    a = Vec2d(x=1, y=0)
    b = a.rotate(radians(90))
    assert areVecEqual(b, Vec2d(0, -1))
    c = b.rotate(radians(90))
    assert areVecEqual(c, Vec2d(x=-1, y=0))
    d = c.rotate(radians(90))
    assert areVecEqual(d, Vec2d(x=0, y=1))
    e = d.rotate(radians(90))
    assert areVecEqual(a, e)
Example #26
0
    def __init__(self, game):
        self.game = game

        self.arrow_positions = (
            (Vec2d(149, 224), self.handleNewGame),
            (Vec2d(154, 125), self.handleContinue),
        )
        self.arrow_position = 0
        self.title_pos = Vec2d(46, 364)
        self.lem_pos = Vec2d(506, 0)
Example #27
0
 def fling(self, target):
     if target is None:
         target = Vec2d(self.fling_object.location)
     else:
         target = Vec2d(target)
     force = (target - self.fling_object.location)/config.object.force_division_factor
     if force.length >= config.object.max_force:
         force.length = config.object.max_force
     self.fling_object.fling(force)
     music.play_whip()
     self.fling_object = None
Example #28
0
 def tallJump(self):
     if self.amountMoved < self.moveLimit:
         if not self.falling:
             self.falling = True
             self.physComp.setVel(Vec2d(0,0))
             if self.direction == Globals.LEFT:
                 self.physComp.addForce(Vec2d(-2000,-12000))
                 self.amountMoved += 1
             else:
                 self.physComp.addForce(Vec2d(2000,-12000))
                 self.amountMoved += 1
Example #29
0
    def playerCollidesWithOtherPlayer(self, player, other_player):
        player_mask = pygame.mask.from_surface(player.surface)
        other_player_mask = pygame.mask.from_surface(other_player.surface)

        other_player_offset = Vec2d(other_player.surface_position) - Vec2d(player.surface_position)

        overlap_point = player_mask.overlap(other_player_mask, other_player_offset)
        if overlap_point is None:
            return False
        else:
            return True
Example #30
0
    def playerCollidesWithBonus(self, player, bonus):
        bonus_mask = pygame.mask.from_surface(bonus.surface)
        player_mask = pygame.mask.from_surface(player.surface)

        bonus_offset = Vec2d(bonus.position) - Vec2d(player.surface_position)

        overlap_point = player_mask.overlap(bonus_mask, bonus_offset)
        if overlap_point is None:
            return False
        else:
            return True
Example #31
0
 def intersects_side(self, ax, ay, bx, by):
     VIEWLENGTH = 1
     p = Vec2d(ax, ay)
     r = Vec2d(bx-ax, by-ay)
     q = Vec2d(self.x, self.y)
     s = Vec2d(VIEWLENGTH*math.sin(self.angle),
               VIEWLENGTH*math.cos(self.angle))
     #make_dot(self.canvas, p)
     #make_dot(self.canvas, q)
     #make_dot(self.canvas, r)
     #make_dot(self.canvas, s)
     # note: division by zero if parallel: r x s = 0
     denom = Vec2d.cross(r, s)
     if denom == 0:
         return None
     t = Vec2d.cross((q - p), s) / denom
     u = Vec2d.cross((q - p), r) / denom
     if u < 0:
         return None
     if 0 < t < 1:
         result = p + t*r
         return result, u
Example #32
0
 def __init__(self, x=0, y=0, angle=0):
     Vec2d.__init__(self, x, y)
     self._angle = angle
Example #33
0
 def __init__(self, x=0, y=-500):
     Vec2d.__init__(self, x, y)
     self.accDif = 0
     self.lockCoef = 0
Example #34
0
 def __init__(self, x=0, y=0, maxrps=21):
     Vec2d.__init__(self, x, y)
     self._rps = 0
     self.maxrps = maxrps