按 space 时使图像出现 300ms

Make image appear for 300ms when pressing space

我之前问过这个问题,但我想我自己表述错误,所以这次我会添加图片。

我有一个游戏,屏幕底部有一个人(实际上是唐纳德特朗普)向来袭的敌人向上发射子弹到屏幕顶部。

他有一把枪,在枪管的末端我想补充一点,当我按space时会出现一个火焰精灵,300ms后它会消失(直到我按space 再次循环)。

这是游戏图片和我的意思:

1 = 没有按键

2 = Space 被按下

3 = Space 不再按下,超过 300 毫秒,现在我希望火焰精灵消失,直到再次按下 space

我该怎么做? :)

只需创建一个变量,在按下按键时存储超时值,并从该值中减去每帧经过的时间。

如果该值 > 0,则显示带有火焰的图像。如果该值为 0,则显示没有火的图像。

这是我一起破解的一个简单示例:

import pygame

class Actor(pygame.sprite.Sprite):
    def __init__(self, *grps):
        super().__init__(*grps)
        # create two images:
        # 1 - the no-fire-image
        # 2 - the with-fire-image
        self.original_image = pygame.Surface((100, 200))
        self.original_image.set_colorkey((1,2,3))
        self.original_image.fill((1,2,3))
        self.original_image.subsurface((0, 100, 100, 100)).fill((255, 255, 255))
        self.fire_image = self.original_image.copy()
        pygame.draw.rect(self.fire_image, (255, 0, 0), (20, 0, 60, 100))

        # we'll start with the no-fire-image
        self.image = self.fire_image
        self.rect = self.image.get_rect(center=(300, 240))

        # a field to keep track of our timeout
        self.timeout = 0

    def update(self, events, dt):

        # every frame, substract the amount of time that has passed
        # from your timeout. Should not be less than 0.
        if self.timeout > 0:
            self.timeout = max(self.timeout - dt, 0)

        # if space is pressed, we make sure the timeout is set to 300ms
        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_SPACE]:
            self.timeout = 300

        # as long as 'timeout' is > 0, show the with-fire-image 
        # instead of the default image
        self.image = self.original_image if self.timeout == 0 else self.fire_image

def main():
    pygame.init()
    screen = pygame.display.set_mode((600, 480))
    screen_rect = screen.get_rect()
    clock = pygame.time.Clock()
    dt = 0
    sprites_grp = pygame.sprite.Group()

    # create out sprite
    Actor(sprites_grp)

    # standard pygame mainloop
    while True:
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:
                return

        sprites_grp.update(events, dt)

        screen.fill((80, 80, 80))
        sprites_grp.draw(screen)
        pygame.display.flip()
        dt = clock.tick(60)

if __name__ == '__main__':
    main()