Lesson 5: Move the Spaceship
Use the left and right arrow keys to glide your ship across the screen.
Step 1: Add Speed
player_speed = 0
Step 2: Handle Key Presses
# inside your game loop
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_speed = -0.5
if event.key == pygame.K_RIGHT:
player_speed = 0.5
if event.type == pygame.KEYUP:
if event.key in [pygame.K_LEFT, pygame.K_RIGHT]:
player_speed = 0
Step 3: Move the Player (+ keep on screen)
player_x += player_speed
player_x = max(0, min(player_x, 800 - player_img.get_width()))
Debug tip: print key presses to the console with
print(event.key).