Degel_
Degel_

Reputation: 23

Pygame: Issue stemming from an update() function using keyboard inputs

I'm trying to create a two-player game in which each player is the object of a class. However, when I run my code, the command prompt gives me an error in line 43, saying that update() is missing a positional argument: "function"

class player(pygame.sprite.Sprite):
    lives = 5

    def __init__(self, left, right, img):
        super(player, self).__init__()
        self.surface = pygame.image.load(img).convert_alpha()
        self.rect = self.surface.get_rect()
        self.left = left
        self.left = right

    def update(self, function):
        if function[self.left]:
            self.rect.move_ip(-5, 0)
        if function[self.right]:
            self.rect.move_ip(5, 0)


player1 = player(K_LEFT, K_RIGHT, "jet1.png")
player2 = player(K_a, K_d, "jet2.png")


open = True
while open:
    for event in pygame.event.get():
        if pygame.key.get_pressed()[K_ESCAPE]:
            open = False
        elif event.type == QUIT:
            open = False

    pressed = pygame.key.get_pressed()

    player.update(pressed)

    display.blit(player1.surface, (width/4, height/4))
    display.blit(player2.surface, (.75 * width, .75 * height))

Also, when I take off the "function" argument in the update function, I get another error that says: 'pygame.key.ScancodeWrapper' object has no attribute 'left'

I'm relatively new to Python and Pygame, so any help would be greatly appreciated!

Upvotes: 2

Views: 88

Answers (1)

Rabbid76
Rabbid76

Reputation: 210968

Class names should normally use the CapWords convention. Rename player to Player, but keep player1 and player2.


player is a class, but update is a Method Objects. You've to invoke update on an Instance Object of the class player. player1 and player2 are instances of the class player.

player.update(pressed)

player1.update(pressed)
player2.update(pressed)

However, since player is a pygame.sprite.Sprite, I recommend using a pygame.sprite.Group:

player1 = player(K_LEFT, K_RIGHT, "jet1.png")
player2 = player(K_a, K_d, "jet2.png")

all_sprites = pygame.sprite.Group([player1, player2])

open = True
while open:
    # [...]

    all_sprites.update(pressed)

    # [...]

Upvotes: 1

Related Questions