Search code examples
pythonclassmethodspygametypeerror

Moving user inputs to a different file from main game file. (Pygame). Positional Arugement error "Takes 1 positional arugement but two where given


Created an instance from a Class in a different file from the main file -

self.movement = User_input_responses(self)

Called a method in that instanced Class to react to users movements -

self.movement.user_input_reactions()

Error I Got -

TypeError: User_input_responses.__init__() takes 1 positional argument but 2 were given

I tried to move user inputs key reactions out of the main game code because it was making the main game code too hectic. I already had the game working before the move.

Everything i moved over to new file - method to deal with pygame events method to deal with user keydown events method to deal with user keyup events

Code of Main file -

from ship_movement import User_input_responses
from settings import Settings
from ship_test import Ship

class Alien_Invasion:

    def __init__(self):
    
        pygame.init()
        self.settings = Settings()
        #screen
        self.screen = pygame.display.set_mode((self.settings.screen_width , self.settings.screen_height))
        pygame.display.set_caption(("Alien Invader"))
        self.bg_color = self.settings.bg_color

        self.clock = pygame.time.Clock()
        self.ship = Ship(self)
        self.movement = User_input_responses(self)

    def update_screen(self):
        pygame.display.flip()
        self.screen.fill(self.bg_color)
        self.ship.blitme()

    def game(self):
        while True:
            self.movement.user_input_reactions()
            self.ship.ship_movement()
            self.update_screen()
            self.clock.tick(60)


if __name__ == '__main__':
    game_launcher = Alien_Invasion()
    game_launcher.game()

Code of mentioned Class file -

class User_input_responses:

    def __init__(self):
        self.ship = Ship(self)

    def user_input_reactions(self):

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
        
            elif event.type == pygame.KEYDOWN:
                self.keydown(event)

            elif event.type == pygame.KEYUP:
                self.keyup(event)
            

Solution

  • The self argument is passed automatically, you shouldn't provide an explicit argument when calling the class constructor function. Change

    self.movement = User_input_responses(self)
    

    to

    self.movement = User_input_responses()