In this lesson, you’ll add user input to control your player sprite. Put this in your game loop right after the event handling loop. Watch for the level of indentation. This returns a dictionary containing the keys pressed at the beginning of every frame:
55# Get the set of keys pressed and check for user input
56pressed_keys = pygame.key.get_pressed()
Next, you write a method in Player
to accept that dictionary. This will define the behavior of the sprite based off the keys that are pressed:
29# Move the sprite based on user keypresses
30def update(self, pressed_keys):
31 if pressed_keys[K_UP]:
32 self.rect.move_ip(0, -5)
33 if pressed_keys[K_DOWN]:
34 self.rect.move_ip(0, 5)
35 if pressed_keys[K_LEFT]:
36 self.rect.move_ip(-5, 0)
37 if pressed_keys[K_RIGHT]:
38 self.rect.move_ip(5, 0)
K_UP
, K_DOWN
, K_LEFT
, and K_RIGHT
correspond to the arrow keys on the keyboard. If the dictionary entry for that key is True
, then that key is down, and you move the player .rect
in the proper direction. Here you use .move_ip()
, which stands for “move in place,” to move the current Rect
.
Xavier on March 28, 2020
I think I entered the code correctly, but I find the player block jumps a large distance for even a single key press. This is perhaps because the loop runs each time the frame is refreshed and what seems a single key press to me may be being registered for multiple frames. Looking ahead, there’s a “Game Speed” lesson. Implementing the clock code from that lesson makes the player behave as seen in this lesson’s demo.