Arjun Sharma
Arjun Sharma

Reputation: 71

Pygame: How to call defined variable that is inside a class in my main game loop?

So, i'm making some stupid platform game, and i'm currently working with a projectile. Right now everything works fine, but I don't know how to make the projectile move left, I can only move it right. I have a variable called 'Bullet' that is inside a class, but I don't know how to call it in the main loop. When ever I try to call it, its not defined. Heres my code for the bullet:

        def shoot(self):
            if self.ammo > 0:
                Bullet = bullet(self.Game,self.rect.x,self.rect.top)
                self.Game.all_sprites.add(Bullet)
                self.Game.bullets.add(Bullet)
                self.ammo -= 1

Heres the bullet class

class bullet(pg.sprite.Sprite):
    def __init__(self, Game,x,y):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.image.load('magicBullet.png')
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.Game = Game
        self.Player = Player
        self.speed = 10

    def update(self):
        self.rect.x += self.speed

Can anyone help?

Upvotes: 1

Views: 222

Answers (1)

Rabbid76
Rabbid76

Reputation: 210909

Why start the variable name with a capital letter and the class name is lowercase? It should be the other way around. See Style Guide for Python Code - Class Names


Anyway, you have to define the direction of movement when the bullet spawns.

Add an additional argument for the speed to the constructor of the class bullet:

class bullet(pg.sprite.Sprite):
    def __init__(self, Game, x, y, speed):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.image.load('magicBullet.png')
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.Game = Game
        self.Player = Player
        self.speed = speed

    def update(self):
        self.rect.x += self.speed

Add an argument which defines the direction to the method shoot. The accepted values for the argument direction are either -1 for the movement to the left or 1 for the movement to the right:

def shoot(self, direction):
    if self.ammo > 0:

        speed = 10 * direction

        Bullet = bullet(self.Game, self.rect.x, self.rect.top, speed)

        self.Game.all_sprites.add(Bullet)
        self.Game.bullets.add(Bullet)
        self.ammo -= 1

Upvotes: 2

Related Questions