0

So Im trying to write a program with classes, and want to use a variable from one class in another. Just what the title says really. For context the variable is called self.stage, and heres the code for the classes:

class Game:
    def newLevel(self):
        if self.player.stage == '2':
            self.map = Map(path.join(gameFolder, 'Level2.txt'))
        if self.player.stage == '3':
            self.map = Map(path.join(gameFolder, 'Level3.txt'))    
        if self.player.stage == '4':
            self.map = Map(path.join(gameFolder, 'Level4.txt'))

class Player:
    def portalCollide(self, dir):
        self.stage = 1
        if dir == 'x':
            hits = pygame.sprite.spritecollide(self, self.game.portals, False)
            if hits:
                self.stage = self.stage + 1
                self.game.newLevel()
        if dir == 'y':
            hits = pygame.sprite.spritecollide(self, self.game.portals, False)
            if hits:
                self.stage = self.stage + 1
                self.game.newLevel()

Thanks for any help

JustNat
  • 11
  • 2
  • Why did you try to destroy the answer? You asked the question, but it is not up to you to "remove" answers or to vandalize answers. – Rabbid76 Sep 13 '21 at 08:44

1 Answers1

0

You cannot "get a variable from a class". You can read an attribute of an Instance Object. Read about the concept of Classes. The instance attribute should be constructed in the constructor (__init__) of the class.


e.g.: Create an instance of the class Player in the constructor of the class Game:

class Game:
    def __init__(self):
        self.player = Player()

    def newLevel(self):
        if self.player.stage == '2':
            self.map = Map(path.join(gameFolder, 'Level2.txt'))
        if self.player.stage == '3':
            self.map = Map(path.join(gameFolder, 'Level3.txt'))    
        if self.player.stage == '4':
            self.map = Map(path.join(gameFolder, 'Level4.txt'))

class Player:
    def __init__(self):
        self.stage = 1

    def portalCollide(self, dir):
        self.stage = 1
        if dir == 'x':
            hits = pygame.sprite.spritecollide(self, self.game.portals, False)
            if hits:
                self.stage = self.stage + 1
                self.game.newLevel()
        if dir == 'y':
            hits = pygame.sprite.spritecollide(self, self.game.portals, False)
            if hits:
                self.stage = self.stage + 1
                self.game.newLevel()

Alternatively you can pass the player object to the constructor of the class Game:

class Game:
    def __init__(self, player):
        self.player = player

    # [...]

class Player:
    def __init__(self):
        self.stage = 1

    # [...]
player = Player()
game = Game(player)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174