首页 > 解决方案 > Pygame淡入黑功能

问题描述

我正在使用 pygame 最新版本在 python 3 中编写游戏。我有一个旨在慢慢淡化屏幕直到它完全变黑的功能。它应该通过在屏幕上多次对低 alpha 黑色表面进行 blitting 来实现。

但是当我测试它时,它只会阻止游戏直到循环完成。我怀疑 black_surface 的 alpha 有问题。

我在论坛上看到了一些关于 pygame 中的淡入淡出的问题,但没有一个问题直接涉及函数中的淡入淡出。

这是代码:

def fade_to_black(screen):
    black_surface = Surface((screen.get_width(), screen.get_height()), flags= SRCALPHA)
    color = (255, 255, 255, 1)
    black_surface.fill(color)
    alpha_key = 1
    while alpha_key <= 255:
        screen.blit(black_surface, screen.get_rect())
        display.flip()
        alpha_key = alpha_key + 1
        time.wait(1)

我查看了文档和论坛,但找不到任何解决方案。希望这不是我会错过的明显问题...感谢您的帮助!

标签: python-3.xpygame

解决方案


您创建了一个名为 的曲面black_surface,但您将其填充为白色。用黑色填充它(例如。(0, 0, 0, 1))并且可能会工作,但还有另一个问题:

当您display.flip()在更改屏幕表面的循环内调用时,如果您不让 pygame 处理事件(例如通过调用pygame.event.get()),则显示可能实际上不会更新,具体取决于您的操作系统。此外,当您的循环运行时,您不能手动处理事件,例如QUIT事件。因此,当您的屏幕变黑时,您无法退出游戏。

一般来说,你应该只有一个主循环,而不是调用像这样的阻塞函数pygame.time.sleep,但当然也有例外)。

这是Sprite基于简单的示例:

import pygame

class Fade(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.rect = pygame.display.get_surface().get_rect()
        self.image = pygame.Surface(self.rect.size, flags=pygame.SRCALPHA)
        self.alpha = 0
        self.direction = 1

    def update(self, events):
        self.image.fill((0, 0, 0, self.alpha))
        self.alpha += self.direction
        if self.alpha > 255 or self.alpha < 0:
            self.direction *= -1
            self.alpha += self.direction

def main():
    pygame.init()
    screen = pygame.display.set_mode((500, 500))
    sprites = pygame.sprite.Group(Fade())
    clock = pygame.time.Clock()

    while True:
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:
                return
        sprites.update(events)
        screen.fill((30, 30, 30))
        pygame.draw.rect(screen, pygame.Color('dodgerblue'), (100, 100, 100, 100))
        sprites.draw(screen)
        pygame.display.update()
        clock.tick(60)

if __name__ == '__main__':
    main()

在此处输入图像描述


推荐阅读