0

Using a guide to help me produce a pygame platformer game, I have come across a coding concept that baffles me, in relation to my code, that is.

https://youtu.be/G8pYfkIajE8?t=4m1s

In this tutorial, he talks about creating a 'reference' so that the class recognises objects that have already been created.

The sprite groups in one file would therefore be able to be recognised in another.

In my code, I need to add the bullet sprite, which is created in the 'PlayerClass' file, into the sprite group, which is located in the 'base' file.

My bullet object is called by this code (from a third file GameClass):

def shoot(self):
    print('Pew pew')

    bullet=Bullet.movebullet(self)

The following code is referenced in the above line Bullet.movebullet(self)

class Bullet(pygame.sprite.Sprite):

    def __init__(self,speed,Game):
        self.speed=speed
        self.image=pygame.Surface((10,10))
        self.rect=self.image.get_rect()

    def movebullet(self):
        self.rect.center=((self.x+self.speed),self.y)
        print('pew spew again')

The sprite groups are defined in my games class, located in the GameClass file.

class Game:
    def __init__(self):
        pass

    def run(self):
        sprites=pygame.sprite.Group()
        platforms=pygame.sprite.Group()
        ground=GameClass.Platform(0,700,1920,80,BLACK)
        middlewall=GameClass.Platform(500,600,30,100,BLACK)

        platforms.add(ground)
        platforms.add(middlewall)

        platforms.draw(display)

        player1=PlayerClasses.Player('Spy',1.5,5,5,200,200)
        sprites.add(player1)

        return sprites,platforms,player1

How would I reference the groups created in the Game class in the bullet file?

scrpy
  • 985
  • 6
  • 23
Link
  • 317
  • 1
  • 5
  • 17
  • you should create bullet instance with `bullet = Bullet()` and later move it with `bullet.movebullet()` – furas Dec 16 '17 at 22:29
  • you can send all groups to `Player` when you create it `player1 = PlayerClasses.Player('Spy', ..., [sprites, platforms, ...])` and player can use them when it creates bullet. – furas Dec 16 '17 at 22:34
  • BTW: `Sprite` has method to [Sprite.groups](http://pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite.groups) – furas Dec 16 '17 at 22:37
  • I've just posted a complete bullet example [here](https://stackoverflow.com/a/47853276/6220679). The `self.all_sprites` and `self.bullet_group` attributes are references to the groups in the `main` function. – skrx Dec 17 '17 at 08:22

0 Answers0