E. Wil
E. Wil

Reputation: 1

Pygame: Loading Sprites With Images

To improve my skill with objects, I'm trying to make a game in python to learn how to handle objects in which a I have a sprite called Player that displays an image taken from a file called image.gif using this class:

class Player(pygame.sprite.Sprite):
    def __init__(self, width, height):
        super().__init__()
        self.rect = pygame.Rect(width, height)
        self.image = pygame.Surface([width, height])
        self.image = pygame.image.load("image.gif").convert_alpha()
        # More sprites will be added.

I then used that class for the following code:

import Pysprites as pys
pygame.init()
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
RED   = (255,   0,   0)
GRAY = (255,255,255)
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Game")
all_sprites_list = pygame.sprite.Group()
player = pys.Player(44,22)
all_sprites_list.add(player)
carryOn = True
clock=pygame.time.Clock()
while carryOn:
    for event in pygame.event.get():
            if event.type==pygame.QUIT:
                carryOn=False
    all_sprites_list.update()
    clock.tick(60)
    all_sprites_list.draw(screen)
    pygame.display.flip()
    pygame.display.update()
pygame.quit()

and got the error:

Traceback (most recent call last):
  File "Game1.py", line 14, in <module>
    player = pys.Player(44,22)
  File "Pysprites.py", line 9, in __init__
    self.rect = pygame.Rect(width, height)
TypeError: Argument must be rect style object

What am I doing wrong? How can I make a sprite with an image without encountering this error?

Upvotes: 0

Views: 1409

Answers (1)

martineau
martineau

Reputation: 123413

The pygame.Rect() documentation says it only accepts one of 3 different combinations of arguments, none of which involves only providing two values as you're attempting to do.

I think you should have used self.rect = pygame.Rect(0, 0, width, height) in the Player__init__() method to provide the left, top, width, and height argument combination it expects.

Upvotes: 2

Related Questions