0

I'm trying to draw a sprite to the screen using the class Player, but I get a traceback. It seems to be complaining when I draw the object to the screen, I'm not really sure what's causing it. I'm new to pygame so I figure that there is something that I am using wrong, or that I am missing, that I don't quite understand.

Here is my code:

import pygame
from sys import exit

# initilaization
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Bullet hell')

class Player(pygame.sprite.Sprite):
    '''The Main player class'''
    def __init__(self):
        super().__init__()
        self.player_image = pygame.image.load('sprites/player/player.png').convert_alpha()
        self.player_rect = self.player_image.get_rect(topleft = (0, 0))

# Player
player = pygame.sprite.GroupSingle()
player.add(Player())

# main game loop
while True:

    # event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    player.draw(screen)
    pygame.display.update()

It produces this error:

Traceback (most recent call last):
  File "/home/linkio/Projects/bullet-hell-game/main.py", line 29, in <module>
    player.draw(screen)
  File "/home/linkio/.local/lib/python3.10/site-packages/pygame/sprite.py", line 552, in draw
    zip(sprites, surface.blits((spr.image, spr.rect) for spr in sprites))
  File "/home/linkio/.local/lib/python3.10/site-packages/pygame/sprite.py", line 552, in <genexpr>
    zip(sprites, surface.blits((spr.image, spr.rect) for spr in sprites))
AttributeError: 'Player' object has no attribute 'image'
Linkio
  • 57
  • 5
  • In your `Player.__init__` method, try changing `self.player_image` to just `self.image` – nigh_anxiety Jun 11 '22 at 23:07
  • Yes, thank you this got me on the right track. Afterward, it gave me another error saying that the class has no attribute `'rect'` so I just applied that same logic and changed `self.player_rect` to just `self.rect`. It looks like sprite classes require specific attribute names. I'll write up an answer – Linkio Jun 11 '22 at 23:39
  • They're probably required to be specific as the methods are being inherited from the pygame.sprite.Sprite superclass, which are going to expect certain attributes to be there. – nigh_anxiety Jun 12 '22 at 01:03

1 Answers1

1

I needed to change my class attribute names. Sprite classes seem to work based on specific keywords as attributes.

class Player(pygame.sprite.Sprite):
    '''The Main player class'''
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('sprites/player/player.png').convert_alpha()
        self.rect = self.image.get_rect(topleft = (0, 0))
Linkio
  • 57
  • 5