Exemplo n.º 1
0
    def intersect(self, ray, line):
        x1 = line[0]
        y1 = line[1]
        # end point
        x2 = line[2]
        y2 = line[3]

        #position of the ray
        x3 = ray.x
        y3 = ray.y
        x4 = ray.x + ray.x
        y4 = ray.y + ray.y

        #denominator
        den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
        #numerator
        num = (x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)
        if den == 0:
            return None

        #formulas
        t = num / den
        u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / den

        if t > 0 and t < 1 and u > 0:
            #Px, Py
            x = x1 + t * (x2 - x1)
            y = y1 + t * (y2 - y1)
            pot = Vector2(x, y)
            return pot
Exemplo n.º 2
0
def make_vel(max_vel):
    angle = random.randint(0, 719)
    rad_ang = angle * pi / 180
    print(rad_ang)

    vel = Vector2(max_vel * sin(rad_ang), max_vel * cos(rad_ang))
    return vel
Exemplo n.º 3
0
    def __init__(self, screen_width, screen_height):
        self.screen_size = Vector2(screen_width, screen_height)
        self.target_fps = 30

        self.screen = pygame.display.set_mode(
            (int(self.screen_size.x), int(self.screen_size.y)))
        self.clock = pygame.time.Clock()
Exemplo n.º 4
0
    def calculatepos(self):
        print(f"pre-collision {self.id} velocity: {self.velocity}")
        for collision in self.collisions:
            m1 = self.mass
            m2 = collision[1]

            u1x = collision[2].x
            u1y = collision[2].y
            u2x = collision[3].x
            u2y = collision[3].y

            p1 = (m1 - m2) / (m1 + m2)
            p2 = 2 * m2 / (m1 + m2)

            v1x = math.floor(p1 * u1x + p2 * u2x)
            v1y = math.floor(p1 * u1y + p2 * u2y)
            print(f"{v1x} {v1y}")

            tangent = collision[4]
            v1fx = v1x + tangent.x
            v1fy = v1y + tangent.y
            self.velocity = Vector2(v1fx, v1fy)
            #self.velocity.update(v1x, v1y)
            print(f"post-collision {self.id} velocity: {self.velocity}")

        self.collisions = []

        dx, dy = self.velocity
        return (dx, dy)
Exemplo n.º 5
0
class Bird:
    """Class to represent a bird in the game."""

    initial_position = (300, 300)
    radius = 10
    gravity = Vector2(0, 900)
    jump_speed = (0, -300)

    def __init__(self, color: Tuple = None):
        """Initializes the bird.

        :param color: color of the bird.
        """
        self.color = color if color else random_color()
        self.position = Vector2(self.initial_position)
        self.velocity = Vector2(0, 0)
        self.rect: pygame.Rect
        self.alive = True

    def update(self, dt):
        """Update physical information about the Bird.

        :param dt: the time delta.
        """
        self.position += self.velocity * dt
        self.velocity += self.gravity * dt

    def jump(self):
        """Call this when the Bird performs a jump."""
        self.velocity = Vector2(self.jump_speed)
Exemplo n.º 6
0
 def __init__(self, x, y, width, height):
     sprite.Sprite.__init__(self)
     self.image = image.load('Food_1.png')
     self.rect = self.image.get_rect()
     self.width = width
     self.height = height
     self.position = Vector2(x, y)
Exemplo n.º 7
0
    def bounce(self, thing):
        total_width = (self.hitbox.width + thing.hitbox.width) / 2
        total_height = (self.hitbox.height + thing.hitbox.height) / 2
        towards_thing = thing.position - self.position
        offset_x = abs(towards_thing.x / total_width)
        offset_y = abs(towards_thing.y / total_height)

        offset = Vector2(offset_x, offset_y)

        is_vertical_bounce = offset.x < offset.y

        if is_vertical_bounce:
            if self.velocity.y > 0:
                self.position.y = thing.position.y - total_height
            else:
                self.position.y = thing.position.y + total_height
            self.velocity.y *= -1
        else:
            if self.velocity.x > 0:
                self.position.x = thing.position.x - total_width
            else:
                self.position.x = thing.position.x + total_width
            self.velocity.x *= -1

        self.push = 200
 def __generateRandomPoints(self):
     self.__initializePoints()
     for i in range(100):
         x = random.randint(50, 750)
         y = random.randint(50, 550)
         pt = Vector2(x, y)
         self.__random_points.append(pt)
Exemplo n.º 9
0
 def platform_animation(self, width, height):
     return {
         'neutral':
         Animation('neutral', [
             transform.scale(self.get_sprite("platform"), (width, height))
         ], [1000], Vector2(width, height))
     }
Exemplo n.º 10
0
    def apply_behavior(self, boids, stones, carnivores, food):
        perception_circle = self.compute_perceptions(boids)
        alignment = self.align(perception_circle[2], perception_circle[3])
        cohesion = self.cohesion(perception_circle[0], perception_circle[4])
        separation = self.separation(perception_circle[2],
                                     perception_circle[5])
        avoidance, near_stone = self.avoid(stones)
        dread, near_enemy = self.fear(carnivores)
        pursuit, near_meal = self.hunt(food)
        if self.satiety:
            near_meal = None

        self.acceleration += separation
        self.acceleration += 0.8 * alignment
        self.acceleration += 0.8 * cohesion
        if near_stone:
            self.velocity += 1.2 * avoidance
        if near_meal:
            self.acceleration = pursuit
        if near_enemy:
            self.acceleration = dread
        if self.acceleration == Vector2(*np.zeros(2)):
            self.acceleration = -self.velocity * 0.01
            self.velocity += 0.03 * self.velocity.rotate(90) \
                * np.sin(time.get_ticks() / 250)
        return perception_circle[2]
Exemplo n.º 11
0
    def brake(self, neighbourhood):
        self.update_buffer_zone()

        # Checks collision and calculates distance from the closest neighbour
        dist = 0
        if self.buffer_zone_image_rect.colliderect(
                neighbourhood["mouse"].image_rect):
            self.collision_imminent = True
            dist = self.get_pos() - neighbourhood["mouse"].get_pos()
        else:
            self.collision_imminent = False
            self.braking = None

        # If there's an imminent collision and the braking is not yet calculated
        if self.collision_imminent and self.braking is None:
            # Calculates braking
            scalar_dist = dist.length()
            scalar_dist -= self.safe_distance
            braking_mag = (-self.get_velocity().length_squared()) / (
                2 * scalar_dist)

            # Limits breaking
            if math.fabs(braking_mag) > math.fabs(self.maxbrake):
                if braking_mag < 0:
                    braking_mag = -self.maxbrake
                else:
                    braking_mag = self.maxbrake

            # Rotates vector to be parallel to the velocity
            self.braking = Vector2(math.fabs(braking_mag), 0)
            self.braking.rotate_ip(self.braking.angle_to(self.velocity))
            self.braking.rotate_ip(180)

        if self.braking is not None:
            self.accel = self.braking
Exemplo n.º 12
0
    def __init__(self, filename, size=None):
        '''
        size - the width, height of the in-game sprite as a Vector2.
                if None, defaults to scaling image by Game.PIXEL_ART_SCALE
        '''
        super().__init__()
        self.filename = filename

        # Load the image
        self.image = pygame.image.load(
            os.path.join(utilities.ROOT_DIR, 'assets', self.filename))

        # Store the original width, height of the pixel art
        rect = self.image.get_bounding_rect()
        self.pixel_size = Vector2(rect.size)
        # The correct size has each pixel scaled by PIXEL_ART_SCALE
        self.correct_size = self.pixel_size * game.Game.PIXEL_ART_SCALE
        # If no size given, use the self.correct_size
        self.size = size or self.correct_size
        # Ensure that self.size has int coords
        for i in self.size:
            if not i == int(i):
                raise Exception('Sprite size must have int coords')

        # Because pygame is picky, it can only scale sprites by int tuples
        int_size = tuple(int(x) for x in self.size)
        # Scale the image to the desired size
        self.image = pygame.transform.scale(self.image, int_size)

        # Check that the pixel art is to the correct scale
        if not self.size == self.correct_size:
            warnings.warn(
                'Sprite pixels are not correct size. Sprite is {}, should be {}.'
                .format(self.size, self.correct_size))
Exemplo n.º 13
0
    def update(self):

        self.life += 1
        self.time_limit -= 1

        if (self.length == len(self.body)):
            for i in range(self.length - 1):
                self.body[i] = self.body[i + 1]

            self.body[-1] = Vector2(self.pos)

        else:
            while len(self.body) != self.length:
                self.body.append(Vector2(self.pos))

        self.pos = self.pos + (self.v * block)
Exemplo n.º 14
0
    def look(self, direction, food):
        inp = [0, 0, 0]

        lookat = Vector2(self.pos)

        foodfound = False
        bodyfound = False

        dist = 1

        lookat += direction * block

        while not (lookat.x < 0 or lookat.x > WIDTH or lookat.y < 0
                   or lookat.y > HEIGHT):

            if (not foodfound) and lookat.distance_to(food) <= 10:
                inp[0] = 1
                foodfound = True

            if (not bodyfound) and lookat in self.body and lookat != self.pos:
                inp[1] = 1 / dist
                bodyfound = True

            lookat += direction * block
            dist += 1

        inp[2] = 1 / dist

        return inp[0], inp[1], inp[2]
Exemplo n.º 15
0
 def update(self, parent: Item = None):
     self._rotating_item.rotate(-3)
     rotation = self._rotating_item.theta * math.pi / 180.0
     pos = Vector2(0.10 * math.cos(rotation), 0.10 * math.sin(rotation))
     self._rotating_item.set_pos(pos)
     self._center_item.rotate(1)
     super().update()
Exemplo n.º 16
0
    def update(self):
        # Add velocity to position
        self.pos += self.vel

        # Create acceleration vector and add it to velocity
        accVec = Vector2(
            cos(radians(self.dir)), sin(radians(self.dir)))
        accVec.scale_to_length(self.acc)

        self.vel += accVec
        self.acc *= 0

        # Limit velocity to maximum value
        if self.vel.magnitude() > self.maxVel:
            self.vel.scale_to_length(self.maxVel)

        # Apply dampening to velocity
        self.vel *= 1 - self.damp

        # If ship is off screen wrap around to other side
        if self.pos.x > self.width:
            self.pos.x = 0
        if self.pos.x < 0:
            self.pos.x = self.width
        if self.pos.y > self.height:
            self.pos.y = 0
        if self.pos.y < 0:
            self.pos.y = self.height

        for B in self.bullets:
            B.update()
            if B.tick >= 100:
                self.bullets.remove(B)

        return
Exemplo n.º 17
0
 def update(self):
     self._t += 1
     if self._t == self._TIME:
         self._game_callback.set_scene_id(SceneId.TEST)
     self._camera.dzoom(0.99)
     self._player.move(Vector2(0.01, 0))
     super().update()
Exemplo n.º 18
0
    def shoot_at(self, x, y, target_group):
        if target_group == self.game.walls:
            weapon = WEAPONS["DRILL"]
        else:
            weapon = WEAPONS[self.weapon_name]

        time_since_last_shot = pygame.time.get_ticks() - self.last_shot_time
        if time_since_last_shot < weapon["FIRING_RATE"]:
            return

        bullet_velocity = Vector2(x, y) - self.position
        if bullet_velocity.magnitude() > 0:
            bullet_velocity = bullet_velocity.normalize()

        for _ in range(weapon["AMMO_PER_SHOT"]):
            Bullet(
                self.game,
                self.rect.center,
                bullet_velocity,
                weapon["SPREAD"],
                weapon["TTL"],
                weapon["SPEED"],
                weapon["DAMAGE"],
                weapon["ID"],
                weapon["SIZE"],
                target_group,
            )
        self.last_shot_time = pygame.time.get_ticks()
Exemplo n.º 19
0
    class Ranged:
        """Health of enemy"""
        HEALTH_MAX = 100
        """Cooldown between attacks"""
        ATTACK_COOLDOWN_S = 2
        """WEIGHT of the enemy"""
        WEIGHT = .5
        """A circle centered on the enemy. If the player enter this rect, the enemy
        will start attacking him.
        """
        DETECTION_RANGE_SQR = 650**2
        """A rect centered on the enemy. If the player enter this rect, the enemy
        will run into the opposite of payer
        """
        FEAR_RANGE_SQR = 300**2
        """Enemy walking velocity.
        When afraid by a player, they will walk according to this velocity.
        """
        FEAR_WALK_VELOCITY = Vector2(.3, 0)

        class Projectile:
            """Duration of projectile life"""
            TIME_TO_LIVE = 10
            """"Strength of the projectile when it impact"""
            STRENGTH = 3000
            """Speed of projectile when lunched by enemy"""
            SPEED = 400
Exemplo n.º 20
0
 def __init__(
     self,
     game,
     position,
     velocity,
     spread,
     ttl,
     speed,
     damage,
     id,
     size,
     target_group,
 ):
     self.groups = game.all_sprites, game.bullets
     pygame.sprite.Sprite.__init__(self, self.groups)
     self.game = game
     self.id = id
     self.image = self.game.bullet_images[self.id]
     self.rect = self.image.get_rect()
     self.position = position
     self.rect.center = self.position
     self.ttl = ttl
     self.spawn_time = pygame.time.get_ticks()
     self.speed = uniform(speed * 0.9, speed * 1.1)
     self.damage = damage
     self.velocity = velocity + Vector2(uniform(-spread, spread),
                                        uniform(-spread, spread))
     self.velocity = self.velocity.normalize()
     self.target_group = target_group
     self.game.weapons_sounds[self.id].play()
Exemplo n.º 21
0
    def __init__(self):
        pygame.init()
        print("Init pygame")
        pygame.font.init()
        print("Init pygame font")
        pygame.display.set_caption('PyGameOfLife')

        self.win_surf = pygame.display.set_mode(MIN_SIZE, pygame.RESIZABLE)
        self.is_running = True
        self.game_paused = True

        self.game = Game()
        # testing only
        self.game.activate_cell((5, -5))
        self.game.activate_cell((6, -5))
        self.game.activate_cell((6, -6))
        self.game.activate_cell((6, -4))
        self.game.activate_cell((7, -4))

        self.renderer = Renderer(self.win_surf)
        self.camera = Camera(Vector2(-9, 5), 25)
        print("Made everything else")
        self.menubar = MenuBar(self)
        print("Made menubar")
        self.menubar.update(self.game)

        self.renderer.render_grid(self.camera)
        self.renderer.render_cells(self.camera, self.game)
        self.renderer.render_menubar(self.menubar)
        pygame.display.update()

        self.dragging = False
        self.shift_pressed = False
        self.btn_active = None
        self.prev_mouse_loc = None
Exemplo n.º 22
0
    def raycast(self, wall):
        x1 = wall.a.x
        y1 = wall.a.y
        x2 = wall.b.x
        y2 = wall.b.y

        x3 = self.pos.x
        y3 = self.pos.y
        x4 = self.pos.x + self.dir.x
        y4 = self.pos.y + self.dir.y

        den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
        if den == 0:
            return None, None

        t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / den
        u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / den

        if 0 < t < 1 and u > 0:
            self.intersection = Vector2()
            self.intersection.x = float(x1 + t * (x2 - x1))
            self.intersection.y = float(y1 + t * (y2 - y1))
            return self.intersection, u
        else:
            return None, None
Exemplo n.º 23
0
 def __init__(self, image: object, position: tuple, layer: int):
     sprite.Sprite.__init__(self)
     self.vec = Vector2((position[0], position[1]))
     self.image = image
     self.rect = Surface.get_rect(self.image)
     self.rect.topleft = self.vec
     self._layer = layer
Exemplo n.º 24
0
    def shoot_at(self, x, y, target_group):
        weapon = WEAPONS[self.weapon_name]

        time_since_last_shot = pygame.time.get_ticks() - self.last_shot_time
        if time_since_last_shot < weapon['FIRING_RATE']:
            return
        bullet_velocity = Vector2(x, y) - self.position
        if bullet_velocity.magnitude() > 0:
            bullet_velocity = bullet_velocity.normalize()

        for _ in range(weapon['AMMO_PER_SHOT']):
            Bullet(self.game, Vector2(self.rect.center), bullet_velocity,
                   weapon['SPREAD'], weapon['TTL'], weapon['SPEED'],
                   weapon['DAMAGE'], weapon['COLOR'], weapon['SIZE'],
                   target_group)
        self.last_shot_time = pygame.time.get_ticks()
Exemplo n.º 25
0
 def __init__(self, pos=None, filename=None):
     super().__init__(pos or Vector2(Game.window.get_width() - 130, 170))
     self.image = load_surface(
         os.path.dirname(__file__) + '/data/images/notepad.png')
     self.image = pygame.transform.scale(self.image, (100, 100))
     self.filename = filename or os.path.dirname(
         __file__) + '/data/code/test.py'
Exemplo n.º 26
0
    def __init__(self, board_rect: Rect):
        board = Board(board_rect)
        self.board = board
        self.center = Vector2(board.container.center)
        self.queen = Queen(board.coin_radius, Board.COIN_MASS, self.center,
                           board.container)
        self.striker = Striker(board.striker_radius, Board.STRIKER_MASS,
                               board.container)
        self.coins = [CarromMen(i % 2, board.coin_radius, Board.COIN_MASS, self.center, board.container) for i in range(6)] \
            + [CarromMen(0, board.coin_radius, Board.COIN_MASS, self.center, board.container) for _ in range(6)]\
            + [CarromMen(1, board.coin_radius, Board.COIN_MASS, self.center, board.container) for _ in range(6)]
        self.rotate_carrom_men(60)
        self.isPocket = False

        self.player_coins = ([], [])
        for coin in self.coins:
            self.player_coins[coin.get_player()].append(coin)
        self.pocketed_coins = ([], [])
        self.foul_count = [0, 0]
        self.has_queen = [False, False]
        self.pocketed_queen = False
        self.queen_on_hold = False
        self.pocketed_striker = False
        self.current_pocketed = []
        self.player_turn = 0
        self.game_over = False
        self.winner = None
        self.reason = None
        self.first_collision = None
Exemplo n.º 27
0
        def inter_ray_line_horizontal(rayVector, line):
            """
            Return the intersection coordinates of given ray cast from fromPos and
            given horizontal line.

            Ray argument is taken as the vector corresponding to the given ray.

            Parameters
            ----------
            rayVector : pygame.Vector2
            line : int
            """
            lineVector = Vector2(1, 0)  # Leftward unit vector
            linePos = Vector2(0, (line + 1) * self.blockSize)
            return self._intersect_lines(fromPos, rayVector, linePos,
                                         lineVector)
Exemplo n.º 28
0
    def renderPolygon(self, points, color=(255, 255, 255), alpha=None):
        newPoints = [Vector2(pt.x, pt.y) for pt in points]
        for i in range(len(newPoints)):
            newPoints[i].y = self.__surface.get_height() - newPoints[i].y
        if alpha is None:
            pg.draw.polygon(self.__surface, color, newPoints)
        else:
            min_x = newPoints[0].x
            min_y = newPoints[0].y
            max_x = newPoints[0].x
            max_y = newPoints[0].y

            for pt in newPoints:
                if pt.x < min_x:
                    min_x = pt.x

                if pt.y < min_y:
                    min_y = pt.y

                if pt.x > max_x:
                    max_x = pt.x

                if pt.y > max_y:
                    max_y = pt.y

            surf = pg.Surface((max_x-min_x, max_y - min_y))
            surf.set_colorkey((0, 0, 0))
            surf.set_alpha(alpha)
            pg.draw.polygon(
                surf, color, [(pt.x - min_x, pt.y - min_y) for pt in newPoints])
            self.__surface.blit(surf, (min_x, min_y))
Exemplo n.º 29
0
 def get_legal_moves(self, board=None) -> List[Vector2]:
     if not board:
         board = self.board
     mlist = []
     if self.name == 'pawn':
         # movement
         if self.board.get_owner(self.pos + (0, self.owner)) == PlayerColor.EMPTY:
             mlist.append(self.pos + (0, self.owner))
         if not self.has_moved and board.get_owner(self.pos+(0, 2*self.owner)) == PlayerColor.EMPTY:
             mlist.append(self.pos+(0, 2*self.owner))
         # capture
         if board.get_owner(self.pos + (1, self.owner)) + self.owner == 0:
             mlist.append(self.pos + (1, self.owner))
         if board.get_owner(self.pos + (-1, self.owner)) + self.owner == 0:
             mlist.append(self.pos + (-1, self.owner))
         return list(filter(self.board.in_board_range, mlist))
     else:
         for v in self._movement_vector:
             v = Vector2(v)
             for i in range(1, config.BOARD_SIZE):
                 if self.name in ('king', 'knight') and i > 1: break
                 if not board.in_board_range(self.pos + i * v): break
                 owner = board.get_owner(self.pos + i * v)
                 if owner == PlayerColor.EMPTY:
                     mlist.append(self.pos + i * v)
                 elif owner != self.owner:
                     mlist.append(self.pos + i * v)
                     break
         return mlist
Exemplo n.º 30
0
 def __init__(self, game, weapon, x, y, orientation, target_group):
     self.groups = game.bullets
     pygame.sprite.Sprite.__init__(self, self.groups)
     self.game = game
     self.image = game.image_bullet
     self.image.fill(weapon['COLOR'])
     self.rect = self.image.get_rect()
     self.rect.center = Vector2(x, y)
     self.speed = weapon['SPEED'] * uniform(0.9, 1.1)
     self.ttl = weapon['TTL']
     self.damage = weapon['DAMAGE']
     self.spawn_time = pygame.time.get_ticks()
     orientation += Vector2(uniform(-weapon['SPREAD'], weapon['SPREAD']),
                            uniform(-weapon['SPREAD'], weapon['SPREAD']))
     self.velocity = orientation.normalize() * self.speed
     self.target_group = target_group