[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] optimization for my sprite rendering



I'm fairly new to both pygame and python, and I was wondering if someone could help a newbie optimize some code I inherited.  

Here's some background info: there are foreground sprites that pop up and go away, and there is an image loaded into the background sprite that changes infrequently (not more than every 5 seconds).  The problem was, the old code updated the entire screen on every iteration, so I broke it apart and only the foreground elements are updated unless the background image changes.  

Yay, it's all fine, except that the framerate still sucks (85-120ms per iteration of the main loop).  If I take out the line in the foreground loop (below) where it draws the background sprite onto the mainscreen, everything under the fg sprites ends up black (the surface self.background is all black - but... it takes an acceptable 30ms to run the loop).  I'd love to just update the areas where the foreground rects overlap the background, but I don't know how (do I need to create a new sprite class?).  I've tried something like: bg_sprite.draw(self.background), but I get the same problem with the background not being redrawn properly.

Sorry for the verbose post (but it's late and I've been working on this for too long) and thanks for any help you can give me in advance.


Chris 


def update(self, fg_only=False):
"Update the screen"

    if fg_only:
        self.foregroundsprites.clear(self.mainscreen, self.background)
            self.foregroundsprites.update()

        self.backgroundsprites.draw(self.mainscreen)
        changed_rects=self.foregroundsprites.draw(self.mainscreen)
    else:
        self.backgroundsprites.clear(self.mainscreen, self.background)
        self.foregroundsprites.clear(self.mainscreen, self.background)
        self.backgroundsprites.update()
            self.foregroundsprites.update()

        changed_rects=self.backgroundsprites.draw(self.mainscreen) + self.foregroundsprites.draw(self.mainscreen)

        pygame.display.update(changed_rects)


def set_bg_image(self, imagefile, x=0, y=0):
    try:
        self.bg_sprite.load_image(imagefile, x, y)
        self.bg_sprite.draw(self.background)
        self.mainscreen.blit(self.background, (0,0))
        pygame.display.flip()

        except:
            return 0
        return 1



__________________________________________________________________
Thank you for using Netscape.