Ejemplo n.º 1
1
 def _get_raw_shadow(self):
     target_img = self.target.get_image(self.capture_state)
     r = target_img.get_rect()
     #the shadow will be larger in order to make free space for fadeout.
     r.inflate_ip(2*self.shadow_radius, 2*self.shadow_radius)
     img = Surface(r.size)
     img.fill((255, 255, 255, 255))
     img.blit(target_img, (self.shadow_radius, self.shadow_radius))
     if self.sun_angle <= 0.:
         raise Exception("Sun angle must be greater than zero.")
     elif self.sun_angle != 45. and self.vertical:
         w, h = img.get_size()
         new_h = h / tan(self.sun_angle * pi / 180.)
         screen_size = functions.get_screen().get_size()
         new_h = abs(int(min(new_h, max(screen_size))))
         img = scale(img, (w, new_h))
     if self.angle_mode == "flip":
         img = flip(img, self.mode_value[0], self.mode_value[1])
     elif self.angle_mode == "rotate":
         img = rotate(img, self.mode_value)
     else:
         raise Exception("angle_mode not available: " + str(self.angle_mode))
     shadow = pilgraphics.get_shadow(img,
                                     radius=self.shadow_radius,
                                     black=self.black,
                                     alpha_factor=self.alpha_factor,
                                     decay_mode=self.decay_mode,
                                     color=self.color)
     return shadow
 def blit_templates(self, surface):
     x = 0
     y = 0
     #not memory nor performance efficient, but clear:
     if self.mode == "flip":
         corners = {
             "topleft": self.topleft_img,
             "bottomleft": flip(self.topleft_img, False, True),
             "bottomright": flip(self.topleft_img, True, True),
             "topright": flip(self.topleft_img, True, False)
         }
         sides = {
             "top": self.top_img,
             "left": rotate(self.top_img, 90),
             "bottom": rotate(self.top_img, 180),
             "right": rotate(self.top_img, 270)
         }
     elif self.mode == "rotate":
         corners = {
             "topleft": self.topleft_img,
             "bottomleft": rotate(self.topleft_img, 90),
             "bottomright": rotate(self.topleft_img, 180),
             "topright": rotate(self.topleft_img, 270)
         }
         sides = {
             "top": self.top_img,
             "left": rotate(self.top_img, 90),
             "bottom": rotate(self.top_img, 180),
             "right": rotate(self.top_img, 270)
         }
     cornsize = {
         key: value.get_size()
         for key, value in iter(corners.items())
     }
     sidsize = {key: value.get_size() for key, value in iter(sides.items())}
     #Blitting Sides
     nx = (self.size[0] - cornsize["topleft"][0] - cornsize["topright"][0])\
                                                      // sidsize["top"][0]
     ny = (self.size[1] - cornsize["topleft"][1] - cornsize["bottomleft"][1])\
                                                      // sidsize["left"][1]
     endx = nx * sidsize["top"][0] + cornsize["topleft"][0]
     endy = ny * sidsize["left"][1] + cornsize["topleft"][1]
     sizex = endx + cornsize["topright"][0]
     sizey = endy + cornsize["bottomleft"][1]
     self.size = (sizex, sizey)
     for i in range(nx):
         x = i * sidsize["top"][0] + cornsize["topleft"][0]
         surface.blit(sides["top"], (x, 0))
         x = i * sidsize["bottom"][0] + cornsize["bottomleft"][0]
         surface.blit(sides["bottom"], (x, sizey - sidsize["bottom"][1]))
     for i in range(ny):
         y = i * sidsize["left"][1] + cornsize["topleft"][1]
         surface.blit(sides["left"], (0, y))
         y = i * sidsize["right"][1] + cornsize["topright"][1]
         surface.blit(sides["right"], (sizex - sidsize["right"][0], y))
     #Blitting corners
     surface.blit(corners["topleft"], (0, 0))
     surface.blit(corners["bottomleft"], (0, endy))
     surface.blit(corners["bottomright"], (endx, endy))
     surface.blit(corners["topright"], (endx, 0))
Ejemplo n.º 3
0
    def image_at(self,
                 rect,
                 colorkey=None,
                 scale2x=False,
                 flip=False,
                 alpha=False):
        if alpha:
            image = Surface(rect.size, SRCALPHA)
            image.blit(self.image, (0, 0), rect)
        else:
            image = Surface(rect.size).convert()
            image.blit(self.image, (0, 0), rect)
            if colorkey is not None:
                if colorkey == -1:
                    colorkey = image.get_at((0, 0))
                image.set_colorkey(colorkey, RLEACCEL)

        if flip == 'x':
            image = transform.flip(image, True, False)
        elif flip == 'y':
            image = transform.flip(image, False, True)

        if scale2x:
            image = transform.scale2x(image)

        return image
Ejemplo n.º 4
0
 def choose_display_image(self, dt):
     if self.moving_right:
         self.last_direction = "RIGHT"
         self.since_last_sprite_animation_frame = self.since_last_sprite_animation_frame + self.engine.clock.get_time(
         )
         if self.since_last_sprite_animation_frame / 1000 >= 0.08:
             self.since_last_sprite_animation_frame = 0
             self.image_to_display = self.image_running[
                 self.current_running_image]
             self.current_running_image = (self.current_running_image + 1
                                           ) % (len(self.image_running) - 1)
     elif self.moving_left:
         self.last_direction = "LEFT"
         self.since_last_sprite_animation_frame = self.since_last_sprite_animation_frame + self.engine.clock.get_time(
         )
         if self.since_last_sprite_animation_frame / 1000 >= 0.08:
             self.since_last_sprite_animation_frame = 0
             self.image_to_display = self.image_running[
                 self.current_running_image]
             self.image_to_display = transform.flip(self.image_to_display,
                                                    True, False)
             self.current_running_image = (self.current_running_image + 1
                                           ) % (len(self.image_running) - 1)
     else:
         self.current_running_image = 0
         self.since_last_sprite_animation_frame = 0
         self.image_to_display = self.image
         if self.last_direction == "LEFT":
             self.image_to_display = transform.flip(self.image_to_display,
                                                    True, False)
 def get_enemy_fire_sprites(cls) -> {Enum, List[Surface]}:
     return {
         EnemyState.RUNNING_RIGHT: [
             transform.flip(i, True, False) for i in [
                 cls.get_image(
                     path.join("hostiles", "fire_walking_calm_1.png")),
                 cls.get_image(
                     path.join("hostiles", "fire_walking_calm_2.png"))
             ]
         ],
         EnemyState.RUNNING_LEFT: [
             cls.get_image(path.join("hostiles",
                                     "fire_walking_calm_1.png")),
             cls.get_image(path.join("hostiles", "fire_walking_calm_2.png"))
         ],
         EnemyState.ATTACKING_RIGHT: [
             transform.flip(i, True, False) for i in [
                 cls.get_image(
                     path.join("hostiles", "fire_walking_angry_1.png")),
                 cls.get_image(
                     path.join("hostiles", "fire_walking_angry_2.png"))
             ]
         ],
         EnemyState.ATTACKING_LEFT: [
             cls.get_image(path.join("hostiles",
                                     "fire_walking_angry_1.png")),
             cls.get_image(path.join("hostiles",
                                     "fire_walking_angry_2.png"))
         ],
     }
Ejemplo n.º 6
0
    def make_border_image(border_images, surface, sides, corners):
        h_side_image, v_side_image, corner_image = border_images

        draw_corners = ContainerGraphics.draw_corners
        full_h_side = ContainerGraphics.get_h_side(h_side_image)
        full_v_side = ContainerGraphics.get_v_side(v_side_image)

        w, h = surface.get_size()

        if "l" in sides:
            surface.blit(full_h_side, (0, 0))

        if "r" in sides:
            h_offset = w - full_h_side.get_size()[0]
            surface.blit(transform.flip(
                full_h_side, True, False), (h_offset, 0))

        if "t" in sides:
            surface.blit(full_v_side, (0, 0))

        if "b" in sides:
            v_offset = h - full_v_side.get_size()[1]
            surface.blit(transform.flip(
                full_v_side, False, True), (0, v_offset))

        if corners:
            draw_corners(corner_image, surface, corners)

        return surface
Ejemplo n.º 7
0
    def __init__(self, area):
        sprite.Sprite.__init__(self)

        self.image_normal1_r, self.rect_sprite = LoadPng("normal.png")
        self.image_normal1_l = transform.flip(self.image_normal1_r, 1, 0)
        self.image_walk1_r, _ = LoadPng("walk1.png")
        self.image_walk1_l = transform.flip(self.image_walk1_r, 1, 0)
        self.image_walk2_r, _ = LoadPng("walk2.png")
        self.image_walk2_l = transform.flip(self.image_walk2_r, 1, 0)
        self.image_jump_r, _ = LoadPng("jump.png")
        self.image_jump_l = transform.flip(self.image_jump_r, 1, 0)

        self.image, self.rect = self.image_normal1_r, self.rect_sprite
        self.rect.midbottom = area.midbottom
        self.area = area
        self.status = "normal"
        self.x = self.rect.x
        self.y = self.rect.y
        self.vel_x = 0.0
        self.vel_y = 0.0
        self.orientation = 'right'
        self.speed = 1
        self.speed_max = 9
        self.speed_increase = 0.5
        self.jump_speed = -20
Ejemplo n.º 8
0
    def create_flipped_animation_sets(self, *names):
        """Create flipped set of animations."""
        if not names:
            prev = self.pack.copy()
            for name in prev:
                anim_set = list(
                    map(lambda x: transform.flip(x, True, False),
                        self.pack[name]))
                if "right" in name:
                    self.pack[name.replace("right", "left")] = anim_set
                    self.meta[name.replace("right",
                                           "left")] = [f"Flipped {name}"]
                else:
                    self.pack[f"{name}-flipped"] = anim_set
                    self.meta[f"{name}-flipped"] = [f"Flipped {name}"]
        for name in names:
            if name not in self.pack:
                raise ValueError(f"Can't find right animation set: {name}")
            # Flipping every frame.
            anim_set = list(
                map(lambda x: transform.flip(x, True, False), self.pack[name]))

            if "right" in name:
                self.pack[name.replace("right", "left")] = anim_set
                self.meta[name.replace("right", "left")] = [f"Flipped {name}"]
            else:
                self.pack[f"{name}Flip"] = anim_set
                self.meta[f"{name}Flip"] = [f"Flipped {name}"]
Ejemplo n.º 9
0
 def images(self):
     sprite_filename = self.status.sprite_filename
     if 0 in self.__images_cash[sprite_filename]:
         image = self.__images_cash[sprite_filename][0]
     else:
         image = load_image(name=sprite_filename, colorkey=-1)
         self.__images_cash[sprite_filename][0] = image
     return [image, flip(image, 1, 0), flip(image, 0, 1), flip(image, 1, 1)]
Ejemplo n.º 10
0
 def images(self):
     sprite_filename = self.status.sprite_filename
     if 0 in self.__images_cash[sprite_filename]:
         image = self.__images_cash[sprite_filename][0]
     else:
         image = load_image(name=sprite_filename, colorkey=-1)
         self.__images_cash[sprite_filename][0] = image
     return [image, flip(image, 1, 0), flip(image, 0, 1), flip(image, 1, 1)]
Ejemplo n.º 11
0
def test_flip(surface):
    """Simple flip tests"""
    obj = _make_object()

    surface.blit(obj, (20, 20))
    obj1 = transform.flip(obj, True, False)
    surface.blit(obj1, (80, 80))
    obj1 = transform.flip(obj, False, True)
    surface.blit(obj1, (160, 160))
    obj1 = transform.flip(obj, True, True)
    surface.blit(obj1, (320, 320))
Ejemplo n.º 12
0
def test_flip(surface):
   """Simple flip tests"""
   obj = _make_object()

   surface.blit(obj, (20, 20))
   obj1 = transform.flip(obj, True, False)
   surface.blit(obj1, (80, 80))
   obj1 = transform.flip(obj, False, True)
   surface.blit(obj1, (160, 160))
   obj1 = transform.flip(obj, True, True)
   surface.blit(obj1, (320, 320))
Ejemplo n.º 13
0
    def __init__(self, maxHealth: int, isPlayer1: bool, nick: str) -> None:
        # region DocString
        """
        Creates a `HealthBar` object

        ### Arguments
            `maxHealth {int}`:
                `summary`: the starting health of the player
            `isPlayer1 {bool}`:
                `summary`: boolean to display the bar in the right direction
            `nick {str}`:
                `summary`: the username of the player
        """
        # endregion

        super().__init__()

        self.isPlayer1 = isPlayer1

        # region Gauge sprite

        self.gaugeImg = load(Game.GAUGE_PATH).convert_alpha()
        self.gaugeRect = self.gaugeImg.get_rect()
        self.gaugeRect.move_ip(
            10 if self.isPlayer1 else Game.SIZE[0] - self.gaugeRect.width - 10,
            10)

        # endregion

        # region Bar sprite

        self.lifeImg = load(Game.LIFEBAR_PATH).convert_alpha()
        self.lifeRect = self.lifeImg.get_rect()
        self.lifeRect.move_ip(
            10 if self.isPlayer1 else Game.SIZE[0] - self.lifeRect.width - 10,
            10)

        # endregion

        if not self.isPlayer1:
            self.gaugeImg = flip(self.gaugeImg, True, False)
            self.lifeImg = flip(self.lifeImg, True, False)

        self.nick = SysFont(Game.FONT, 30).render(nick.strip(), False,
                                                  Color.WHITE)
        self.nickRect = self.nick.get_rect()
        self.nickRect.move_ip(
            15 if self.isPlayer1 else Game.SIZE[0] - self.nickRect.width - 15,
            self.gaugeRect.height + 15,
        )

        self.playerHealth = maxHealth
        self.maxHealth = maxHealth
Ejemplo n.º 14
0
    def draw(self, surface):
        if self.enabled:
            if self.do_flip:
                self.image = flip(self.image, True, False)
                if not self.shadow == None:
                    self.shadow = flip(self.shadow, True, False)
                self.do_flip = False

            pos=[self.old_pos[0]-self.offset[0],self.old_pos[1]-self.offset[1]]

            if not self.shadow == None:
                surface.blit(self.shadow,(pos[0]+2, pos[1]+2))
            surface.blit(self.image,pos)
Ejemplo n.º 15
0
def test_flip_subsurface(surface):
    """Test transform.flip with a subsurface as the source"""
    obj = _make_object()

    surface.blit(obj, (20, 20))
    obj_sub = obj.subsurface((20, 20, 15, 25))
    surface.blit(obj_sub, (20, 190))
    obj1 = transform.flip(obj_sub, True, False)
    surface.blit(obj1, (60, 190))
    obj1 = transform.flip(obj_sub, False, True)
    surface.blit(obj1, (20, 390))
    obj1 = transform.flip(obj_sub, False, False)
    surface.blit(obj1, (60, 390))
Ejemplo n.º 16
0
def test_flip_subsurface(surface):
    """Test transform.flip with a subsurface as the source"""
    obj = _make_object()

    surface.blit(obj, (20, 20))
    obj_sub = obj.subsurface((20, 20, 15, 25))
    surface.blit(obj_sub, (20, 190))
    obj1 = transform.flip(obj_sub, True, False)
    surface.blit(obj1, (60, 190))
    obj1 = transform.flip(obj_sub, False, True)
    surface.blit(obj1, (20, 390))
    obj1 = transform.flip(obj_sub, False, False)
    surface.blit(obj1, (60, 390))
Ejemplo n.º 17
0
    def on_init(self) -> None:
        """Load image upon initialization."""
        _image = image.load(self.path)
        _rect = _image.get_rect()

        self.image = transform.scale(
            _image, (_rect.width * CONFIG.get_texture_factor(),
                     _rect.height * CONFIG.get_texture_factor()))

        if all(self.flippable):
            self.image_flipped_xy = transform.flip(self.image, True, True)
        if self.flippable[0]:
            self.image_flipped_x = transform.flip(self.image, True, False)
        if self.flippable[1]:
            self.image_flipped_y = transform.flip(self.image, False, True)
Ejemplo n.º 18
0
 def handle_render(self):
     if self._stage_one:
         r_i = flip(assets.images['enemy'], False, True)
         for enemy in self._stage_one_enemies:
             self.game.display.blit(r_i, enemy.rect)
         self.game.display.blit(assets.images['player'],
                                self._stage_one_player.rect)
     if self._stage_two:
         r_i = flip(assets.images['player'], False, True)
         for laser in self._stage_two_lasers:
             self.game.display.blit(assets.images['laser_enemy'],
                                    laser.rect)
         for enemy in self._stage_two_enemies:
             self.game.display.blit(assets.images['enemy'], enemy.rect)
         self.game.display.blit(r_i, self._stage_one_player.rect)
Ejemplo n.º 19
0
    def update(self):
        #movement updates
        changed = False
        if self.moveTo and (self.actionFramesLeft == 0):
            self.image = self.defImage.copy()
            self.resize()
            self.rect = self.image.get_rect()
            if self.marker == 1:
                self.rect.midtop = self.moveTo
            else:
                self.rect.midbottom = self.moveTo
            self.moveTo = None
            changed = True

        elif self.moveTo:
            self.image = self.moveStrip.next().copy()
            self.resize()
            self.actionFramesLeft -= 1
            changed = True


        #attack updates
        elif self.attack and (self.actionFramesLeft == 0):
            self.image = self.defImage.copy()
            self.resize()
            self.attack = None
            changed = True
        
        elif self.attack:
            #self.image = self.basicAttackStrip.next()
            self.image = self.attackStrip.next().copy()
            self.resize()
            self.actionFramesLeft -= 1
            changed = True

        if self.charactor.charging:
            chargingImage = self.chargeImages[self.chargeIndex]
            self.image.blit(chargingImage, self.image.get_rect().center)
            self.chargeIndex = (self.chargeIndex + 1) % len(self.chargeImages)


        #mirror character on right side
        if self.idNum == 2 and changed:
            self.image = trans.flip(self.image, True, False)


        if self.marker == 1 and changed:
            self.image = trans.flip(self.image, False, True)
Ejemplo n.º 20
0
def command_horiz(new_img, screen, file, rect):
    "flip horizontally (mirror)"
    wait_cursor()
    new_img = flip(new_img, 90, 0)
    my_update_screen(new_img, rect, file)
    normal_cursor()
    return (new_img, new_img, rect)
Ejemplo n.º 21
0
 def drawEntity(self):
     if self.heading == 1:
         self.screen.blit(self.animation.image, self.entity.getPos())
     elif self.heading == -1:
         self.screen.blit(
             flip(self.animation.image, True, False), self.entity.getPos()
         )
Ejemplo n.º 22
0
def command_vert(new_img, screen, file, rect):
    "flip vertically"
    wait_cursor()
    new_img = flip(new_img, 90, 90)
    my_update_screen(new_img, rect, file)
    normal_cursor()
    return (new_img, new_img, rect)
Ejemplo n.º 23
0
 def render(self):
     self.fr += 1
     cur_frame = self.fr % 3
     if self.side > 0:
         self.scrn.blit(flip(self.enemy_main[cur_frame], True, False), self.rect)
     else:
         self.scrn.blit(self.enemy_main[cur_frame], self.rect)
Ejemplo n.º 24
0
	def __animate(self, game):

		if ((game.frame % self.animInterval) == 0):
			self.anim_frame += 1
		
			if (self.anim_frame > self.maxFrames):
				self.anim_frame = 1
			if (self.anim_frame <= 0):
				self.anim_frame = self.maxFrames

				
		imageString = self.sprname + "_" + str(self.anim_frame)
		
		# if we flip the y then we must move adjust the rect.x
		if self.flips[1]:
			self.rect.x = self.orgRect.x + self.posPercent * self.orgRect.height - self.orgRect.height + TILE_SIZE
		else:
			self.rect.x = self.orgRect.x
			
		# clip part of the image
		img = transform.chop(game.images[imageString][0], Rect(0,0,0,self.posPercent * self.orgRect.height))
		
		# apply flipping and rotation if required
		if self.flips[0] or self.flips[1]:
			img = transform.flip(img, self.flips[0], self.flips[1])
		if self.rotation != 0:
			img = transform.rotate(img, self.rotation)
			
		self.setimage(img)
Ejemplo n.º 25
0
    def __init__(self, game_env, source, target, flip):
        super(Sam, self).__init__()
        self.__game_env = game_env
        self.__angle = math.atan2(target[1] - source[1], target[0] -
                                  source[0])  # sam angle of fire in radian
        self.__speed = 5 + (
            1 if self.__game_env.dynamic.game_level % 2 == 0 else 0
        )  # default sam speed is 5 and increased each level

        if flip:  # sam image rotational angle based on the fire position
            rotation_angle = 90 - self.__angle * (180 / 3.1415)
        else:
            rotation_angle = 270 + self.__angle * (180 / 3.1415)

        self.surf = image.load(
            self.__game_env.static.sam).convert()  # loading sam image
        self.surf = transform.rotate(self.surf,
                                     rotation_angle)  # rotating the image
        self.surf = transform.flip(self.surf, flip,
                                   ~flip)  # flipping image as necessary
        self.surf.set_colorkey(
            (255, 255, 255), self.__game_env.RLEACCEL
        )  # setting the white color as the transperant area; RLEACCEL is used for better performance on non accelerated displays
        self.rect = self.surf.get_rect(center=(
            source[0], source[1]
        ))  # setting the position of the bullet as the input (souce_x, y_pos)
Ejemplo n.º 26
0
    def __init__(
        self,
        facing: bool,
        nick: str,
        health: int,
        animationFrames: dict[AS, Animation],
        sprite_list: Group,
    ) -> None:
        # region Docstring
        """
        Creates a `Player` object

        ### Arguments
            `facing {bool}`:
                `summary`: boolean to display the player in the right direction
            `nick {str}`:
                `summary`: the username of the player
            `health {int}`:
                `summary`: the max health of the player
            `animationFrames {{AnimationState, Animation}}`:
                `summary`: a dictionary that associates every `AnimationState` with a `Animation` object
            `sprite_list {Group}`:
                `summary`: the sprite group in which to append internally generated sprites
        """
        # endregion

        super().__init__()

        # region Animation variables

        self.anims = animationFrames
        self.state = AS.IDLE
        self.current_anim_frame = 0
        self.animation_frames = 6
        self.current_atk_frame = 0
        self.atk_frames = 24
        self.chargedAtk = 0
        self.atk_cooldown_frames = 40
        self.cooldown = False

        # endregion

        # region Sprite variables

        self.image = self.anims[self.state].next()
        self.rect = self.image.get_rect()
        self.rect.bottom = Game.SIZE[1]

        self.facing = facing
        if not self.facing:
            self.image = flip(self.image, True, False)
            self.rect.right = Game.SIZE[0]

        # endregion

        self.vel_y = 0

        self.health = HealthBar(health, facing, nick)

        self.sprite_list = sprite_list
Ejemplo n.º 27
0
    def __animate(self, game):

        if ((game.frame % self.animInterval) == 0):
            self.anim_frame += 1

            if (self.anim_frame > self.maxFrames):
                self.anim_frame = 1
            if (self.anim_frame <= 0):
                self.anim_frame = self.maxFrames

        imageString = self.sprname + "_" + str(self.anim_frame)

        # if we flip the y then we must move adjust the rect.x
        if self.flips[1]:
            self.rect.x = self.orgRect.x + self.posPercent * self.orgRect.height - self.orgRect.height + TILE_SIZE
        else:
            self.rect.x = self.orgRect.x

        # clip part of the image
        img = transform.chop(
            game.images[imageString][0],
            Rect(0, 0, 0, self.posPercent * self.orgRect.height))

        # apply flipping and rotation if required
        if self.flips[0] or self.flips[1]:
            img = transform.flip(img, self.flips[0], self.flips[1])
        if self.rotation != 0:
            img = transform.rotate(img, self.rotation)

        self.setimage(img)
Ejemplo n.º 28
0
    def update(self):
        if self.item_grab:
            self.item.equanto_pego(self)

        self.move(get_pressed())

        if self.parar == 3:
            if self.item_grab:
                self.current_sprites = self.grab_item_run_sprites
            else:
                self.current_sprites = self.run_sprites

        self.sprite_change += 0.1
        self.parar -= 0.5

        if self.parar <= 0:
            if self.item_grab:
                self.current_sprites = self.grab_item_idle_sprite
            else:
                self.current_sprites = self.idle_sprites

        if self.sprite_change >= len(self.current_sprites):
            self.sprite_change = 0

        self.image = flip(self.current_sprites[int(self.sprite_change)],
                          self.flipped, False)

        self.pos_x = [True, True]
        self.pos_y = [True, True]

        self.colision_check()
Ejemplo n.º 29
0
 def attack(self, x, y):
     try:
         played = False
         if board.board[y][x][-1] == 'attackable':
             i = 0
             board.clear()
             time = clock.tick(30)
             if self.name != 'archer' and self.name != 'skeleton':
                 self.attack_sound.play()
             while i < len(self.attack_anim):
                 time = clock.tick(30) / 1000
                 i = (i + time * 10)
                 if int(i % 12) == 8 and not played and (
                         self.name == 'archer' or self.name == 'skeleton'):
                     self.attack_sound.play()
                     played = True
                 if self.x > x:
                     self.anim = rotate.flip(
                         self.attack_anim[int(i % len(self.attack_anim))],
                         1, 0)
                 else:
                     self.anim = self.attack_anim[int(
                         i % len(self.attack_anim))]
                 draw(self)
             board.board[y][x].hurt(self.pw)
     except TypeError:
         pass
Ejemplo n.º 30
0
 def load(self, spritemanager):
     for fdata in self.raw_frames:
         frame = spritemanager.get(*fdata)
         if self.flip:
             frame = flip(frame, True, False)
         self.frames.append(frame)
     return self
Ejemplo n.º 31
0
    def image(self):
        image = self.assets.images[self.state][self.frame]

        if self.flip < 0:
            return flip(image, True, False)

        return image
Ejemplo n.º 32
0
    def update_anim(self, time):
        self.last_frame_time += time
        if self.anim_jump:
            row = 64
            frames = self.frames['jump']
        elif self.on_walk:
            row = 0
            frames = self.frames['walk']
        else:
            row = 0
            frames = self.frames['stay']

        while self.last_frame_time > self.animation_speed:
            self.current_frame += 1
            self.last_frame_time = self.last_frame_time - self.animation_speed
        if not self.anim_jump:
            self.current_frame = self.current_frame % frames
        else:
            self.current_frame = min(self.current_frame, frames)
        self.surface.fill((0, 0, 0, 0))
        self.surface.blit(
            self.spritesheet,
            (0, 0),
            (
                42*self.current_frame,
                row,
                43, 64
            )
        )
        self.surface = flip(self.surface, self.flipx, False)
Ejemplo n.º 33
0
    def next_frame(self):
        """
        switch to the next image (or to the first if current is last)
        """
        if not self.paused and self.animation:
            self.changes += 1
            if self.changes % self.delay == 0:
                self.frame_number += 1
                if self.frame_number == len(self.frames):
                    self.frame_number = 0

                if self.cached_size != self.size:
                    new_frames = []
                    for frame in self.frames:
                        frame = transform.scale(
                            frame, (self.size.width, self.size.height))
                        new_frames.append(frame)
                    self.frames = new_frames
                    self.cached_size = self.size
                if (self.cached_angle != self.angle) and self.rotations:
                    new_frames = []
                    for frame in self.source_frames:
                        if self.angle == 180:
                            frame = transform.flip(frame, True, False)
                        else:
                            frame = transform.rotate(frame, self.angle)
                        frame = transform.scale(
                            frame, (self.size.width,
                                    self.size.height))  # todo: optimize
                        new_frames.append(frame)
                    self.frames = new_frames
                    self.cached_angle = self.angle

                self.frame = self.frames[self.frame_number]
Ejemplo n.º 34
0
    def draw(self, surface):
        if self.enabled:
            if self.do_flip:
                self.image = flip(self.image, True, False)
                if self.shadow is not None:
                    self.shadow = flip(self.shadow, True, False)
                self.do_flip = False

            pos = [
                self.old_pos[0] - self.offset[0],
                self.old_pos[1] - self.offset[1]
            ]

            if self.shadow is not None:
                surface.blit(self.shadow, (pos[0] + 2, pos[1] + 2))
            surface.blit(self.image, pos)
Ejemplo n.º 35
0
    def __init__(self, game, spawn_x, spawn_y):
        super().__init__(game, spawn_x, spawn_y)

        # properties:
        self.health = 5
        self.radius = 25
        self.create_new_body()

        # animation:
        self.img_l1 = [
            pygame.image.load("data/images/e2/e2l1.png").convert_alpha()
        ]
        self.img_r1 = [
            flip(
                img.load("data/images/e2/e2l1.png").convert_alpha(), True,
                False)
        ]
        self.img_up = [
            pygame.image.load("data/images/e2/e2l1.png").convert_alpha()
        ]
        self.img_down = [
            pygame.image.load("data/images/e2/e2l1.png").convert_alpha()
        ]
        self.img_dead = [
            pygame.image.load("data/images/e2/e2l1.png").convert_alpha()
        ]
        self.img_dead_near = [
            img.load("data/images/e2/e2l1.png").convert_alpha()
        ]
        self.images = self.img_down
Ejemplo n.º 36
0
def get_shadow(target_img, shadow_radius=2, black=255, color_format="RGBA",
                alpha_factor=0.85, decay_mode="exponential", color=(0,0,0),
                sun_angle=30., vertical=True, angle_mode="flip", mode_value=(False, True)):
        r = target_img.get_rect()
        #the shadow will be larger in order to make free space for fadeout.
        r.inflate_ip(2*shadow_radius, 2*shadow_radius)
        img = Surface(r.size)
        img.fill((255, 255, 255, 255))
        img.blit(target_img, (shadow_radius, shadow_radius))
        if sun_angle <= 0.:
            raise Exception("Sun angle must be greater than zero.")
        elif sun_angle != 45. and vertical:
            w, h = img.get_size()
            new_h = h / tan(sun_angle * pi / 180.)
            screen_size = functions.get_screen().get_size()
            new_h = abs(int(min(new_h, max(screen_size))))
            img = scale(img, (w, new_h))
        if angle_mode == "flip":
            img = flip(img, mode_value[0], mode_value[1])
        elif self.angle_mode == "rotate":
            img = rotate(img, mode_value)
        else:
            raise Exception("angle_mode not available: " + str(angle_mode))
        shadow =             _pilshadow(img,
                                        radius=shadow_radius,
                                        black=black,
                                        alpha_factor=alpha_factor,
                                        decay_mode=decay_mode,
                                        color=color)
        #
        W, H = functions.get_screen_size()
        shadow.set_alpha(-1, RLEACCEL)
        return shadow.convert_alpha()
 def render(self):
     if self.robo == 0:
         if self.mdir == "mr": return self.robo0
         else: return transform.flip(self.robo0, True, False)
     elif self.robo == 1:
         if self.mdir == "mr": return self.robo1
         else: return transform.flip(self.robo1, True, False)
     elif self.robo == 2:
         if self.mdir == "mr": return self.robo2
         else: return transform.flip(self.robo2, True, False)
     elif self.robo == 3:
         if self.mdir == "mr": return self.robo3
         else: return transform.flip(self.robo3, True, False)
     elif self.robo >= 4:
         if self.mdir == "mr": return self.robo4
         else: return transform.flip(self.robo4, True, False)
Ejemplo n.º 38
0
    def __init__(self, bullets: Group):
        super().__init__()
        self.bullets = bullets

        # Load images
        img = image.load('images/player03.png').convert_alpha()
        self.imagesN = []
        self.imagesL = []
        self.imagesR = []
        for i in range(4):
            self.imagesN.append(img.subsurface((64 * i, 192, 64, 96)))
        for i in range(4):
            imgL = img.subsurface((64 * i, 288, 64, 96))
            imgR = transform.flip(imgL, True, False)
            self.imagesL.append(imgL)
            self.imagesR.append(imgR)

        self.image = self.imagesN[0]
        self.rect = self.image.get_rect()

        self.slow_effect0 = image.load('images/sloweffect.png').convert_alpha()
        self.slow_effect = self.slow_effect0
        self.slow_rect = self.slow_effect.get_rect()
        self.slow_rect.center = self.rect.center

        self.shoot1_img = img.subsurface((384, 0, 64, 64))

        self.hit_box = Sprite()
        self.hit_box.rect = Rect(0, 0, 4, 4)

        self.reborn()
Ejemplo n.º 39
0
def _resolve_params(data, obj_col):
    """(dict, list) -> NoneType
    For each object in obj_col, resolve the non-type parameters on it, and render the object if applicable."""
    for obj in obj_col:
        if data["img"]:
            obj.img = load_img(data["img"])
        if data["flip"]:
            horiz, vert = None, None
            args = data["flip"].strip("()").split(",")
            if args[0] == "false":
                horiz = False
            else:
                horiz = True
            if args[1] == "false":
                vert = False
            else:
                vert = True

            obj.img = transform.flip(obj.img, horiz, vert)
        if data["rotate"]:
            obj.img = transform.rotate(obj.img, int(data["rotate"].split("=")[-1]))
        if data["scale"]:
            obj.img = transform.scale(obj.img, tuple(int(i) for i in data["scale"].strip("()").split(",")))

        obj.render(screen, update_queue)
Ejemplo n.º 40
0
    def animate(self, pressed_keys: Sequence) -> None:
        # region DocString
        """
        Method to animate the player

        ### Arguments
            `pressed_keys {Sequence}`:
                `summary`: a dictionary with the status of all keys
        """
        # endregion

        # region Set correct animation state

        if self.state is not AS.ATTACK:
            self.setState(AS.IDLE)
            if self.vel_y < 0:
                self.setState(AS.JUMPDOWN)
            elif self.vel_y > 0:
                self.setState(AS.JUMPUP)
            else:
                if pressed_keys[K_LEFT] or pressed_keys[K_RIGHT]:
                    self.setState(AS.MOVE)

        # endregion

        # region Execute animation

        if self.current_anim_frame == self.animation_frames:
            self.current_anim_frame = 0
            self.image = (self.anims[self.state].next() if self.facing else
                          flip(self.anims[self.state].next(), True, False))
        self.current_anim_frame += 1
Ejemplo n.º 41
0
    def create_pipe(self):

        opennig_size_scale = random.randint(3, 6) * 0.40 * self.difficulty
        openning_y_middle =  random.normalvariate(GlobalVars.get_world_size().y / 2, sigma= 0.4)
        openning_y_upper = openning_y_middle - opennig_size_scale
        opennig_y_lower = openning_y_middle + opennig_size_scale
        self.last_created = (self.last_created + 1 ) % 2
        
        print("Middle: " + str(openning_y_middle), "Upper: " + str(openning_y_upper), "Lower:" + str(opennig_y_lower) )
        
        bottom_pipe =  Pipe(
                self.image,
                Vector2(
                    GlobalVars.get_world_size().x , 
                    opennig_y_lower),
                Rect(self.texture_offset, self.texture_size)
            ) 
            
        up_pipe =  Pipe(
                flip(self.image, False, True),
                Vector2(GlobalVars.get_world_size().x , openning_y_upper - (GlobalVars.get_world_size().y / 2)),
                Rect(self.texture_offset, self.texture_size)
            )

        return (up_pipe, bottom_pipe)
 def get_environment_wind_stream_sprites(
     cls, size: (int, int)) -> {Enum, List[Surface]}:
     sprites = {
         WindDirection.UP: [
             cls.get_image(path.join("props", "wind_stream_1.png")),
             cls.get_image(path.join("props", "wind_stream_2.png"))
         ],
         WindDirection.DOWN: [
             transform.flip(e, False, True) for e in [
                 cls.get_image(path.join("props", "wind_stream_1.png")),
                 cls.get_image(path.join("props", "wind_stream_2.png"))
             ]
         ],
         WindDirection.LEFT: [
             transform.rotate(e, -90) for e in [
                 cls.get_image(path.join("props", "wind_stream_1.png")),
                 cls.get_image(path.join("props", "wind_stream_2.png"))
             ]
         ],
         WindDirection.RIGHT: [
             transform.rotate(e, 90) for e in [
                 cls.get_image(path.join("props", "wind_stream_1.png")),
                 cls.get_image(path.join("props", "wind_stream_2.png"))
             ]
         ],
     }
     for key in sprites.keys():
         sprites[key] = [
             scaling_repeat(sprite, size) for sprite in sprites.get(key)
         ]
     return sprites
Ejemplo n.º 43
0
 def _get_raw_shadow(self):
     target_img = self.target.get_image(self.capture_state)
     r = target_img.get_rect()
     #the shadow will be larger in order to make free space for fadeout.
     r.inflate_ip(2 * self.shadow_radius, 2 * self.shadow_radius)
     img = Surface(r.size)
     img.fill((255, 255, 255, 255))
     img.blit(target_img, (self.shadow_radius, self.shadow_radius))
     if self.sun_angle <= 0.:
         raise Exception("Sun angle must be greater than zero.")
     elif self.sun_angle != 45. and self.vertical:
         w, h = img.get_size()
         new_h = h / tan(self.sun_angle * pi / 180.)
         screen_size = functions.get_screen().get_size()
         new_h = abs(int(min(new_h, max(screen_size))))
         img = scale(img, (w, new_h))
     if self.angle_mode == "flip":
         img = flip(img, self.mode_value[0], self.mode_value[1])
     elif self.angle_mode == "rotate":
         img = rotate(img, self.mode_value)
     else:
         raise Exception("angle_mode not available: " +
                         str(self.angle_mode))
     shadow = pilgraphics.get_shadow(img,
                                     radius=self.shadow_radius,
                                     black=self.black,
                                     alpha_factor=self.alpha_factor,
                                     decay_mode=self.decay_mode,
                                     color=self.color)
     return shadow
Ejemplo n.º 44
0
def command_vert(new_img, screen, file, num_imgs, rect):
    "flip vertically"
    wait_cursor()
    start = start_timer()
    new_img = flip(new_img, 90, 90)
    my_update_screen(new_img, screen, rect, file, num_imgs, check_timer(start))
    normal_cursor()
    return (new_img, new_img, rect)
Ejemplo n.º 45
0
	def draw(self, screen, pos=(0,0)):
		frame = transform.flip(
			self.currframe(),
			self.flipx,
			self.flipy
		)

		screen.blit(frame, pos)
Ejemplo n.º 46
0
 def get_mirrored_version(self):
     """
     Utility method to get the part with mirrored image and attachment points
     :return: Mirrored AttachmentPart object
     """
     mirrored_image = flip(self.image, True, False)
     mirrored_point = (abs(self.width - self.attachment_point[0]), self.attachment_point[1])
     return AttachmentPart(mirrored_image, mirrored_point)
Ejemplo n.º 47
0
def command_horiz(new_img, screen, file, num_imgs, rect):
    "flip horizontally (mirror)"
    wait_cursor()
    start = start_timer()
    new_img = flip(new_img, 90, 0)
    my_update_screen(new_img, screen, rect, file, num_imgs, check_timer(start))
    normal_cursor()
    return (new_img, new_img, rect)
 def render(self):
     global tigeraniindex,tigerframetracker, stonerender
     stonerender = self.stone.render()
     tigerframetracker +=1
     if tigeraniindex > len(self.animation)-2:
         tigeraniindex = -1
     if tigerframetracker % 21 == 0:
         tigeraniindex += 1
     if tigerframetracker > 500: tigerframetracker = 0
     if self.mdir == "ml":
         return self.animation[tigeraniindex]
     elif self.mdir == "mr":
         return transform.flip(self.animation[tigeraniindex], True, False)
     elif self.mdir == "l":
         return self.animation[0]
     elif self.mdir == "r":
         return transform.flip(self.animation[0], True, False)
Ejemplo n.º 49
0
 def render_footer(self,screen):
     x,y = self.position
     cwidth,cheight = self.content_size()
     y += self.headheight+cheight
     ew = self.foot_end.get_width()
     lw = self.bottom_line.get_width()
     screen.blit(self.foot_end,(x,y))
     screen.blit(self.bottom_line,(x+ew,y))
     screen.blit(flip(self.foot_end,True,False),(x+ew+lw,y))
Ejemplo n.º 50
0
 def generate_jumping_dct(self, pid):
     """Genrerate animations with rotations and flipping."""
     dct = {}
     # Raw
     diag_image = self.resource.image.get(self.diag_names[pid])
     perp_image = self.resource.image.get(self.perp_names[pid])
     # Rotate
     for r in (0, 3):
         dct[self.perp_dir[r]] = transform.rotate(perp_image, r*90)
         dct[self.diag_dir[r]] = transform.rotate(diag_image, r*90)
     if pid == 2:
         dct[self.perp_dir[3]] = transform.flip(dct[self.perp_dir[3]], 0, 1)
     dct[self.diag_dir[1]] = transform.flip(dct[self.diag_dir[0]], 1, 0)
     dct[self.diag_dir[2]] = transform.flip(dct[self.diag_dir[3]], 1, 0)
     dct[self.perp_dir[1]] = transform.flip(dct[self.perp_dir[3]], 1, 0)
     dct[self.perp_dir[2]] = transform.rotate(perp_image, 180)
     # Return
     return dct
 def __init__(self, images, startx, starty):
     self.img = transform.scale(images, (130/3,100/3))
     self.dir = random.randint(0,1)
     self.x, self.y = startx, starty
     if self.dir == 0:
         pass
     else:
         self.img = transform.flip(self.img, True, False)
     self.y = 430
Ejemplo n.º 52
0
	def animate(self, game):
		
		if game.player.rect.x < self.rect.x and self.curDir == 1: 
			img = game.images[self.sprname][0]
			self.setimage(img)
			self.curDir *= -1
		if game.player.rect.x > self.rect.x and self.curDir != 1:
			img = transform.flip(game.images[self.sprname][0], True, False)
			self.setimage(img)
			self.curDir *= -1
Ejemplo n.º 53
0
 def set_frame(self, frame):
     self.animation_timer, frame = frame
     new_surf, axis = frame
     self.axis = pymunk.Vec2d(axis)
     if self.flip:
         w, h = new_surf.get_size()
         new_surf = flip(new_surf, 1, 0)
         self.axis.x = -self.axis.x
     self.original_surface = new_surf
     self.dirty = True
Ejemplo n.º 54
0
 def render_header(self,screen):
     ew = self.head_end.get_width()
     lw = self.top_line.get_width()
     mw = self.head_mid.get_width()
     x,y = self.position
     screen.blit(self.head_end,(x,y))
     screen.blit(self.top_line,(x+ew,y))
     screen.blit(self.head_mid,(x+ew+lw,y))
     screen.blit(self.top_line,(x+ew+lw+mw,y))
     screen.blit(flip(self.head_end,True,False),(x+ew+2*lw+mw,y))
Ejemplo n.º 55
0
    def flip(self, is_horizontal=False, is_vertical=False):
        """Flip this graphic horizontally, vertically, or both.

        Args:
            is_horizontal: A Boolean indicating whether to flip the
                Graphic's image horizontally.
            is_vertical: A Boolean indicating whether to flip the
                Graphic's image vertically.
        """
        self.image = transform.flip(self.image, is_horizontal,
                                    is_vertical)
Ejemplo n.º 56
0
    def scale_image(src_image, x_scale, y_scale):

        # flip the image if the scales are negative
        invert_x = x_scale < 0
        invert_y = y_scale < 0
        dst_image = transform.flip(src_image, invert_x, invert_y)

        # find the new dimensions of scaled image
        new_width = src_image.get_width() * abs(x_scale)
        new_height = src_image.get_height() * abs(y_scale)
        return transform.scale(dst_image, (int(new_width), int(new_height)))
Ejemplo n.º 57
0
    def _updateCache(self):
        angle = self.getOrientation()

        if self.curAnimation == None:
            self.play(self.default)

        if not angle == self._prevAngle:
            self.curImage = self.curAnimation.getImage(self.curFrame, angle)
            self._rect = self.curImage.get_rect().move(self.axis)
            if self.flip: self.curImage = flip(self.curImage, 1, 0)

        elif not self.curFrame == self._prevFrame:
            self.curImage = self.curAnimation.getImage(self.curFrame, angle) 
            self._rect = self.curImage.get_rect().move(self.axis)
            if self.flip: self.curImage = flip(self.curImage, 1, 0)

        elif self.curImage == None:
            self.curImage = self.curAnimation.getImage(self.curFrame, angle) 
            self._rect = self.curImage.get_rect().move(self.axis)
            if self.flip: self.curImage = flip(self.curImage, 1, 0)
Ejemplo n.º 58
0
def handle_transformation(tile, flags):
    if flags:
        fx = flags & TRANS_FLIPX == TRANS_FLIPX
        fy = flags & TRANS_FLIPY == TRANS_FLIPY
        r = flags & TRANS_ROT == TRANS_ROT

        newtile = None
        if r:
            # not sure why the flip is required...but it is.
            newtile = rotate(tile, 270)
            newtile = flip(newtile, 1, 0)

            if fx or fy:
                newtile = flip(newtile, fx, fy)

        elif fx or fy:
            newtile = flip(tile, fx, fy)

        return newtile

    else:
        return tile
Ejemplo n.º 59
0
    def __init__(self, spriteName):
        if spriteName is None:
            # Eventually gameObject should compose a drawing component
            # once we stop using pygame's collisions.
            # For now we give it a blank surface instead.
            surf = Surface((0, 0)).convert_alpha()
            self.visible = False
        else:

            surf = IMG.load(spriteName)
            self.visible = True
        # List with [1] = right-facing and [-1] = left-facing.
        self.frames = [None, FL.loadFrame(surf),
                       FL.loadFrame(flip(surf, True, False))]
Ejemplo n.º 60
0
    def attack_action(self):
        # animation
        self.fr += 1
        cur_frame = self.fr % 4
        if self.side > 0:
            self.scrn.blit(flip(self.enemy_attack[cur_frame], True, False), self.rect)
        else:
            self.scrn.blit(self.enemy_attack[cur_frame], self.rect)

        hit = randint(0, 3)
        if hit == 0:
            return self.attack
        else:
            return 0