Search code examples
pythonpygamesprite

Problems generating Player sprite image with pygame


I am trying to run the following pytho pygame code from this tutorial https://opensource.com/article/17/12/game-python-add-a-player. After correcting the indentation as I posted on this question 'Player' object has no attribute 'rect I tried to run the python code below followed by the file tree in the local folder called images as shown below. But I can't see hero.png in the game. I try also Pygame player sprite not appearing .

folder images:

stage.png: https://i.sstatic.net/Tmyok.jpg hero.png: https://opengameart.org/sites/default/files/spellun-sprite.png

My code:

import pygame  # load pygame keywords
import sys     # let  python use your file system
import os      # help python identify your OS

'''
Create class for player
'''

class Player(pygame.sprite.Sprite):
    def __init__(self):
      pygame.sprite.Sprite.__init__(self)
      self.images = []
      img = pygame.image.load(os.path.join('images','hero.png')).convert()
      self.images.append(img)
      self.image = self.images[0]
      self.rect.x = 40
      self.rect.y = 30
#cria a classe para o player

'''
Objects
'''

# put Python classes and functions here

'''
Setup
'''
worldx = 260
worldy = 220

fps   = 40  # frame rate
ani   = 4   # animation cycles
clock = pygame.time.Clock()
pygame.init()
#BUG REMOVIDO: BUG É ".convert()" da linha "backdrop = pygame.image.load(os.path.join('images','stage.png').convert())"
world    = pygame.display.set_mode([worldx,worldy])
backdrop = pygame.image.load(os.path.join('images','stage.png'))
backdropbox = world.get_rect()

BLUE  = (25,25,200)
BLACK = (23,23,23 )
WHITE = (254,254,254)

main = True

# put run-once code here

'''
Main Loop
'''

while main == True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); sys.exit()
            main = False

        if event.type == pygame.KEYDOWN:
            if event.key == ord('q'):
                pygame.quit()
                sys.exit()
                main = False
world.blit(backdrop, backdropbox)
# put game loop here

pygame.display.flip()
clock.tick(fps)

Solution

  • You have to add the attribute .rect to Player:

    class Player(pygame.sprite.Sprite):
        def __init__(self):
          pygame.sprite.Sprite.__init__(self)
          self.images = []
          img = pygame.image.load(os.path.join('images','hero.png')).convert()
          self.images.append(img)
          self.image = self.images[0]
          self.rect = self.image.get_rect() # <----
          self.rect.x = 40
          self.rect.y = 30
    

    Create an instance of Player. Create a pygame.sprite.Group and add palyer:

    player = Player()
    all_sprites = pygame.sprite.Group()
    all_sprites.add(player)
    

    Use draw() to draw all the Sprites in the Group. draw makes use of the image and rect attributes of the Sprites, to draw all the Sprites in the Group:

    all_sprites.draw(world)
    

    Respect the Indentation:

    while main == True:
    
        # handle events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit(); sys.exit()
                main = False
    
            if event.type == pygame.KEYDOWN:
                if event.key == ord('q'):
                    pygame.quit()
                    sys.exit()
                    main = False
    
        # draw background
        world.blit(backdrop, backdropbox)
    
        # draw scene
        all_sprites.draw(world)
    
        # update display
        pygame.display.flip()
        clock.tick(fps)