python - 如何在 pygame 中使用 pygame.time.set_timer() ?

标签 python pygame

我是 python 和 pygame 的新手,正在尝试自学,所以我自然是个菜鸟。 现在,我正在尝试编写某种“过场动画”(它只是一个黑屏,带有声音效果和在特定时间播放和显示的文本),可以通过按转义键随时跳过。这是我到目前为止这部分的内容(我还没有添加文本):

def play_crash():
    pygame.time.delay(500)
    cutsc_crash.play(0)

def play_fwoosh():
    pygame.time.delay(2000)
    cutsc_fwoosh.play(0, 0, 50)

def play_burn():
    pygame.time.delay(2050)
    cutsc_fire.play(0, 15000, 0)

def play_run():
    pygame.time.delay(2500)
    cutsc_run.play()

def intro_cutscene():

    pygame.mixer.music.stop()
    gameDisplay.fill(black)
    pygame.display.update()

    Skip_Cut = False
    play_audio = True

    while not Skip_Cut:
        Clock.tick(60)
        pygame.key.get_pressed()
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    Skip_Cut = True
                if event.key == pygame.K_RETURN:
                    print("in a perfect universe, this would do something more significant.")
            if event.type == pygame.QUIT:
                print("Ending program.")
                pygame.quit()
                quit()
        if play_audio:
            play_crash()
            play_fwoosh()
            play_burn()
            play_run()
            play_audio = False
            pygame.display.update()

    if Skip_Cut:
        pygame.display.update()
        pygame.mixer.stop()
        print("Skipping cutscene...")
        print(game_test())

到目前为止,我正在使用 pygame.time.delay() 使声音在播放前等待一段时间,但是当然,这会延迟所有输出的出现,因此不会'实际上,您可以通过按“Esc”键来跳过过场动画,直到播放完所有声音(无论多么简短)。 我知道这个问题可以通过使用 pygame.time.set_timer 来解决(或者至少我希望如此)。但是,我一生都无法弄清楚如何准确地使用该命令。

最佳答案

你基本上有两件事要做:

  • 跟踪游戏当前运行的场景。典型场景包括介绍主菜单实际游戏制作人员名单等。
  • 跟踪时间,以便您可以维护一个时间点和要运行的操作的列表。

下面是一个简单的、可运行的示例(请注意注释)。

这个想法是

  • 有一种在场景之间切换的简单方法。这是通过使用 GroupSingle 来完成的,每个场景都有一种方法来启用下一个场景。
  • 拥有一个定时操作列表,并在正确的时间点运行它们

代码如下:

import pygame
import pygame.freetype
import random

# Just a ball that falls down
class Ball(pygame.sprite.Sprite):
    def __init__(self, *groups):
        super().__init__(*groups)
        self.image = pygame.Surface((32, 32))
        self.image.set_colorkey((0, 0, 0))
        self.image.fill((0, 0, 0))
        self.rect = self.image.get_rect()
        pygame.draw.circle(self.image, pygame.Color('orange'), self.rect.center, 15)
        self.pos = pygame.Vector2(random.randint(0, 200), -10)
        self.rect.center = self.pos
        self.direction = pygame.Vector2(0, 0.1)

    def update(self, events, dt):
        self.direction += pygame.Vector2(0, 0.02)
        self.pos += self.direction * dt
        self.rect.center = self.pos
        if not pygame.display.get_surface().get_rect().colliderect(self.rect):
            self.kill()

# The actual game. Well, actually, it does nothing but switching back to the cutscene
class Game(pygame.sprite.Sprite):
    def __init__(self, font):
        super().__init__()
        self.switch = None
        self.image = pygame.display.get_surface().copy()
        self.image.fill(pygame.Color('darkred'))
        font.render_to(self.image, (10, 30), 'playing a game...', fgcolor=pygame.Color('orange'))
        self.rect = self.image.get_rect()

    def update(self, events, dt):
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE and self.switch:
                    self.switch()

# the scripted cutscene
class Cutscene(pygame.sprite.Sprite):
    def __init__(self, font):
        super().__init__()
        self.font = font
        self.switch = None
        self.image = pygame.display.get_surface().copy()
        self.back_colors = {-1: pygame.Color('grey12'), 1: pygame.Color('black')}
        self.back_color = 1
        self.background()
        self.rect = self.image.get_rect()
        # we keep track of time to know when to do what action
        self.timer = 0
        self.sprites = pygame.sprite.Group()
        # we keep this list of actions, so after 500ms we create the first ball etc
        # after 3 seconds, we change the background color etc.
        # after 4 seconds, we start all over again
        self.org_actions = [
            (500, lambda: Ball(self.sprites)),
            (600, lambda: Ball(self.sprites)),
            (1000, lambda: Ball(self.sprites)),
            (2000, lambda: Ball(self.sprites)),
            (2100, lambda: Ball(self.sprites)),
            (2400, lambda: Ball(self.sprites)),
            (3000, lambda: self.switch_background()),
            (3200, lambda: Ball(self.sprites)),
            (4000, lambda: self.reset_timer())
        ]
        self.actions = self.org_actions

    def reset_timer(self):
        self.timer = 0
        self.actions = self.org_actions

    def switch_background(self):
        self.back_color *= -1

    def background(self):
        self.image.fill(self.back_colors[self.back_color])
        self.font.render_to(self.image, (10, 30), 'press [ESC] to quit', fgcolor=pygame.Color('white'))

    def update(self, events, dt):
        # we switch to a different scene when the player presses ESC
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE and self.switch:
                    self.switch()

        # keep track of time
        self.timer += dt

        # do all actions 
        for action in [action for action in self.actions if action[0] <= self.timer]:
            action[1]()

        # remove all actions that are in the past
        self.actions = [action for action in self.actions if action[0] > self.timer]

        # update our own sprites and draw stuff
        self.sprites.update(events, dt)
        self.background()
        self.sprites.draw(self.image)

def main():
    font = pygame.freetype.SysFont(None, 20)
    font.origin = True
    screen = pygame.display.set_mode((300, 300))
    clock = pygame.time.Clock()
    scene = pygame.sprite.GroupSingle()

    game = Game(font)
    cutscene = Cutscene(font)
    game.switch = lambda: scene.add(cutscene)
    cutscene.switch = lambda: scene.add(game)
    scene.add(cutscene)
    dt = 0

    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.QUIT:
                return
        screen.fill((200,200,200))
        scene.draw(screen)
        pygame.display.update()
        scene.update(events, dt)
        dt = clock.tick(60)

if __name__ == '__main__':
    pygame.init()
    main()

enter image description here


如果你想了解更多关于pygame.time.set_timer的信息,你可以看看 this answer .

关于python - 如何在 pygame 中使用 pygame.time.set_timer() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54280545/

相关文章:

graphics - 求以椭圆为界最大面积的等腰三角形的坐标

python - 使用 Anaconda 安装 pygame

python - 除了 (MyClass, self) 之外,您还会将其他任何内容传递给 super() 吗?

python - Pygame 缩放 Sprite

python - 为什么PyGame动画闪烁

python - polyfit() 获得意外的关键字参数 'w'

python - Pygame 加载图像

python - 如何在 pandas 中查找子组统计数据?

python - 如何从应用程序引擎中的数据存储区获取基于时间的实体

python - python 3.5 matplotlib 安装错误