Search code examples
pythonpygamepygame-surface

Pygame. How Do I Resize My Fish Player Image Everytime It Eats A Fish?


I am trying to make my fish bigger everytime it eats a fish but I am not sure why its not working this is what I did

everything else works but my playerman height or width is not adding up video

# our main loop
runninggame = True
while runninggame:
    clock.tick(fps)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runninggame = False

         #[...........]
    for blac in blacs:
        if playerman.rect.colliderect(blac.rect):
            playerman.width += 10
            playerman.height += 10
            blac.x = 880

my full code: https://pastebin.com/iL5h4fst


Solution

  • You need to scale all the images of the player with pygame.transform.smoothscale(), when the size is inreased:

    if playerman.rect.colliderect(blac.rect):
        playerman.width += 10
        playerman.height += 10
        blac.x = 880
        playerman.right = [pygame.transform.scale(image, (playerman.width,playerman.height)) for image in playerman.right]
        playerman.left = [pygame.transform.scale(image, (playerman.width,playerman.height)) for image in playerman.left]
        playerman.rect = pygame.Rect(playerman.x, playerman.y, playerman.width, playerman.height)
    

    The attributes self.width and self.height have to be initialized by the down scaled size of the images (image.get_width()//8 respectively image.get_height()//8)

    As the player grows, you'll need to multiply the size of the player by a scale factor to keep the aspect ratio. When using pygame.transform.scale, round the width and height to integral numbers:

    class player:
        def __init__(self,x,y,height,width,color):
            # [...]
    
            self.right_original = [pygame.image.load("r" + str(i) + ".png") for i in range(1, 13)]
            self.left_original = [pygame.image.load("l" + str(i) + ".png") for i in range(1, 13)]
            self.width = self.right_original[0].get_width() / 8
            self.height = self.right_original[0].get_height() / 8
            self.scale_images()
    
            # [...]
    
        def scale_images(self):
            w, h = round(self.width), round(self.height)
            self.right = [pygame.transform.scale(image, (w, h)) for image in self.right_original]
            self.left = [pygame.transform.scale(image, (w, h)) for image in self.left_original]
            self.rect = pygame.Rect(self.x, self.y, w, h)
    
        def collide(self, other_rect):
            return self.rect.colliderect(other_rect)
    
        def grow(self, scale):
            self.width *= scale
            self.height *= scale
            self.scale_images()
    
    for blac in blacs:
        if playerman.collide(blac):
            blac.x = 880
            playerman.grow(1.1)