7.2.5 - Moving sprites with the keyboard

As we have seen in a previous chapter we can use the keyboard to control the movement of shapes. The same thing can be done with sprites. 

Save the avoid_v0.1 program as avoid_v0.2 inside the same folder Module7.2.

To move the spaceship 

1. We initialize its position and speed outside the main loop with the following commands:

# Initialization of spaceships position and speed ship_x = 380 ship_y = 285 ship_x_speed = 0 ship_y_speed = 0


2. Inside the main loop in the event processing area we add the commands:

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

12

3. In the game logic area we add the following commands so the spaceship which size  is 40x33 doesn't get out of the screen. 

if ship_x >= 0 and ship_x <= 760: ship_x += ship_x_speed elif ship_x < 0: ship_x = 1 elif ship_x > 760: ship_x = 759 if ship_y >= 0 and ship_y <= 567: ship_y += ship_y_speed elif ship_y < 0: ship_y = 1 elif ship_y > 567: ship_y = 566


4. and change the command that blit the spaceship using the variables ship_x and ship_y:

screen.blit(spaceshipImg, (ship_x, ship_y))


34

The final program can be downloaded from here.