Table of contents
1.
Introduction
2.
Creating and controlling Sprites in pygame
2.1.
Creating Sprite
2.1.1.
Code Creating Sprite class
2.2.
Controlling Sprite
2.2.1.
Functions Used
2.2.2.
Code for sprite class
3.
Frequently asked questions
3.1.
What is the utilization of sprite in pygame?
3.2.
How would you control sprites in pygame?
3.3.
How does pygame recognize sprite crash?
3.4.
What is the sprite class in pygame?
3.5.
How would I erase a sprite in pygame?
4.
Conclusion
Last Updated: Mar 27, 2024

Creating and controlling Sprites in pygame

Author Adya Tiwari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The Pygame library has support for sprites. A sprite is a two-layered picture essential for the bigger graphical scene. Regularly a sprite will be some sort of item in the scene that will be communicated with like a vehicle, frog, or minimal handyman fellow. The essential method for making a Rect object in Pygame is to pass two tuples into the Pygame. Rect() Class. The first tuple (left, top) addresses the place of the rect on the window, while the second tuple (width, level) addresses the components of the Rect.

Creating and controlling Sprites in pygame

Sprites are objects with various properties like level, width, variety, and so forth, and techniques like moving right, left, all over, hop, and so on. In this article, we are hoping to make an item in which clients have some control over that item and push it ahead, in reverse, up, and down utilizing bolt keys. 

Creating Sprite

Let's first gander at our top notch, i.e., the class where our sprite is characterized; we will call that class Sprite. This Sprite class depicts its positions(x and y facilitates), aspect of an item, variety, and so forth. To start with, we will call our __init__() technique. It is known as a constructor for a class.

Code Creating Sprite class

import pygame

# GLOBAL VARIABLES
COLOR = (255, 100, 98)
SURFACE_COLOR = (167, 255, 100)
WIDTH = 500
HEIGHT = 500

# Object class
class Sprite(pygame.sprite.Sprite):
    def __init__(self, color, height, width):
        super().__init__()

        self.image = pygame.Surface([width, height])
        self.image.fill(SURFACE_COLOR)
        self.image.set_colorkey(COLOR)

        pygame.draw.rect(self.image,
                        color,
                        pygame.Rect(0, 0, width, height))

        self.rect = self.image.get_rect()
You can also try this code with Online Python Compiler
Run Code

Presently, that the class has been made, we can create objects from the course. It empowers us to make however many articles we want to utilize a similar style. Presently we will make an item using our Class Sprite.

Syntax:

object = Sprite(RED,WIDTH,HEIGHT)
You can also try this code with Online Python Compiler
Run Code

Of course, the article will be on position (0,0), i.e., upper left of the screen. We can change the x and y properties of the article.

Syntax:

object.rect.x = value
You can also try this code with Online Python Compiler
Run Code
object.rect.y = value
You can also try this code with Online Python Compiler
Run Code

We can characterize n of sprites that we need to make; however, to comprehend, how about we rearrange. Here we have made a square shape sprite of specific aspects, on which we can perform various tasks on spirits like push ahead, in reverse, bounce, slow, speed up, and so on.

import pygame
import random

# GLOBAL VARIABLES
COLOR = (255, 100, 98)
SURFACE_COLOR = (167, 255, 100)
WIDTH = 500
HEIGHT = 500

# Object class
class Sprite(pygame.sprite.Sprite):
    def __init__(self, color, height, width):
        super().__init__()

        self.image = pygame.Surface([width, height])
        self.image.fill(SURFACE_COLOR)
        self.image.set_colorkey(COLOR)

        pygame.draw.rect(self.image,color,pygame.Rect(0, 0, width, height))

        self.rect = self.image.get_rect()


pygame.init()

RED = (255, 0, 0)

size = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Creating Sprite")

all_sprites_list = pygame.sprite.Group()

object_ = Sprite(RED, 20, 30)
object_.rect.x = 200
object_.rect.y = 300

all_sprites_list.add(object_)

exit = True
clock = pygame.time.Clock()

while exit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit = False

    all_sprites_list.update()
    screen.fill(SURFACE_COLOR)
    all_sprites_list.draw(screen)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
You can also try this code with Online Python Compiler
Run Code

Output:

Controlling Sprite

Now we will see instructions to control the sprite, such as pushing ahead, in reverse, slow, or speed up, and a portion of the properties that the sprite ought to have. We will add occasion overseers to our program to answer keystroke occasions; when the player utilizes the bolt keys on the console, we will call our unadulterated techniques to move the article on the screen.

Functions Used

  • move right(): This strategy takes contention pixels, which implies the number of pixels an article that ought to be carried in the correct course. It is essentially adding pixels to the ongoing x-direction of the article.
  • Movement (): This strategy takes contention pixels, which implies the number of pixels an essay needs to be moved in the left course. It is fundamentally deducting pixels to the ongoing x-direction of the article.
  • Move forward(): This strategy takes a contention speed, which implies the rate that will increment by the number of elements. It is essentially speeding up with the component of n in the y-heading of the article.
  • Move backward(): This strategy takes a contention speed, and that implies by the number of elements the momentum that will diminish. It is essentially a diminishing rate with the aspect of n in the y-heading of the article.
  • Let us first take a gander at the execution of a Sprite class, which assists us with making an item on our PyGame surface, and, alongside added four techniques that will help us push ahead, in reverse, both ways.

Code for sprite class

import pygame

# GLOBAL VARIABLES
COLOR = (255, 100, 98)
SURFACE_COLOR = (167, 255, 100)
WIDTH = 500
HEIGHT = 500

# Object class
class Sprite(pygame.sprite.Sprite):
    def __init__(self, color, height, width):
        super().__init__()

        self.image = pygame.Surface([width, height])
        self.image.fill(SURFACE_COLOR)
        self.image.set_colorkey(COLOR)

        pygame.draw.rect(self.image,
                        color,
                        pygame.Rect(0, 0, width, height))

        self.rect = self.image.get_rect()

    def moveRight(self, pixels):
        self.rect.x += pixels

    def moveLeft(self, pixels):
        self.rect.x -= pixels

    def moveForward(self, speed):
        self.rect.y += speed * speed/10

    def moveBack(self, speed):
        self.rect.y -= speed * speed/10
You can also try this code with Online Python Compiler
Run Code

We will perceive how we control our fundamental program circle to deal with the sprites. The initial segment of the process will answer the occasions, for example, collaborations when the client utilizes the mouse or the console. Afterward, on above techniques for experience dealing with our article will be dealt with. On every occasion controller will call the relevant strategy from the Sprite class.

In this piece of code, we have control of our article, i.e., our article is an item according to our given bearings; assuming we press the right bolt key, it will move that way and the equivalent with all the bolt keys. Here, we use pygame.KEYDOWN technique to instate the strategy to involve the bolt keys for controlling the items; later on, we need to control the particular system to set off the unique key to play out the specific activity.

For example, if we have the correct bolt key, we need to call pygame.K_RIGHT strategy to move straight toward the item, and comparative for pygame.K_DOWN technique is utilized for the move up toward the object.

Frequently asked questions

What is the utilization of sprite in pygame?

The Pygame library has support for sprites. A sprite is a two-layered picture important for the more significant graphical scene.

How would you control sprites in pygame?

To move a sprite in Pygame, you should tell Python to redraw the sprite in its new area — and where that new area is. Since the Player sprite isn't continuously moving, make these updates a devoted capacity inside the Player class.

How does pygame recognize sprite crash?

To have the option to execute crash discovery, you first need to know how pygame identifies impacts between sprites. Each Sprite in pygame has (ought to) have a rect or "square shape" object doled out to it.

What is the sprite class in pygame?

Sprite, which is a Sprite class characterized by pygame. This lets Python know that the Ball class is a sort of Sprite (we say it is a subclass of Sprite ).

How would I erase a sprite in pygame?

The kill() technique eliminates the sprite from all gatherings it has a place with. This will neatly erase the sprite object.

Conclusion

Sprites are objects with various properties like level, width, variety, and so forth, and strategies like moving right, left, all over, bounce, and so on. In this article, we hope to make an article in which clients have some control over that item and push it ahead, reverse, up, and down utilizing bolt keys. To move a sprite in Pygame, you should tell Python to redraw the sprite in its new area — and where that new area is. Since the Player sprite isn't continuously moving, make these updates a devoted capacity inside the Player class. Add this capacity after the control work you made before. 

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 suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, 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