Pygame tutorial 2 – Moving the object with keyboard

Before we start, make sure you have read the first tutorial of creating game in python with pygame, if you not then just go ahead and read the first part of this pygame tutorial series.

In this tutorial I am going to show you how to move the game object within the pygame’s display screen with your keyboard.

In order to move our object within pygame we will need to find out whether the user has pressed a certain key or not from the value of the event’s key property and also we will only move our character if the user is continue pressing that key.

Below is the entire python script to move a boat in the right or the left direction on the display screen. The display portion of the script is almost the same as the previous one but with an additional loop to retrieve the value of the event’s key property (in this example the left or the right arrow key on your keyboard) as well as to detect whether you are continue pressing that key or have already released it, if you have released the key then the direction will again set to zero which means no movement will be made by that object at the moment or else the object will move to either left or the right by 0.05 unit (if you pressed the left arrow key then the boat will move left or else it will move right if right arrow key is pressed).

#!/usr/bin/env python

import pygame
from pygame.locals import *
from sys import exit

background_image = 'terain7.png'
boat = 'boat.png'

SCREEN_SIZE = (500, 500)
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
pygame.display.set_caption("Pygame Demo")
background = pygame.image.load(background_image).convert()
player = pygame.image.load(boat).convert_alpha()

x, y = 150, 353
direction = 0

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                direction = MOVE_LEFT
            elif event.key == K_RIGHT:
                direction = MOVE_RIGHT
        elif event.type == KEYUP:
            if event.key == K_LEFT:
                direction = 0
            elif event.key == K_RIGHT:
                direction = 0
    if(direction == MOVE_LEFT):
    elif(direction == MOVE_RIGHT):
    screen.blit(background, (0, 0))
    screen.blit(player, (x, y))

Run the above script in NetBeans 8.1 and you will see the below outcome.

If you are interested in pygame then don’t miss my daily pygame tutorial because starting from today I will write one to three posts per day on pygame so do visit this blog everyday and master the entire pygame tutorial within a week!