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

时间:2019-01-20 20:13:25

标签: python pygame

我是python和pygame的新手,正在尝试自学,因此,我是菜鸟。 现在,我正在尝试编写各种“过场动画”(这将是一个黑屏,具有声音效果和在特定时间播放和显示的文字),可以随时通过按Escape键来跳过。到目前为止,这就是我要的内容(我尚未添加文字):

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()使声音在播放之前等待一会儿,但是,当然,这会延迟所有输出的出现,因此实际上并没有通过按Escape来跳过过场动画,直到所有声音都已播放,但是简短。 我知道可以使用pygame.time.set_timer来解决此问题(或者至少希望如此)。但是,我一生都无法弄清楚该命令的使用方式。

1 个答案:

答案 0 :(得分:2)

您基本上有两件事要做:

  • 跟踪您的游戏正在运行的当前场景。典型的场景包括简介主菜单实际游戏信用等。
  • 保持时间跟踪,以便您可以维护要运行的时间点和动作的列表。

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

想法是

  • 具有在场景之间切换的简便方法。这是通过使用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