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

Re: [pygame] newbie question--> rendeing order



enrike@ixi-software.net wrote:
I was wondering if there is some way to change the rendering order of a group of sprites "on the fly". I want to bring the clicked sprite above the others.
So far i have manage to do it by storing a reference of the sporites in a list, change the order of that list, remove all objects from the rendering group and adding the whole list back again to the group.
it isn't hard to write new sprite groups that have different 'draw' functions. but your problem will still be ordering the list of sprites.

the standard sprite groups use dictionaries internally for storing the sprites. this gives them several bonuses, like very fast searching and adding/removing of sprites. unfortunately it also means no sorting.

if we're talking less than 100 or so sprites total, i believe sorting the list everytime we draw would be fast enough (although not totally efficient). if all sprites have a "pickorder" field with ascending numbers, the following sprite group would do the rendering for you..



#note, this is largely 'cut&paste' from the RenderUpdates code
#note, all the complexity from this code comes from managing the
# update rectangles

class RenderPickOrder(pygame.sprite.RenderUpdates):
"""render sprites in the order of their 'pickorder' field"""
def draw(self, surface):
dirty = self.lostsprites
self.lostsprites = []
allsprites = self.spritedict.sprites()
allsprites.sort(lambda a,b: cmp(a[0].pickorder, b[0].pickorder))
for s,r in allsprites:
newrect = surface.blit(s.image, s.rect)
if r is 0:
dirty.append(newrect)
else:
if newrect.colliderect(r):
dirty.append(newrect.union(r))
else:
dirty.append(newrect)
dirty.append(r)
self.spritedict[s] = newrect
return dirty



when you need to press more performance out. i believe you will need to create a new type of sprite group that doesn't use a dictionary. your best bet is probable a regular list, or a priority queue container (there are several in the asdn cookbook).

check the source of the pygame.sprite module, it has extra documentation for creating your own classes, but it's easiest to carve and paste what you need.
http://cvs.seul.org/cgi-bin/cvsweb-1.80.cgi/games/pygame/lib/sprite.py?rev=1.22