You will:
Learn to move an object with the mouse;
learn to move an object with the keyboard.
Do you prefer multiplayer games or to go solo? Why?
Moving an image with the mouse
In the previous lesson, you’ve loaded character images. Now, you will move these characters.
Inside the main program loop, the mouse coordinates are retrieved, and passed to another blit function as the coordinates to draw the image: # Get the current mouse position.
# This returns the position as a list of two numbers.
player_position = pygame.mouse.get_pos()
x = player_position[0]
y = player_position[1]
# Copy image to screen:
screen.blit(player_img, [x, y])
Add this parts of script to your game code. And you will control your spaceship using mouse.
Practice 1
1. Change the mouse pointer to the center of the spaceship;
2. Add the window edges. When spaceship reaches the edge of the window, it stops.
Moving an image with the keyboard
In the previous lesson, you’ve learned to move an object with the keyboard using method pygame.key. Now, you will learn to move image using the keyboard using a different method.
State checking
It’s possible to call functions from the pygame.key and pygame.mouse module to receive the state of the key and mouse. However, it’s not the recommended way to process events in pygame since there are some flaws with it:
- You’ll receive the states when the function is called, which means you might miss events between calls if the user is pressing buttons fast;
- You cannot determine the order of the events;
- You still need to call one of pygame’s event functions for pygame to internally interact with the operating system,
- otherwise, it’ll warn that the program has become unresponsive.
State checking
The key module has a function pygame.key.get_pressed() which returns a list of the state of all keys. The list contains 0 for all the keys which are not pressed and 1 for all keys that are pressed. Its index in the list is defined by constants in the pygame module, all prefixed with K_ and the key name.
Example
# Allow pygame to handle internal actions.
pygame.event.pump()
key = pygame.key.get_pressed()
key = pygame.key.get_pressed()
# moves image right if RIGHT_KEY is pressed
if key[pygame.K_RIGHT]:
x+=1
# moves image left if LEFT_KEY is pressed
if key[pygame.K_LEFT]:
x-=1
Practice 2
1. Add the window edges. When spaceship reaches the edge of the window, it stops.
2. Add UP and DOWN keys to move image up and down.