Search code examples
pythonpygamepyscripter

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


Been working on a game inspired from a game called 'I wanna be the guy', and I've moved onto traps. The problem is I've been stuck on how to activate them and make them shoot up and kill the player.

Here's what I have been working with:

#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

What instead happens is that it will move up, but it is restricted by the if statement in autoHazard, which will make it only move when player position x is greater than the trap's x position. What I want is for the trap to shoot up and not get deactivated if the if statement condition is not met.


Solution

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

    The issue is, that self.counter is set 0 every time when autoHazard.set is called. If you want to make this state persistent then you have to remove self.counter = 0 form autoHazard.set. Initialize self.counter = 0 in the constructor:

    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