How to implement animations in pygame

Recently, I have been perfecting a small game about airplane battles. The one-to-one version based on the book is a bit crude, so I added a lot of elements to it. One of them is the dynamic effect of bullets, but pygame does not support gif animations (it can be imported, but it will not move), so what should I do?

We know that the principle of animated pictures is to play a group of pictures quickly. Following this idea, we can try to disassemble the gif into pngs one by one, and then import them into the game for quick rotation.

The disassembly of gif can be completed through PS. There are many tutorials on CSDN. I also learned it from here, so I won’t go into details. The key step is to import multiple images at the same time and play them in turn:

image_list = ['index0001', 'index0002', ...]
frame_list = []
    for i in image_list:
        ii = pygame.image.load(f'../images/gif/{i}.png')
        frame_list.append(ii)

Above is the imported code. The image_list contains the pictures of each frame of the gif you want to import. Sometimes a gif can contain dozens or even hundreds of pictures. It is certainly impossible for us to type in the names one by one. However, generally the PNGs disassembled by PS will have a unified name prefix, such as index0001, index0002, etc. Assuming there are 60 pictures, it can be easily solved with a for loop:

image_list = []
for i in range(0,61):
    name = f'index00{i}'
    image_list.append(name)
# 前十个数最后输出是index001,index002...少一个零,别忘记改

Continuing from the above, each pygame.image.load() is stored in the frame_list list through another for loop to facilitate subsequent calls. The code for image rotation is as follows:

self.images = image_list
self.image = self.images[0]
self.rect = self.image.get_rect()
self.image_index = 0

    def bullets_draw(self):
        """轮换"""
        if self.image_index < len(self.images) - 1:
            self.image_index += 1
        else:
            self.image_index = 0
        self.image = self.images[self.image_index]
        self.screen.blit(self.image, self.rect)

self.image sets the first frame, and then uses an image_index as the list index to achieve the effect of sequential playback. Pygame draws the screen very quickly, and loading these images takes just a moment.

The above is my personal experience when I first learned pygame. I hope it can help those in need. After all, I searched for guides for a long time but couldn't find them...

Guess you like

Origin blog.csdn.net/2203_75311888/article/details/128905355