微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

是否可以向 pygame Sprite 显示颜色变化?

如何解决是否可以向 pygame Sprite 显示颜色变化?

我有一个通过 Font 生成的 pygame Sprite。它只是一个 16x16 的表面,上面印有一个字母并被 blitted。

精灵有一个计时器(它是一个通电),当它接近生命的尽头时,我希望它在每次更新时闪烁随机颜色。我已经成功地用其他文本做到了这一点,但该文本不是一个精灵,只是一个我在记分板上 blit 的字符串。我想这会是一样的,但是一旦生成精灵,无论我改变精灵的颜色多少,更改都不会转换到屏幕上(尽管如果我 print(self.color) 我可以看到更新的颜色元组在控制台中)。

我尝试将随机颜色选择器放在 Class 内,并在我的 while 循环中尝试在课堂外使用。我可以很容易地改变颜色,但屏幕上的精灵实际上并没有改变。我没有使用外部精灵图像,只是一个 Font blitted 到 pygame.Surface。

这是我的物品类别。

class Item(pygame.sprite.Sprite):
    def __init__(self,name,pos):
        pygame.sprite.Sprite.__init__(self)
        self.name = name
        self.image = pygame.Surface([16,16])
        self.image.set_colorkey(black)
        self.font = pygame.font.Font("./fonts/myfont.ttf",16)
        self.pos = pos
        if self.name == "health":
            self.color = (255,0)
            self.text = self.font.render("H",True,self.color)

        self.lifespan = 200
        self.lifespan_counter = 0
     
        self.image.blit(self.text,(0,0))

    def update(self):
        # Update timer
        self.lifespan_counter += 0.1
        if self.lifespan_counter >= self.lifespan:
            self.kill()
        # Update position
        self.rect.center = (int(self.pos[0]),int(self.pos[1]))

然后在 while 循环中 def main()底部我有这样的东西:

        random_color_counter += 1
        if random_color_counter > 3:
            random_color = get_random_color()
            random_color_counter = 0

        screen.fill(background)
        text_Box.fill(blue)
        game_Box.fill(white)

        # Update the sprites positions and then draw them to game_Box surface
        player_sprites.update()
        player_bullet_sprites.update()
        enemy_sprites.update()
        enemy_bullet_sprites.update()
        item_sprites.update()

        player_sprites.draw(game_Box)
        player_bullet_sprites.draw(game_Box)
        enemy_sprites.draw(game_Box)
        enemy_bullet_sprites.draw(game_Box)
        item_sprites.draw(game_Box)

        ...

        for i in item_sprites:
            game_Box.blit(i.image,(int(i.pos[0]),int(i.pos[1])))

        # Refresh everything
        pygame.display.update()

这是选择新颜色的函数

def get_random_color():
    r = random.randint(0,255)
    g = random.randint(0,255)
    b = random.randint(0,255)
    return r,g,b    

然后我可以在大多数情况下使用颜色 random_color,但显然不是精灵。

就像我说的,这在它应该显示的位置(坏人死亡的地方)很好地显示了精灵,但我似乎无法将项目精灵颜色转换到屏幕上。我只是没有看到我做错了什么。

解决方法

当你想改变文本的颜色时,你必须再次渲染文本并更新文本Surface。编写一个 change_color 方法:

class Item(pygame.sprite.Sprite):
    # [...]

    def change_color(self,color):
        self.image = pygame.Surface([16,16])
        self.image.set_colorkey(black)
        self.color = color
        self.text = self.font.render("H",True,self.color)
        self.image.blit(self.text,(0,0))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。