In this PyGame with Python 3 tutorial, we cover how to move our epic race car image about using key inputs from the user. Luckily for us, PyGame handles a lot of the event handling in the background, simply feeding us the events that have happened, allowing us to then do what we please.
Let's see an example:
import pygame
pygame.init()
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A bit Racey')
black = (0,0,0)
white = (255,255,255)
clock = pygame.time.Clock()
crashed = False
carImg = pygame.image.load('racecar.png')
def car(x,y):
gameDisplay.blit(carImg, (x,y))
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
car_speed = 0
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
############################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
######################
##
x += x_change
##
gameDisplay.fill(white)
car(x,y)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
So again, the changed code is around the # signs. The main bit of logic here is:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
Easy enough if we break this down. First, we're asking if the event is a keydown event, which means if there is any key being pressed. Later, we can combine all of this into 1 statement, but here I'd like to keep things as simple as possible. So, is there a key being pressed? If so, is that key a LEFT arrow key? If it is, then our x_change is -5. If the KEYDOWN is a RIGHT arrow key, then x_change is 5. Finally, if the key change is actually a KEYUP, meaning if we have released a key, then x_change is 0.
Then, we use x_change to change our x variable:
x += x_change
Remember that "x" is used to position our car image in the car function.
That's really all there is to moving the car around!