在Pygame中,如何在一个事件中为不同的对象设置多个计时器?

2024-05-19 01:04:50 发布

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

所以我在Pygame里创作了一个子弹地狱风格的游戏,灵感来源于Touhou,玩家可以向多个不同的方向和不同的射击速度发射子弹。我设法借用了一些代码,使我能够实现子弹的快速射击,然后通过创建多个不同的子弹对象来扩展射击。然而,尽管我希望能够为每一个单独的子弹物体流调整重新加载速度,但我真的很困惑如何调整。有人能帮帮我吗?你知道吗

以下是子弹按预期发射所涉及的代码,所有子弹都具有相同的重新加载速度:

reloadSpeed = 50
shootingEvent = pygame.USEREVENT + 1
reloaded = True

(稍后在while循环中):

if key[pygame.K_z]:
        if reloaded:
            bulletSound.stop()
            player.shoot()
            bulletSound.play()
            reloaded = False
            pygame.time.set_timer(shootingEvent, reloadSpeed)

以下是我的Player类中的shoot函数,以及context的Bullet类:

def shoot(self):
        bullet1N = Bullet(self.rect.centerx, self.rect.top, -4, -10, lb)
        bulletCentreN = Bullet(self.rect.centerx, self.rect.top, 0, -10,db)
        bullet3N = Bullet(self.rect.centerx, self.rect.top, 4, -10, lb)
        bullet1N2 = Bullet(self.rect.centerx, self.rect.top, -2, -10, db)
        bullet2N2 = Bullet(self.rect.centerx, self.rect.top, -1, -10, db)
        bullet3N2 = Bullet(self.rect.centerx, self.rect.top, 1, -10, db)
        bullet4N2 = Bullet(self.rect.centerx, self.rect.top, 2, -10, db)

(等等,等等,很多不同类型的子弹。第一个数字代表相应的“力量”阈值中的数字流,因为在整个游戏中,随着力量的增加,我需要不同的子弹流;“N”或“S”代表该流是在正常射击期间还是在按住shift键时使用,第二个数字代表该流用于的力量级别。)

        keystate = pygame.key.get_pressed()
        if power < 16:
            if keystate[pygame.K_LSHIFT]:
                Group(bulletCentreS)

            else:
                Group(bullet1N)
                Group(bulletCentreN)
                Group(bullet3N)

        if power >= 16 and power < 48:
            if keystate[pygame.K_LSHIFT]:
                Group(bullet1S2)
                Group(bullet2S2)


            else:
                Group(bullet1N2)
                Group(bullet2N2)
                Group(bullet3N2)
                Group(bullet4N2)

(Group只是将项目符号添加到几个sprite组中的一个函数,效率稍高一些)

class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y, speedx, speedy, col):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((6, 6))
        self.image.set_alpha(100)
        self.image.fill(col)
        self.rect = self.image.get_rect()
        self.rect.bottom = y
        self.rect.centerx = x
        self.speedy = speedy
        self.speedx = speedx

    def update(self):
        self.rect.y += self.speedy
        self.rect.x += self.speedx
        # kill if it moves off the top of the screen
        if self.rect.bottom < 25:
            self.kill()
        if self.rect.x > WIDTH/2:
            self.kill()

如图所示,这会导致任何模式的每颗子弹都以相同的速度发射,尽管在某些情况下移动速度不同。你知道吗

编辑:多亏了金斯利,我才意识到我需要在我的子弹类中实现射击功能,这样不同子弹流的射击速度就可以通过每个具有firerate属性的子弹对象进行调整。。。但我该如何实现呢?你知道吗


Tags: rectimageselfdbiftopgrouppygame
1条回答
网友
1楼 · 发布于 2024-05-19 01:04:50

一种简单的技术是记录“触发”事件的实时性,并且在延时过期之前不允许进一步执行该类型的操作。你知道吗

获取可用时间戳的一种简单方法是PyGamefunctionpygame.time.getticks(),它返回自启动以来不断增加的毫秒数。你知道吗

每当用户启动触发机制时,存储时间。你知道吗

fire_time_type1 = pygame.time.getticks()  # time of last shot

还要决定触发频率延迟应该是什么,例如:

RELOAD_DELAY_TYPE1 = 300   # milliseconds

修改用户界面,使触发过程仅在延迟结束后完成:

now = pygame.time.getticks()
if ( now > fire_time_type1 + RELOAD_DELAY_TYPE1 ):
    fire_weapon_type1()
    fire_time_type1 = now
else:
    # still waiting for re-load time delay
    # play weapon-too-hot sound, etc.
    pass

显然,这种机制可以工作到类中,因此延迟发生在对象内部,而不是像本例那样发生在外部。你知道吗

通过简单地存储更多的使用时间记录,这种方法很容易实现不同的延迟。你知道吗

编辑:

也许触发类可以维护不同类型的 子弹。你知道吗

### Gun object encapsulates enough detail to track the number of shots
### from a given magazine size, enforcing a reload-delay once the
### magazine is empty
class Gun:
    def __init__( self, name, magazine_size, reload_delay=300 ):
        self.name     = name
        self.shots    = 0
        self.mag_size = magazine_size
        self.reload   = reload_delay    # milliseconds
        self.use_time = 0

    def hasBullet( self ):
       """ Check that either a bullet is available, or that the
           reload delay has expired """
       now = pygame.time.getticks()
       if ( self.shots >= self.mag_size and now > self.use_time + self.reload ):
           self.shots = 0    # reload
           print( "Debug: [%s] reloaded after %d millisecs" % (self.name, self.reload ) )
       return ( self.shots < self.mag_size )

    def trackFiring( self ):
        """ keep track of the magazine limit, and when the shot was fired """
        self.shots    += 1
        self.use_time  = pygame.time.getticks()  # time of last shot             
        print( "Debug: [%s] fired, %d rounds left" % (self.name, self.mag_size - self.shots ) )



### ...

nail_gun = Gun( 'nail', 200, 500 )  
rockets  = Gun( 'rocket', 3, 1000 )
bfg      = Gun( 'BFG (oh yes!)', 1, 5000 )

### ...

# Player activates rocket launcher~
if ( rockets.hasBullet() ):
    rockets.trackFiring()
    shoot( ... )

很明显,子弹射击可以在Gun类中使用,但这是留给读者的练习。你知道吗

注意:我没有测试编译这段代码,小错误和遗漏预期。你知道吗

相关问题 更多 >

    热门问题