Chapter 7.2 - Move with Keyboard

7.2 - Move with the Keyboard

Download  the code from here and open it to Thonny.

Study the lines 41 to 59

if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT or event.key == pygame.K_d: ship_x_speed = 5 if event.key == pygame.K_LEFT or event.key == pygame.K_a: ship_x_speed = -5 if event.key == pygame.K_DOWN or event.key == pygame.K_s: ship_y_speed = 5 if event.key == pygame.K_UP or event.key == pygame.K_w: ship_y_speed = -5 if event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT: ship_x_speed = 0 if event.key == pygame.K_d or event.key == pygame.K_a: ship_x_speed = 0 if event.key == pygame.K_UP or event.key == pygame.K_DOWN: ship_y_speed = 0 if event.key == pygame.K_w or event.key == pygame.K_s: ship_y_speed = 0


In these lines pygame checks if arrow keys LEFT, RIGHT, UP, DOWN or keys d, a , s, w are pressed down (KEYDOWN) or released (KEYUP) and moves spaceship accordingly.

In lines 30 to 33 which are outside the main loop we set the starting position of the spaceship and the starting speed in each axis to 0

ship_x = 500 ship_y = 380 ship_x_speed = 0 ship_y_speed = 0


And finally lines 74 to 87 where we show the spaceship, move i and make sure that it stays inside the screen

screen.blit(spaceshipImg, (ship_x, ship_y)) if ship_x >= 0 and ship_x <= 984: ship_x += ship_x_speed elif ship_x < 0: ship_x = 1 elif ship_x > 984: ship_x = 983 if ship_y >= 0 and ship_y <= 728: ship_y += ship_y_speed elif ship_y < 0: ship_y = 1 elif ship_y > 728: ship_y = 727 print(ship_x, ship_y)


The final version to PLAY, finally, is here.

avoid the rocks