banner



How To Add A Sprite In Pygame

Pygame Lesson 1-2: Working with Sprites

Tags: python tutorial gamedev pygame

This is part 2 of our tutorial series, "Game Development with Pygame". It is intended for beginner/intermediate programmers who are interested in game development and improving their Python coding skills. Y'all should start with Office i: Getting Started

You lot can watch a video version of this lesson here:

What is a sprite?

A sprite is a computer graphics term for any object on the screen that can motility around. When you lot play whatsoever 2D game, all the objects y'all see on the screen are sprites. Sprites tin can be animated, they tin can be controlled by the player, and they can even collaborate with each other.

Nosotros will take intendance of updating and drawing our sprites in the UPDATE and Depict sections of our game loop. But you tin probably imagine, if your game has a large number of sprites then these sections of your game loop could go very long and complicated. Fortunately, Pygame has a good solution for this: the sprite group.

A sprite group is just a drove of sprites that yous tin can act on all at the same fourth dimension. Permit'due south make a sprite grouping to hold all the sprites in our game:

                          clock              =              pygame              .              time              .              Clock              ()              all_sprites              =              pygame              .              sprite              .              Group              ()                      

Now we tin take advantage of the group past adding the following in our loop:

                          # Update              all_sprites              .              update              ()              # Describe / render              screen              .              fill              (              BLACK              )              all_sprites              .              draw              (              screen              )                      

Now for every sprite that we create we just brand sure nosotros add together it to the all_sprites group, and it will automatically exist drawn on the screen and updated each time through the loop.

Creating a sprite

Now we're ready to make our outset sprite. In Pygame, sprites are objects. If you haven't worked with objects in Python before, they are a convenient manner of grouping information and lawmaking into a unmarried entity. It may be a little confusing at offset, but fortunately, Pygame sprites are a skillful way to exercise with objects and get used to how they piece of work.

We start by defining our new sprite:

                          grade              Player              (              pygame              .              sprite              .              Sprite              ):                      

form tells Python we're defining a new object, which is going to be our actor sprite, and its type is pygame.sprite.Sprite, which means information technology volition be based on Pygame's pre-defined Sprite class.

The first chip of code we need in a class definition, is the special __init__() function, which defines what code will run whenever a new object of this type is created. There are also two properties that every Pygame sprite must accept: an prototype and a rect:

                          class              Player              (              pygame              .              sprite              .              Sprite              ):              def              __init__              (              self              ):              pygame              .              sprite              .              Sprite              .              __init__              (              self              )              self              .              image              =              pygame              .              Surface              ((              50              ,              50              ))              self              .              image              .              make full              (              GREEN              )              cocky              .              rect              =              self              .              epitome              .              get_rect              ()                      

The first line, pygame.sprite.Sprite.__init__(cocky) is required by Pygame - it runs the congenital-in Sprite classes initializer. Next, we define the image property - in this example, we're just creating a simple fifty x 50 square and filling it with the color GREEN. Later we'll acquire how to brand the sprite's image exist something fancier, like a character or spaceship, but a solid square is good enough for now.

Adjacent, we must ascertain the sprite's rect, which is brusque for "rectangle". Rectangles are used all over the identify in Pygame to continue track of an object's coordinates. the get_rect() command simply looks at the image and calculates the rectangle that volition enclose it.

Nosotros can use the rect to put the sprite wherever we want information technology on the screen. Let's get-go with the sprite in the middle:

                          class              Player              (              pygame              .              sprite              .              Sprite              ):              def              __init__              (              self              ):              pygame              .              sprite              .              Sprite              .              __init__              (              self              )              self              .              image              =              pygame              .              Surface              ((              fifty              ,              50              ))              self              .              prototype              .              fill              (              Greenish              )              self              .              rect              =              self              .              image              .              get_rect              ()              self              .              rect              .              center              =              (              WIDTH              /              2              ,              HEIGHT              /              2              )                      

Now that we've defined our Player sprite, we demand to "spawn" (meaning create) it by making an instance of the Actor class. We also need to make sure nosotros add the sprite to the all_sprites group:

                          all_sprites              =              pygame              .              sprite              .              Group              ()              actor              =              Player              ()              all_sprites              .              add              (              player              )                      

Now, if you run your plan, you'll see the dark-green square at the center of the screen. Go ahead and increment the WIDTH and HEIGHT settings of your program so that you will have enough of space for the sprite to move around in the next step.

Sprite movement

Think, in the game loop, we have the all_sprites.update(). This means that for every sprite in the group, Pygame will look for an update() function and run it. So to get our sprite to movement, we just need to ascertain its update rules:

                          course              Player              (              pygame              .              sprite              .              Sprite              ):              def              __init__              (              self              ):              pygame              .              sprite              .              Sprite              .              __init__              (              self              )              self              .              paradigm              =              pygame              .              Surface              ((              50              ,              50              ))              self              .              image              .              fill up              (              Greenish              )              cocky              .              rect              =              self              .              image              .              get_rect              ()              self              .              rect              .              middle              =              (              WIDTH              /              2              ,              Top              /              2              )              def              update              (              cocky              ):              cocky              .              rect              .              x              +=              5                      

This ways that every time through the game loop, we increase the ten coordinate of the sprite past 5 pixels. Go ahead and run information technology and you'll come across the sprite head off the correct side of the screen:

Permit'southward gear up that by making the sprite wrap around - whenever it reaches the right side of the screen, we will move it to the left side. We can do this easily by using one of the convenient "handles" on the sprite's rect:

So if the left edge of the rect goes off the screen, we'll gear up the right border to 0:

                          form              Player              (              pygame              .              sprite              .              Sprite              ):              def              __init__              (              cocky              ):              pygame              .              sprite              .              Sprite              .              __init__              (              self              )              cocky              .              epitome              =              pygame              .              Surface              ((              fifty              ,              50              ))              cocky              .              image              .              fill              (              Light-green              )              cocky              .              rect              =              cocky              .              prototype              .              get_rect              ()              self              .              rect              .              center              =              (              WIDTH              /              2              ,              HEIGHT              /              2              )              def              update              (              self              ):              cocky              .              rect              .              x              +=              5              if              self              .              rect              .              left              >              WIDTH              :              self              .              rect              .              correct              =              0                      

And now nosotros can run across the sprite will announced to wrap effectually the screen:

That volition exercise it for this lesson. Go alee and experiment - notice that anything you put in the update() method of the sprite will happen every frame. Try making the sprite move up and downward (alter the y coordinate) or making it bounce off the wall (reverse the direction when the rect reaches the edge).

In the adjacent tutorial, nosotros'll testify yous how to use art for your sprite - changing it from a evidently square into an blithe character.

Part iii: More About Sprites

  • Installing Python
  • Installing Pygame
  • Setting up Atom

How To Add A Sprite In Pygame,

Source: https://kidscancode.org/blog/2016/08/pygame_1-2_working-with-sprites/

Posted by: steinmetzocas1943.blogspot.com

0 Response to "How To Add A Sprite In Pygame"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel