Moving an object in PyGame|Python

Moving an object in PyGame|Python

Now as we have learned how to add images, we can finally bring the mechanics/movement to our game elements using pygame. So, the aim of this article is to make you learn how to make PyGame elements moving or Moving an object in PyGame. All in all, we will learn how to move an image using arrow keys.

So, let’s begin:

First of all, let’s create a blank game window and then add a background color to it.

To do so, we need to write the following code:

import pygame
pygame.init()
screen = pygame.display.set_mode((800,600))
# Title
pygame.display.set_caption("copyassignment")
isRunning = True
#Game loop
while(isRunning ==True):
    screen.fill((167,145,55))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            isRunning = False
    pygame.display.update()

The image that I am using to demonstrate the movement can be downloaded using the following link: Man Image – Flaticon

Now put it inside your current working directory. And then load it inside your game using the following code:

player = pygame.image.load('athlete.png')

Now we need to specify the initial X and Y coordinate of the player.

So we will define two variables that will contain the X and Y coordinate of the player on our game window/screen. Let’s assume the initial coordinates of the player be (375,500). As our game window is of size (800,600), this coordinate will set our image somewhere at the bottom in the center.

playerX = 375
playerY = 500

Now, let’s write screen.blit() inside our game loop before updation of the screen.

screen.blit(player,(playerX,playerY))

After adding this, your full code must be looking like this:

import pygame
pygame.init()
screen = pygame.display.set_mode((800,600))
# Title
pygame.display.set_caption("copyassignment")
isRunning = True
#Loading image
player = pygame.image.load('athlete.png')
#Specifying the X and Y Coordinate
playerX = 375
playerY = 500
while(isRunning ==True):
    screen.fill((167,145,55))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            isRunning = False
    screen.blit(player,(playerX, playerY))
    pygame.display.update()

Notice that by changing the value of playerX and playerY, the position of the player also changes.

Moving an object in PyGame

Before adding motion, we need to understand the concept of it.

As we have already defined the X and Y coordinates of the game window, now we need to change them in order to change the position of the player.

How does changing the X and Y coordinates change the player’s position?

Changing X and Y coordinates change the player’s position because of the screen.blit(). As we know that screen.blit() adds the image on our screen at a certain coordinate that it takes as one of its necessary arguments. So, when we change the X and Y coordinate, screen.blit() changes the position of the image to new X and Y coordinates that are passed inside it.

So, what we exactly want is that when the Upward arrow key is pressed the player should move up, and just like that we want our player to move with respect to the type of arrow key that is pressed. So, now we will use the event module from pygame. Earlier in our series of articles, we used an event module to detect the event that is happening on our game window, which was the quit event. So, now in this article, we will dive deeper into the concept of events.

Events in PyGame

An event is basically anything that is happening on your screen. And pygame gives us a very easy way to detect those events.

Pygame has an event module for interacting with events and queues.

pygame.event.pumpinternally process pygame event handlers
pygame.event.getget events from the queue
pygame.event.pollget a single event from the queue
pygame.event.waitwait for a single event from the queue
pygame.event.peektest if event types are waiting on the queue
pygame.event.clearremove all events from the queue
pygame.event.event_nameget the string name from an event id
pygame.event.set_blockedcontrol which events are allowed on the queue
pygame.event.set_allowedcontrol which events are allowed on the queue
pygame.event.get_blockedtest if a type of event is blocked from the queue
pygame.event.set_grabcontrol the sharing of input devices with other applications
pygame.event.get_grabtest if the program is sharing input devices
pygame.event.postplace a new event on the queue
pygame.event.custom_typemake custom user event type
pygame.event.Eventcreate a new event object
pygame.event.EventTypepygame object for representing events

But in this article, we will be focusing on the event.get() method, as it will help us get the information about the event that happened on our game window/screen. It has no necessary argument so, we can leave the parenthesis blank.

As we will be using the event.get() method we need to know its syntax and how to use it.

In our previous article, we ran a for loop inside our game loop that is the while loop. And what we did in that for loop is that we created a variable called event and we stored the event that is happening on our screen using the following code:

for event in pygame.event.get():

And then inside the for loop we checked the type of the event using:

if event.type == pygame.QUIT:

And just like this, we will detect our other events, which can be KEYDOWN or KEYUP and many more.

Here are some of the events that are provided to us by pygame:

Constant nameAttributes
QUITnone
ACTIVEEVENTgain, state
KEYDOWNunicode, key, mod
KEYUPkey, mod
MOUSEMOTIONpos, rel, buttons
MOUSEBUTTONUPpos, button
MOUSEBUTTONDOWNpos, button
JOYAXISMOTIONjoy, axis, value
JOYBALLMOTIONjoy, ball, rel
JOYHATMOTIONjoy, hat, value
JOYBUTTONUPjoy, button
JOYBUTTONDOWNjoy, button
VIDEORESIZEsize, w, h
VIDEOEXPOSEnone
USEREVENTcode

The above table contains all the events that can occur from a keyboard, mouse, joystick, etc.

To handle our events we simply loop through the queue, check what type it is, and then perform some action.

Now we know all these types of events but how will we know that what key was pressed on the keyboard so that we can move our player.

To do so, we need to first check if a key was pressed or released. To check if a key was pressed we can use an if statement inside of for loop:

if event.type == pygame.KEYDOWN:
    print("Key was pressed")
if event.type == pygame.KEYUP:
    print("Key was released")

Now inside of printing if the key was pressed or not, we can simply put an if statement to check if the key which we want was pressed or not. Here we want if the upward arrow key was pressed or not. So we can simply do that by writing event.key == pygame.K_UP.

But for your reference here are all of the pygame.key constants:

pygame
Constant      ASCII   Description
---------------------------------
K_BACKSPACE   \b      backspace
K_TAB         \t      tab
K_CLEAR               clear
K_RETURN      \r      return
K_PAUSE               pause
K_ESCAPE      ^[      escape
K_SPACE               space
K_EXCLAIM     !       exclaim
K_QUOTEDBL    "       quotedbl
K_HASH        #       hash
K_DOLLAR      $       dollar
K_AMPERSAND   &       ampersand
K_QUOTE               quote
K_LEFTPAREN   (       left parenthesis
K_RIGHTPAREN  )       right parenthesis
K_ASTERISK    *       asterisk
K_PLUS        +       plus sign
K_COMMA       ,       comma
K_MINUS       -       minus sign
K_PERIOD      .       period
K_SLASH       /       forward slash
K_0           0       0
K_1           1       1
K_2           2       2
K_3           3       3
K_4           4       4
K_5           5       5
K_6           6       6
K_7           7       7
K_8           8       8
K_9           9       9
K_COLON       :       colon
K_SEMICOLON   ;       semicolon
K_LESS        <       less-than sign
K_EQUALS      =       equals sign
K_GREATER     >       greater-than sign
K_QUESTION    ?       question mark
K_AT          @       at
K_LEFTBRACKET [       left bracket
K_BACKSLASH   \       backslash
K_RIGHTBRACKET ]      right bracket
K_CARET       ^       caret
K_UNDERSCORE  _       underscore
K_BACKQUOTE   `       grave
K_a           a       a
K_b           b       b
K_c           c       c
K_d           d       d
K_e           e       e
K_f           f       f
K_g           g       g
K_h           h       h
K_i           i       i
K_j           j       j
K_k           k       k
K_l           l       l
K_m           m       m
K_n           n       n
K_o           o       o
K_p           p       p
K_q           q       q
K_r           r       r
K_s           s       s
K_t           t       t
K_u           u       u
K_v           v       v
K_w           w       w
K_x           x       x
K_y           y       y
K_z           z       z
K_DELETE              delete
K_KP0                 keypad 0
K_KP1                 keypad 1
K_KP2                 keypad 2
K_KP3                 keypad 3
K_KP4                 keypad 4
K_KP5                 keypad 5
K_KP6                 keypad 6
K_KP7                 keypad 7
K_KP8                 keypad 8
K_KP9                 keypad 9
K_KP_PERIOD   .       keypad period
K_KP_DIVIDE   /       keypad divide
K_KP_MULTIPLY *       keypad multiply
K_KP_MINUS    -       keypad minus
K_KP_PLUS     +       keypad plus
K_KP_ENTER    \r      keypad enter
K_KP_EQUALS   =       keypad equals
K_UP                  up arrow
K_DOWN                down arrow
K_RIGHT               right arrow
K_LEFT                left arrow
K_INSERT              insert
K_HOME                home
K_END                 end
K_PAGEUP              page up
K_PAGEDOWN            page down
K_F1                  F1
K_F2                  F2
K_F3                  F3
K_F4                  F4
K_F5                  F5
K_F6                  F6
K_F7                  F7
K_F8                  F8
K_F9                  F9
K_F10                 F10
K_F11                 F11
K_F12                 F12
K_F13                 F13
K_F14                 F14
K_F15                 F15
K_NUMLOCK             numlock
K_CAPSLOCK            capslock
K_SCROLLOCK           scrollock
K_RSHIFT              right shift
K_LSHIFT              left shift
K_RCTRL               right control
K_LCTRL               left control
K_RALT                right alt
K_LALT                left alt
K_RMETA               right meta
K_LMETA               left meta
K_LSUPER              left Windows key
K_RSUPER              right Windows key
K_MODE                mode shift
K_HELP                help
K_PRINT               print screen
K_SYSREQ              sysrq
K_BREAK               break
K_MENU                menu
K_POWER               power
K_EURO                Euro

The keyboard also has a list of modifier states (from pygame.localspygame constants) that can be assembled by bitwise-ORing them together.

pygame
Constant      Description
-------------------------
KMOD_NONE     no modifier keys pressed
KMOD_LSHIFT   left shift
KMOD_RSHIFT   right shift
KMOD_SHIFT    left shift or right shift or both
KMOD_LCTRL    left control
KMOD_RCTRL    right control
KMOD_CTRL     left control or right control or both
KMOD_LALT     left alt
KMOD_RALT     right alt
KMOD_ALT      left alt or right alt or both
KMOD_LMETA    left meta
KMOD_RMETA    right meta
KMOD_META     left meta or right meta or both
KMOD_CAPS     caps lock
KMOD_NUM      num lock
KMOD_MODE     AltGr

Now as we have understood how to detect the keypress and change the position of the player, we are finally ready to add movement to the player.

To learn Moving an object in PyGame, we need to first learn about coordinates in PyGame which are just the positions of any object or element or you can say an image according to two assumed 2-dimensional human modals of X and Y directions, which are the same like we saw in mathematics graphs. So, let’s create two variables that will contain the changes in X and Y coordinates. Let’s assume Xchange and Ychange.

Xchange = 0
Ychange = 0

Now let’s get inside our game loop and create all the if statements to check the keypress events happening. In our case, we will check the arrow keys. And then we will increase Xchange or Ychange accordingly.

while(isRunning ==True):
    screen.fill((167,145,55))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            isRunning = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                Ychange-=0.5
            if(event.key == pygame.K_DOWN):
                Ychange+=0.5
            if event.key == pygame.K_LEFT:
                Xchange-=0.5
            if event.key == pygame.K_RIGHT:
                Xchange+=0.5
        if event.type == pygame.KEYUP:
            # To stop the increase in X change and Ychange
            Ychange=0
            Xchange=0
    playerX+=Xchange
    playerY+=Ychange
    screen.blit(player,(playerX, playerY))
    pygame.display.update()

Your full code should look like this:

import pygame
pygame.init()
screen = pygame.display.set_mode((800,600))
# Title
pygame.display.set_caption("copyassignment")
isRunning = True
#Loading image
player = pygame.image.load('athlete.png')
#Specifying the X and Y Coordinate
playerX = 375
playerY = 500
Xchange = 0
Ychange = 0
while(isRunning ==True):
    screen.fill((167,145,55))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            isRunning = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                Ychange-=0.5
            if(event.key == pygame.K_DOWN):
                Ychange+=0.5
            if event.key == pygame.K_LEFT:
                Xchange-=0.5
            if event.key == pygame.K_RIGHT:
                Xchange+=0.5
        if event.type == pygame.KEYUP:
# To stop the increase in X change and Ychange
            Ychange=0
            Xchange=0
    playerX+=Xchange
    playerY+=Ychange
    screen.blit(player,(playerX, playerY))
    pygame.display.update()

Now run it, Notice that the player can even cross the boundary of our game window/screen. To stop that we need to check if the player is touching the boundaries or not. To do that we need to write the following code instead of changing the values of playerX and PlayerY before screen.blit():

if playerX+Xchange>775 or playerY+Ychange>565 or playerX+Xchange<0 or playerY+Ychange<0:
        playerY+=0
        playerX+=0
    else:
        playerY+=Ychange
        playerX+=Xchange

What we have done in the above code is that we have checked if the value of X coordinate of the player is going below 0 that is the left most coordinate or it is going above the highest value of X that is 800 and same with Y coordinate but this time instead of checking if it is higher than 800, we are checking if it is greater than 600. Remember the height and width that we set while creating the game window is the highest value of the X and Y-axis.

Now, we also know that our player also has a size so we will set the highest points of X and Y in such a way that our player does not get out of the boundaries.

After doing this, the final code must be looking like this:

import pygame
pygame.init()
screen = pygame.display.set_mode((800,600))
# Title
pygame.display.set_caption("copyassignment")
isRunning = True
#Loading image
player = pygame.image.load('athlete.png')
#Specifying the X and Y Coordinate
playerX = 375
playerY = 500
Xchange = 0
Ychange = 0
while(isRunning ==True):
    screen.fill((167,145,55))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            isRunning = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                Ychange-=0.5
            if(event.key == pygame.K_DOWN):
                Ychange+=0.5
            if event.key == pygame.K_LEFT:
                Xchange-=0.5
            if event.key == pygame.K_RIGHT:
                Xchange+=0.5
        if event.type == pygame.KEYUP:
            Ychange=0
            Xchange=0
    if playerX+Xchange>775 or playerY+Ychange>565 or playerX+Xchange<0 or playerY+Ychange<0:
        playerY+=0
        playerX+=0
    else:
        playerY+=Ychange
        playerX+=Xchange
    screen.blit(player,(playerX, playerY))
    pygame.display.update()

So thank you for reading this article. For more information, you can read the Pygame Docs. In the next article, we will get to know how to add sound to our game. Until then, enjoy learning.


Also Read:

Share:

Author: Ayush Purawr