Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Moving an object in PyGame
2.1.
Adding movement
2.2.
Event in PyGame
2.3.
Python code
3.
Frequently asked questions
3.1.
How would you move protests haphazardly in pygame?
3.2.
How would you move pictures in pygame?
3.3.
What is arbitrary Randrange in Python?
3.4.
How would you move the square shape in pygame?
3.5.
What is a pygame surface?
4.
Conclusion
Last Updated: Mar 27, 2024

Moving an object in Pygame

Author Adya Tiwari
0 upvote

Introduction

Pygame is a cross-stage set of Python modules intended for composing computer games. It incorporates PC illustrations and sound libraries designed to be utilized with the Python programming language. Presently, it depends on the creative mind or need of the engineer and what kind of game they need to foster using this tool compartment.

We will figure out how to move an article to such an extent that it carries on a level plane while squeezing the right bolt key or left bolt key on the console, and it moves upward while pressing the up bolt key or down bolt key.

The fundamental idea is to change the item's coordinates and invigorate the screen. When the screen revives each time window, the tone gets loaded up with the unique style, and the new square shape is framed, so when bolt keys get squeezed, coordinates change, and apparently, the item is moving.

Moving an object in PyGame

To understand Moving an article in PyGame, we want to initially find out about arranges in PyGame, which are only the places of any item or component, or you can say a picture as per two expected 2-layered human modals of X and Y bearings, which are similar like we found in science charts. In this way, we should make two factors that will contain the progressions in X and Y arranges. How about we accept Xchange and Ychange.

Adding movement

Before adding movement, we want to figure out the idea of it.

As we have proactively characterized the X and Y directions of the game window, we presently want to transform them to change the player's place.

How does changing the X and Y change the player's situation?

Changing X and Y facilitates shifting the player's position as a result of the screen.blit(). As we probably are aware that screen.blit() includes the picture of our screen in a specific direction that it takes as one of its vital contentions. In this way, when we change the X and Y coordinate, screen.blit() changes the place of the picture to new X and Y facilitates that are passed inside it.

Event in PyGame

An event is fundamentally whatever is occurring on your screen. What's more, pygame gives us a straightforward method for recognizing that event.

Pygame has an event module for cooperating with events and lines.

We will zero in on the event.get() technique, as it will assist us with getting the data about the possibility that occurred on our game window/screen. It has no strong contention in this way, and we can leave the enclosure clear.

As we will utilize the event.get() strategy; we want to know its punctuation and how to use it.

Python code

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()
You can also try this code with Online Python Compiler
Run Code

What we have done in the above code is that we have checked to assume the worth of X direction of the player is heading under 0 is the left generally direction or it is running over the most significant value of X that is 800 and same with Y coordinate however this time as opposed to checking to assume it is higher than 800, we are checking on the off chance that it is more prominent than 600. Recollect the level and width that we set while making the game window is the most elevated worth of the X and Y-pivot.

We likewise realize that our player again has a size, so we will set the highest places of X and Y so that our player doesn't escape the limits.

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()
You can also try this code with Online Python Compiler
Run Code

What's more, it is right there. This is the code we want to invigorate ten items on the screen. The main point that could require making sense of is the two circles we use to clear every one of the articles and draw every one of the items. To do things appropriately, we want to delete every one of the articles before removing them. Our example here may not make any difference; however, when articles are covered, utilizing two circles like this becomes significant.

Frequently asked questions

How would you move protests haphazardly in pygame?

To add uneven development in our item, we will utilize the randint technique for the arbitrary module.

How would you move pictures in pygame?

To situate an item on the screen, we want to tell the blit() work where to put the picture. In pygame, we generally pass positions as an (X, Y) coordinate.

What is arbitrary Randrange in Python?

The randrange() technique returns a haphazardly chosen component from the predefined range.

How would you move the square shape in pygame?

The strategy pygame. Rect. move_ip(x, y) can move the pygame square shape with the x-hub offset and y-pivot offset.

What is a pygame surface?

A pygame Surface is utilized to address any picture. The Surface has a good goal and pixel design. Surfaces with 8-digit pixels use a variety range to guide to 24-bit tone. Call pygame. Surface() pygame object for addressing pictures to make another picture object.

Conclusion

In the above article, we learned how to add movement to random objects or make a moving object in Python using Pygame and different events in Pygame. The principal idea of moving an item is by changing the coordinates of the article and invigorating the screen. When the screen animates each time window, the tone gets loaded up with the unique style, and the new square shape is framed, so when bolt keys get squeezed, coordinates change, and the article moves.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in PygameCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass