1

I am learning Python in Python Crashcourse and am making the Alien Invasion game.

This is what I have in ship.py file to control the Spaceship's X position

     # Movement flag
    self.moving_right = False
    self.moving_left = False

def update(self):
    """Update the ship''s position based on the movement flag"""
    if self.moving_right:
        self.rect.x += 1
    if self.moving_left:
        self.rect.x -= 1

And here is the main alien_invasion.py file using pygame.KEYLEFT and KEYRIGHT

    def _check_events(self):
    # Watch for keyboard and mouse movements.
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                self.ship.moving_right = True
            elif event.key == pygame.KEYLEFT:
                self.ship.moving_left = True

        elif event.type == pygame.KEYUP:
            if event.key == pygame.KEYRIGHT:
                self.ship.move_right = False
            elif event.key == pygame.KEYLEFT:
                self.ship.moving_left = False

And I keep getting the error AttributeError: module 'pygame' has no attribute 'KEYLEFT' when I run the game and press the left key. Sorry if this is an overload of stuff for a small problem, not sure how much info is needed to help fix. Thank you

noahb04
  • 13
  • 3

1 Answers1

2

There is a KEYUP and KEYDOWN, but no KEYRIGHT and KEYLEFT. You are looking for K_LEFT and K_RIGHT.

def _check_events(self):
# Watch for keyboard and mouse movements.
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        sys.exit()
    elif event.type == pygame.KEYDOWN:
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True

    elif event.type == pygame.KEYUP:
        if event.key == pygame.K_RIGHT:
            self.ship.move_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False
Mitchell Olislagers
  • 1,758
  • 1
  • 4
  • 10