Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

python - How to use sprite groups in pygame

So I've gotten to the point in my program where I need to create a group for some sprites that the player can collide with without dying (like some other sprites I may have on screen).

I've scoured Google but it appears that the official pygame documentation is useless and/or hard to comprehend. I'm looking for just a wee bit of help from anyone who knows a bit about this.

First, I need to find out how to create a group. Does it go in the initial game setup?

Then adding a sprite to a group upon its creation. The pygame site has this to say on the subject:

Sprite.add(*groups)

So... how does one use this? Let's say I have an sprite named gem. I need to add gem to the gems group. Is it:

gem = Sprite.add(gems)

I doubt it, but without any examples to go off of on the site, I am at a loss.

Furthermore, I would love to be able to edit attributes for a certain group. Is this done by defining a group like I would a class? Or is it something I define within the definition for the existing sprite, but with an 'if sprite in group'?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To answer your first question; to create a group you would do something like this:

gems = pygame.sprite.Group()

Then to add a sprite:

gems.add(gem)

Regarding the attributes for the group you'd like to edit it depends what they are. For example you could define something like this to indicate the direction of the group:

gems.direction = 'up'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...