在 pygame 中设置陷阱的有效方法是什么?

What would be an effective way to do traps in pygame?

我一直在开发一款受名为 'I wanna be the guy' 的游戏启发的游戏,并且我已经转向了陷阱。 问题是我一直在思考如何激活它们并让它们向上射击并杀死玩家。

这是我一直在使用的东西:

#parent class
class Sprite(pygame.sprite.Sprite):
    def __init__(self, img, x, y):
        super().__init__()
        self.image = img
        self.rect = self.image.get_rect()
        self.initial_x = x
        self.initial_y = y
        self.reset()

    def reset(self):
        self.rect.x = self.initial_x
        self.rect.y = self.initial_y


#child class inheriting from Sprite
class autoHazard(Sprite):
    def set(self, x_speed, y_speed):
        self.counter = 0
        self.triggered()
        if self.counter == 1:
            self.rect.x += x_speed
            self.rect.y += y_speed

        hit = pygame.sprite.collide_rect(self, play)
        if hit:
            play.kill()
    def triggered(self):
        if play.rect.x >= self.rect.x - 76:
            self.counter = 1

#main file
... code
#outside main program loop
Trap = autoHazard(img.lul_img, 1000, con.height - 100)
grp.all_sprites.add(Trap)

Trap2 = autoHazard(img.lul_img, 800, con.height - 100)
grp.all_sprites.add(Trap2)
... code

#inside main program loop
... code
Trap.set(0,-20)
Trap2.set(0,-20)
... code

相反,它会向上移动,但它受到 autoHazard 中的 if 语句的限制,这将使其仅在玩家位置 x 大于陷阱的 x的位置。我想要的是如果不满足 if 语句条件,陷阱会突然上升并且不会停用。

What I want is for the trap to shoot up and not get deactivated

问题是,每次调用 autoHazard.set 时,self.counter 都设置为 0。如果你想让这个状态持续存在,那么你必须删除 self.counter = 0 形式 autoHazard.set。在构造函数中初始化self.counter = 0

class autoHazard(Sprite):
    def __init__(self, img, x, y):
        super().__init__()

        # [...]

        self.counter = 0

    def set(self, x_speed, y_speed):

        if self.counter == 0:
            self.triggered()
        if self.counter == 1:
            self.rect.x += x_speed
            self.rect.y += y_speed

        hit = pygame.sprite.collide_rect(self, play)
        if hit:
            play.kill()

    def triggered(self):
        if play.rect.x >= self.rect.x - 76:
            self.counter = 1