简体   繁体   中英

Pygame/Python For loop only blitting last element inside sprite list

here's my main problem and a brief explanation of what I have: I have a class named Cat, and a list of them called Cats. After some random condition I want a new one to be added to a random part of the screen.

Now here's the thing, if I paint the screen white and then I use a for loop to blit every element, the for loop will only blit the last element after filing the screen.

screen = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT),0,32)
catsprite = pygame.image.load('catcit.png')
Cats = []
while True:
    screen.fill(WHITE)
    if Catspawnlimit == 0:
        if random.randint(0,50) < 10: #deciding whether a new cat is created
            newCat = Cat()     

            Cats.append(newCat) #Adding newCat to the Cats list
            Catspawnlimit = 0
    Catspawnlimit += 1

    for kitty in Cats:
        screen.blit(kitty.surface, kitty.catRect)

    pygame.display.update()

And here's the Cat class

class Cat(object):

sizeX = 50
sizeY = 100
catRect = catsprite.get_rect() 
surface = pygame.transform.scale(catsprite, (sizeX, sizeY))

def __init__(self):
    self.posX = random.randint(0,WINDOWWIDTH/2 - self.sizeX)
    self.posY = random.randint(0, WINDOWHEIGHT-self.sizeY)
    self.catRect.topleft= (self.posX,self.posY)

Thank you.

You create a class attribute catRect which is the same for each cat object. In your init function, you move the catRect to have the topleft at the new position.

To fix this make another rectangle that will be copied from the class one.

Another tip - do create new variables to store position if you already have a place to store them - rectangle. With those two in mind here is the relevant code:

def __init__(self):
    posX = random.randint(0,WINDOWWIDTH/2 - self.sizeX)
    posY = random.randint(0, WINDOWHEIGHT-self.sizeY)    
    self.rect = self.catRect.copy()
    self.rect.topleft = (posX,posY)

Don't forget to change your draw code to use the rect instead of the catRect .

for kitty in Cats:
    screen.blit(kitty.surface, kitty.rect)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM