Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In Pygame, sprites are very minimal. They consist of two main parts: an image and a rect. The image is what is displayed on the screen and the rect is used for positioning and collision detection. Here's an example of how your grass image could be made into a Sprite:</p> <pre><code>grass = pygame.image.load("grass.png") grass = grass.convert_alpha() grassSprite = new pygame.sprite.Sprite() grassSprite.image = grass #This automatically sets the rect to be the same size as your image. grassSprite.rect = grass.get_rect() </code></pre> <p>Sprites are pretty pointless on their own, since you can always keep track of images and positions yourself. The advantage is in using groups. Here's an example of how a group might be used:</p> <pre><code>myGroup = pygame.sprite.Group() myGroup.add([sprite1,sprite2,sprite3]) myGroup.update() myGroup.draw() if myGroup.has(sprite2): myGroup.remove(sprite2) </code></pre> <p>This code creates a group, adds three sprites to the group, updates the sprites, draws them, checks to see if sprite2 is in the group, then removes the sprite. It is mostly straight forward, but there are some things to note: 1) Group.add() can take either a single sprite or any iterable collection of sprites, such as a list or a tuple. 2) Group.update() calls the update methods of all the Sprites it contains. Pygame's Sprite doesn't do anything when its update method is called; however, if you make a subclass of Sprite, you can override the update method to make it do something. 3) Group.draw() blits the images of all the Group's Sprites to the screen at the x and y positions of their rects. If you want to move a sprite, you change its rect's x and y positions like so: <code>mySprite.rect.x = 4</code> or <code>mySprite.rect.y -= 7</code></p> <p>One way to use Groups is to create a different group for each level. Then call the update and draw method of whichever group represents the current level. Since nothing will happen or be displayed unless those methods are called, all other levels will remain "paused" until you switch back to them. Here's an example:</p> <pre><code>levels = [pygame.sprite.Group(),pygame.sprite.Group(),pygame.sprite.Group()] levels[0].add(listOfLevel0Sprites) levels[1].add(listOfLevel1Sprites) levels[2].add(listOfLevel2Sprites) currentLevel = 0 while(True): levels[currentLevel].update() levels[currentLevel].draw() </code></pre> <p>I know this question is somewhat old, but I hope you still find it helpful!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload