如何避免全局变量(和使用类?)Python

2024-09-29 19:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

学习Python,尤其是面向对象编程。我正在创建一个简单的基于文本的游戏。我有点纠结于全局变量的使用。人们说最好避开他们。你知道吗

我的问题是,如果没有它们,我怎样才能让事情正常运行,以及在哪里声明这些变量。你知道吗

目前,在main()方法中,我将根据游戏中可能发生的每个房间或交互的类来启动游戏。 但是有一些我想随时访问的对象,比如敌人或者主角,比如生命值,库存等等(见代码)。你知道吗

我用这些变量创建了一个全局变量,以便随时访问它,但我认为我不应该这样做。你知道吗

有什么建议我该怎么做吗?你知道吗

class Character(object):

    def __init__(self, location, accuracy):
            self.current_health = 100
        self.max_health = 100
        self.max_ammo = 20
        # self.current_ammo = 0
        self.current_ammo = 20
        # self.inventory = {}
        self.inventory = {'Gun': True}
        self.location = location
        self.accuracy = accuracy


class MainCharacter(Character):
    # some extra attributes only for the main character


class EnemyChar(Character):

    def __init__(self, location, accuracy, can_see_you=True):
        self.type = 'Alien'
        self.can_see_you = can_see_you
        super(EnemyChar, self).__init__(location, accuracy)


def main():
    # Some globals to be able to access anytime
    global enemies, main_char, keypad


    # Where we start
    first_room = 'first_room'

    # Enemies
    enemies = {
        #'Enemy_1': EnemyChar('small_ally', 30, False),
        'Enemy_1': EnemyChar(first_room, 30, False),
        'Enemy_2': EnemyChar(first_room, 90)
    }

    # You
    main_char = MainCharacter(first_room, 50)

    # Stuff to interact with
    keypad = Keypad()

    map = Map(first_room)
    game = GameEngine(map)
    game.play()


if __name__ == '__main__':
    main()

目前它适用于我的全局变量,但我认为这不是“正确”的方法。你知道吗


Tags: self游戏initmaindeflocationcurrentclass
1条回答
网友
1楼 · 发布于 2024-09-29 19:23:43

这通常是通过使用一些全局类作为所有这些变量的容器来解决的。例如:

class Game:
    def __init__(self):
        # Where we start
        self.first_room = 'first_room'

        # Enemies
        self.enemies = {
            #'Enemy_1': EnemyChar('small_ally', 30, False),
            'Enemy_1': EnemyChar(self.first_room, 30, False),
            'Enemy_2': EnemyChar(self.first_room, 90)
        }

        # You
        self.main_char = MainCharacter(self.first_room, 50)

        # Stuff to interact with
        self.keypad = Keypad()

        self.map = Map(self.first_room)
        self.game = GameEngine(map)

    def play(self):
        self.game.play()

等等。现在,当您需要这些变量中的一个时,您可以创建接受Game对象的函数,或者使该函数成为Game类的方法。在你的情况下,你可能会使用游戏引擎,而不是游戏。你知道吗

相关问题 更多 >

    热门问题