0

I'm trying to learn about pygame, and in this course I have been asked to use event.key to check if the user presses a certain key and to perform actions accordingly. However, the system doesn't recognize "key" (inside the for loop) as an attribute of any of my classes, and VSC reads "any" when I hover my cursor over it...

def run_game_loop(self):

    player_direction = 0
    self.draw_objects()
    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.QUIT:
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    player_direction = -1
                if event.key == pygame.K_DOWN:
                    player_direction = 1

        self.player.move(player_direction) 
        self.clock.tick(60)

Any idea why this happening and how I can solve it? I know it is probably a silly problem with an even sillier solution, but I am a complete noob at coding so please bear with me :)

  • I can't see anything abnormal stand out from this particular code example, looks almost identical to my own projects. Have you checked if your python/pygame versions are correct ? – Alexander Freyr Apr 04 '22 at 19:38
  • I am sure I have the latest versions installed: Pygame 2.1.2 and Python 3.10.4. I don't know why but when I run the main.py of this "game" I receive the standard window with bg and items, but I can't move the player. I guessed that that's because "key" is not recognized as being part of a method, but now I'm starting to think that there might be another problem. – Giorgio Doveri Apr 05 '22 at 07:36
  • You could try using the debugger or using `print()` statements to see if your code is reaching inside `event.key == pygame.K_UP`. If it reaches inside then you can say for certain that something else is wrong. – Alexander Freyr Apr 05 '22 at 10:57
  • 1
    You know, actually KEYDOWN and event.key work. I tried raising a couple of exceptions and they actually work just fine. For some reason, the player's "move" method is not updating after I press the corresponding keys... I checked the code in the other files and everything seems okay. I am at an impasse, I hope the course support will reply soon cause I'd like to get to the bottom of this project. Thanks for your answer! – Giorgio Doveri Apr 05 '22 at 15:30
  • Indeed the solution WAS quite silly... I was updating the display BEFORE executing logic (see that "self.draw_object()" call on top of the run_game_loop function?). Of course nothing was working ^^" Thank you so much for your time! – Giorgio Doveri Apr 05 '22 at 16:06

0 Answers0