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
.
Then you can call .update()
every frame to move the player sprite in response to keypresses. Add this call right after the call to .get_pressed()
:
53# Main loop
54while running:
55 # for loop through the event queue
56 for event in pygame.event.get():
57 # Check for KEYDOWN event
58 if event.type == KEYDOWN:
59 # If the Esc key is pressed, then exit the main loop
60 if event.key == K_ESCAPE:
61 running = False
62 # Check for QUIT event. If QUIT, then set running to false.
63 elif event.type == QUIT:
64 running = False
65
66 # Get all the keys currently pressed
67 pressed_keys = pygame.key.get_pressed()
68
69 # Update the player sprite based on user keypresses
70 player.update(pressed_keys)
71
72 # Fill the screen with black
73 screen.fill((0, 0, 0))
Now you can move your player rectangle around the screen with the arrow keys. Try it out:
$ python sky_dodge.py
For more information about .move_ip()
and .get_pressed()
, check out the following resources from the pygame
documentation:
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.