0

If I try to call a function from outside of the 'Player' class, it doesn't work, and complains that it's missing the 'self' variable. If I call it from inside the 'Player' class, it complains that 'Player' is not defined yet. How do I fix this?

Code needed to run it:


import pygame
import os.path

# Initializes pygame
pygame.init()


screen = pygame.display.set_mode([800, 576])


PlayerSprite = pygame.image.load(os.path.join('assets', 'sprites', 'player', '01.png')).convert_alpha()


running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    screen.fill((125, 125, 125))

            
    all_sprites = pygame.sprite.Group()

    
    move = 2

    class Player(pygame.sprite.Sprite):


        def __init__(self):
            super().__init__()
            self.image = PlayerSprite
            self.rect = self.image.get_rect()
            self.rect.center = 50, 50

        def keyboard_input(self):
            event = pygame.event.poll()
            keys = pygame.key.get_pressed()
            # Triggered if the user inputs a key.
            if event.type == pygame.KEYDOWN:
                key = pygame.key.name(event.key) # Returns the value of the pressed key
                
                if len(key) == 1: # All keys other than numpad
                    if keys[pygame.K_w] or keys[pygame.K_UP]: # Move the player up
                        self.y += move

    player = Player()
    all_sprites.add(player)
    all_sprites.draw(screen)
    Player.keyboard_input()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Techflash
  • 25
  • 1
  • 6

1 Answers1

0

Player.keyboard_input() is trying to reference the class object, you should reference the player variable. I.e, player.keyboard_input().