[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [pygame] y-Sorted RenderGroup



On Tue, Jun 04, 2002 at 10:52:02AM -0700, steve wrote:
>    I've developed a RenderUpdate group that sorts it's sprites on their 
> y position, useful for things like Japaneese style RPGs where sprites 
> closer to the bottom of the screen are drawn first, and sprites near the 
> top of the screen are drawn last.

Looks like an addition to the PCR to me.

>    As you can see, I sort when I paint the sprites, because Python's 
> dictionaries return their items in random order, sorting the dictionary 
> would be pointless (you can't anyways).  After I sort, I paint the 
> sorted list of sprites instead of spritedict.items(), #3 below.  I use 
> my own sorting routine called y_sort(a, b).

Ever got into lambda functions? Your sort routine can be rewritten like
this:

# y.sort(y_sort)
y.sort(lambda a,b: cmp(a[0].rect.top, b[0].rect.top))

It's nice, it's small and it's usually faster. I'm not exactly sure
how big the overhead of the cmp() call is, but you could also eliminate
that one by calling:

y.sort(lambda a,b: ((a[0].rect.top > b[0].rect.top)<<1)-1)

This one doesn't work exactly in case the two tops are equal.. but then
again order is irrelevant (to the sort) if they're exactly atop each other.

>    My question is, is creating an iternal list inside draw(), "y" in #1 
> below, the right way of doing this?  Since draw is called so frequently, 
> should I worry about garbage, and make this sorted list a class variable 
> (self.y)?  Is there a better way of doing this within the existing 
> Sprite classes, or am I on track here?

The problem with the class variable is to keep it up2date when you change
the group. I've tested a little (very little actually :) with your script
and found that it doesn't make much of a difference unless you expand the
group to several hundred sprites. And even then the difference is almost
neglectable. I wouldn't say it's worth the effort of keeping the group
updated.
I'm not sure if you could get an improvement by keeping an internal flag
for the sorting. As you sort all your sprites each time draw() is called
this might be an overhead one could eliminate by keeping a flag that
triggers the sorting only when a sprite has actually moved in the y
direction. But then again I don't know how the sort routine works and how
much work is actually done in case of an already sorted list. I think it'll
be just another minor improvement only relevant to a group with hundreds
of sprites.

hth,
-- 
Raiser, Frank aka CrashChaos
IRC: irc.openprojects.net #pygame
____________________________________
pygame mailing list
pygame-users@seul.org
http://pygame.seul.org