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

标签 python pygame pyscripter

我一直在开发一款游戏,其灵感来自于一款名为“我想成为那个人”的游戏,并且我已经进入了陷阱。 问题是我一直纠结于如何激活它们并让它们射击并杀死玩家。

这是我一直在做的事情:

#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。如果您想让此状态持久存在,则必须从 autoHazard.set 中删除 self.counter = 0。在构造函数中初始化 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

关于python - 在 pygame 中设置陷阱的有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59596413/

相关文章:

python-3.x - 关于 PyScripter 中 python 解释器的字体

python - 如何让 PyScripter 中的类型指示器显示在我单击的行的末尾?

python - 在 pygame 中,重置每个 Sprite 位置的最有效方法是什么?

python 包导入模块使用 __init__.py

python - 如何通过 Python 查找与 Windows 文件关联的图标?

python - 在python中创建一个按钮

python - Pygame - 两名玩家的射击功能

python - 如何使用KEYDOWN?

Python递归函数,打印反向数字

python - ipython Pandas 类型错误 : read_csv() got an unexpected keyword argument 'delim-whitespace' '