For my project i am recreating donkey kong in pygame, and ive got to the stage where i need sprites for my ladders, platforms and my character, but im unsure how to make sprites and then use these in pygame.
-
This question seems a bit too broad - you might want to narrow it down to a specific problem you're facing currently. See [how to ask a good question](https://stackoverflow.com/help/how-to-ask) – vekerdyb Jul 29 '21 at 08:31
1 Answers
Here is a very basic example for using a Sprite in pygame (see also Sprite):
repl.it/@Rabbid76/PyGame-Sprite
import pygame
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self, center_pos, image):
super().__init__()
self.image = image
self.rect = self.image.get_rect(center = center_pos)
def update(self, surf):
keys = pygame.key.get_pressed()
self.rect.x += (keys[pygame.K_d]-keys[pygame.K_a]) * 5
self.rect.y += (keys[pygame.K_s]-keys[pygame.K_w]) * 5
self.rect.clamp_ip(surf.get_rect())
player_surf = pygame.image.load('Bird64.png').convert_alpha()
player = Player(window.get_rect().center, player_surf)
all_sprites = pygame.sprite.Group([player])
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
all_sprites.update(window)
window.fill(0)
all_sprites.draw(window)
pygame.display.flip()
pygame.quit()
exit()
An image can be loaded to a pygame.Surface
object with pygame.image.load
. See How to draw images and sprites in pygame?.
Pygame uses pygame.sprite.Sprite
objects and pygame.sprite.Group
objects to manage Sprites. pygame.sprite.Group.draw()
and pygame.sprite.Group.update()
are methods which are provided by pygame.sprite.Group
.
The former delegates the to the update
method of the contained pygame.sprite.Sprite
s - you have to implement the method. See pygame.sprite.Group.update()
:
Calls the
update()
method on all Sprites in the Group [...]
The later uses the image
and rect
attributes of the contained pygame.sprite.Sprite
s to draw the objects - you have to ensure that the pygame.sprite.Sprite
s have the required attributes. See pygame.sprite.Group.draw()
:
Draws the contained Sprites to the Surface argument. This uses the
Sprite.image
attribute for the source surface, andSprite.rect
. [...]

- 202,892
- 27
- 131
- 174