按sp键时使图像显示300ms

2024-09-30 12:22:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我之前问过这个问题,但我认为我的表述是错误的,所以这次我将添加图片

我有一个游戏,里面有一个人(实际上是唐纳德·特朗普)在屏幕的底部,朝屏幕的顶部向来袭的敌人射击

他有一把枪,在枪管的末端,我想补充一点,当我按下空格键时,会出现一个火焰精灵,300毫秒后它就会消失(直到我再次按下空格键,循环继续)

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

1=没有按键

2=按下空格

3=空间不再被按下,超过300毫秒已经过去,现在我希望火焰精灵消失,直到空间再次被按下

1

我该怎么做?:)


Tags: 游戏屏幕错误空间图片按键精灵空格
1条回答
网友
1楼 · 发布于 2024-09-30 12:22:48

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

如果该值大于;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()

相关问题 更多 >

    热门问题