【问题标题】:Fish swim in pygame鱼在pygame中游泳
【发布时间】:2013-04-18 05:46:50
【问题描述】:

我想使用 python pygame 模块制作一个 2D 的“鱼缸”。

基本上我会加载一个 jpg 图像作为背景,并加载一个描绘鱼游泳的 gif 动画图像并让它移动。

我知道如何使静态图像移动,但如何在图像本身为动画的同时使 gif 图像移动。

我已经安装了PIL,如果需要使用请确定。

如果这不起作用,我还可以将 gif 文件拆分为几个静态帧,并循环让每个帧显示在屏幕上。后一个贴出来的时候,前一个需要去掉,怎么去掉?

【问题讨论】:

    标签: python-2.7 pygame python-imaging-library gif


    【解决方案1】:

    这是我以我的名义使用的一个类,用于让 PyGame 动画正常工作:

    class Animation(pygame.sprite.Sprite):
        def __init__(self, img, fps = 6):
            # Call the parent class (Sprite) constructor 
            pygame.sprite.Sprite.__init__(self)
    
            # Slice source image to array of images
            self.images = self.loadSliced(img)
    
            # Track the time we started, and the time between updates.
            # Then we can figure out when we have to switch the image.
            self._start = pygame.time.get_ticks()
            self._delay = 1000 / fps
            self._last_update = 0
            self._frame = 0
            self.image = self._images[self._frame]
    
    def loadSliced(w, h, filename):
        """
        Pre-conditions:
            Master can be any height
            Sprites frames must be the same width
            Master width must be len(frames)*frames.width
    
        Arguments: 
            w -- Width of a frame in pixels
            h -- Height of a frame in pixels
            filename -- Master image for animation
        """
        images = []
    
        if fileExists( img, "Animation Master Image"):
            master_image = pygame.image.load(filename).convert_alpha()
            master_width, master_height = master_image.get_size()
            for i in range(int(master_width/w)):
                images.append(master_image.subsurface((i*w, 0, w, h)))
        return images
    
    def update(self, t):
        # Note that this doesn't work if it's been more than self._delay
        # time between calls to update(); we only update the image once
        # then. but it really should be updated twice
    
        if t - self._last_update > self._delay:
            self._frame += 1
            if self._frame >= len(self._images): 
                self._frame = 0
                self.image = self._images[self._frame]
                self._last_update = t
            self.image = self._images[self._frame]
            self._last_update = t
    
    def getFrame(self, screen):
        # Update Frame and Display Sprite
        self.update(pygame.time.get_ticks())
        return self.image
    

    【讨论】:

    • 看起来不错 - 您能否添加一些内容来解释您所做的工作如何帮助 OP?
    • @GHC:他正在从单个图像创建 spritesheet。然后用定时器切换image
    • 你能给我一个如何使用这个类的例子吗?我对 pygame 很陌生,很抱歉。
    猜你喜欢
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多