Increasing Pygame Image size after collision?

633 views Asked by At

So I'm just learning how to work with classes and getting them to work between each different class. I'm trying to design a game where the user moves around and picks up food and each time the user picks up a piece of food the size of the character increases. I've done something similar before but now that there are classes involved I seem to have a hard time finding which class this should be part of. I added within the sprite update method that if it collides with a cherry then the size of the player should increase by 5 pixels each time. using the code :

self.Player.surface = pygame.transform.scale(self.Player.surface, (pwidth+5, pheight+5))
self.rect = self.Player.surface.get_rect()

Each time the game runs the player size doesn't change and for some reason the game no longer ends after the player has eaten a certain amount of cherries so I was just wondering if I was using a wrong method of changing the size of the player perhaps there may be an easier way to do so? Heres the rest of the code incase it helps at all.

import pygame, glob, random, time
from pygame.locals import *
from LabelClass import *

# CONSTANTS
WIDTH  = 400  # Window width
HEIGHT = 400  # Window height
BLACK  = (0,0,0) # Colors
WHITE  = (255,255,255)
BACKGR = BLACK  # Background Color
FOREGR = WHITE  # Foreground Color
FPS    = 40 # Frames per second
pwidth = 40
pheight = 40

class Food:
    def __init__(self,screen,centerx,centery):
        self.screen = screen
        self.surface = pygame.image.load('cherry.png')
        self.rect = self.surface.get_rect()
        self.rect.centerx = centerx
        self.rect.centery = centery

    def draw(self):
        self.screen.blit(self.surface,self.rect)
        #pygame.display.update([self.rect])


class Player:

    def __init__(self, screen, centerx, 
      centery, speed, backcolor):
        self.surface = pygame.image.load('player.png')
        self.rect = self.surface.get_rect()
        self.rect.centerx = centerx
        self.rect.centery = centery
        self.speed = speed
        self.screen = screen
        self.backcolor = backcolor

        self.dir = ''

    def draw(self):
        self.screen.blit(self.surface,self.rect)
        #pygame.display.update([self.rect])


    def move(self):
        if self.dir != '':
            if self.dir == 'd' and self.rect.bottom < HEIGHT:
                self.rect.top += self.speed
            if self.dir == 'u' and self.rect.top > 0:
                self.rect.top -= self.speed
            if self.dir == 'l' and self.rect.left > 0:
                self.rect.left -= self.speed
            if self.dir == 'r' and self.rect.right < WIDTH:
                self.rect.right += self.speed

    def jump(self,top,left):
        self.rect.top = top
        self.rect.left = left

class SpritesGame:

    def __init__(self,screen):

        self.screen = screen
        screen.fill(BLACK)
        pygame.display.update()
        music_file = getRandomMusic()
        pygame.mixer.music.load(music_file)
        pygame.mixer.music.play(-1,0.0)
        self.music = True
        self.Foods = [ ]
        self.Eaten = 0



        for i in range(20):
            self.Foods.append(
              Food(self.screen,
              WIDTH*random.randint(1,9)//10,
              HEIGHT*random.randint(1,9)//10))
        for f in self.Foods:
            f.draw()
        self.Player = Player(screen,WIDTH//2,HEIGHT//2,6,BLACK)
        self.PickUpSound = pygame.mixer.Sound('pickup.wav')
        self.PlaySound = True
        self.startTime = time.clock()
        self.endTime = -1
        self.Won = False

    def update(self):
        self.screen.fill(BLACK)
        pickedUp = False
        for f in self.Foods[:]:

            if self.Player.rect.colliderect(f.rect):
                self.Foods.remove(f)
                self.Foods.append(Food(self.screen,WIDTH*random.randint(1,9)//10,HEIGHT*random.randint(1,9)//10))
                pickedUp = True
                self.Eaten += 1

                self.Player.surface = pygame.transform.scale(self.Player.surface, (pwidth+5, pheight+5))
                self.rect = self.Player.surface.get_rect()
                #self.rect.center = center



                print self.Eaten





        if pickedUp and self.PlaySound:
            self.PickUpSound.play()
        for f in self.Foods:
            f.draw()
        if self.Eaten == 40:
            self.Won = True
            self.endTime = time.clock()
        self.Player.move()
        self.Player.draw()
        pygame.display.update()

    def toggleMusic(self):
        self.music = not self.music
        if self.music:
            pygame.mixer.music.play(-1,0.0)
        else:
            pygame.mixer.music.stop()


    def run(self):
        stop = False
        while not stop:
            for event in pygame.event.get():
                if event.type == QUIT:
                    stop = True
                if event.type == KEYDOWN: # Keeps moving as long as key down
                    if event.key == K_LEFT or event.key == ord('a'):
                        self.Player.dir = 'l'
                    if event.key == K_RIGHT or event.key == ord('d'):
                        self.Player.dir = 'r'
                    if event.key == K_UP or event.key == ord('w'):
                        self.Player.dir = 'u'
                    if event.key == K_DOWN or event.key == ord('s'):                     
                        self.Player.dir = 'd'
                if event.type == KEYUP:
                    if event.key == ord('q'):
                        stop = True
                    if event.key == K_ESCAPE:
                        stop = True
                    if event.key == K_LEFT or event.key == ord('a'): # End repetition.
                        self.Player.dir = ''
                    if event.key == K_RIGHT or event.key == ord('d'):
                        self.Player.dir = ''
                    if event.key == K_UP or event.key == ord('w'):
                        self.Player.dir = ''
                    if event.key == K_DOWN or event.key == ord('s'):
                        self.Player.dir = ''
                    if event.key == ord('x'):
                        top = random.randint(0,
                          HEIGHT - self.Player.rect.height)
                        left = random.randint(0,
                          WIDTH - self.Player.rect.width)
                        self.Player.jump(top,left)
                    if event.key == ord('m'):
                        self.toggleMusic()
                    if event.key == ord('p'):
                        self.PlaySound = not self.PlaySound 
            mainClock.tick(FPS)
            self.update()
            if self.Won:
                stop = True # END OF WHILE
        if self.Won:
            self.screen.fill(BLACK)
            pygame.display.update()
            msg = (str((int(self.endTime)
                       -int(self.startTime)))
                    +" seconds to finish. Hit Q.")
            L2 = Label(display,WIDTH//2,HEIGHT*7//8,26,msg,WHITE,BLACK)
            L2.draw()
            stop = False
            while not stop:
               for event in pygame.event.get():
                   if event.type == KEYUP:
                       if event.key == ord('q'):
                           stop = True
        pygame.event.get()
        pygame.mixer.music.stop()

def getRandomMusic():
    mfiles = glob.glob("*.wav")
    mfiles.append(glob.glob("*.mid"))
    r = random.randint(0,len(mfiles)-1)
    return mfiles[r]

def OpeningScreen(screen):
    screen.fill(BLACK)
    pygame.display.update()
    L1 = Label(display,WIDTH//2,HEIGHT*7//8,26,"Hit Q to Quit, P to Play.",WHITE, BLACK)
    L1.draw()

# Properly initiate pygame
pygame.init()
# pygame.key.set_repeat(INT,INT)
# Set the clock up
mainClock = pygame.time.Clock()

# Initialize Display
display = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Sprites and Sounds V06')

OpeningScreen(display)

stop = False
while not stop:
    for event in pygame.event.get():
        if event.type == QUIT:
            stop = True
        if event.type == KEYUP:
            if event.key == ord('p'):
                game = SpritesGame(display)
                game.run()
                OpeningScreen(display)
            if event.key == ord('q'):
                stop = True


pygame.quit()
1

There are 1 answers

2
KSab On

Surface.get_rect() will always return a rect starting at (0,0), and you also are modifying SpritesGame.rect. I think you should change

self.rect = self.Player.surface.get_rect()

to

self.Player.rect.inflate_ip(5, 5)