让模块文件使用全局变量?

Let a module file use a global variable?

如果这只是一个超级简单的解决方案,请原谅我,因为我是 Python 的新手。现在我正在尝试制作一个基本的视频游戏,为了节省 space 我决定为战斗遭遇制作一个模块——这样我在为每次遭遇编写代码时所要做的就是 运行那个模块里的函数,只需要写敌人特有的变量。但是,代码需要知道玩家的 HP 或玩家拥有的武器类型等信息。我尝试将 global 放在函数模块中的变量之前,但当然它不起作用,因为这是在模块中引用全局变量,而不是主游戏文件。或者还有另一种方法可以解决这个问题吗?如果您需要我附上我的代码,我很乐意这样做。

编辑:这是模块中的代码(称为 combat)。我想让它做的是主文件的代码只会说:

combat.combat(3, "mysterious creature", 12, 2, 4, 3, "claws", 5, 0)

根据我浅薄的理解,我是如何为每个对手编辑变量的,它来自模块文件中的这一行。

def combat(enemylevel, enemyname, enemyhp, enemydefense, enemystrength,
           enemyattack, enemyweaponattack, enemygp, run):

基于你们的困惑,我猜我做的是一些非常基本的错误。原谅我(很可能)的卑鄙和低效的代码编写:

import random
import math
def combat(enemylevel, enemyname, enemyhp, enemydefense, enemystrength, 
           enemyattack, enemyweaponattack, enemygp, run):
    global xp
    global hp
    global maxhp
    global gp
    global weapon_attack
    global weapon
    levelandname = "level" , enemylevel, enemyname
    print("You draw your weapon and prepare for battle. You are fighting a",
          levelandname, ".")
    while enemyhp > 0:
        if enemyhp > 0:
            print()
            attackorrun = input("Do you wish to attack or run? ")
            if attackorrun == "attack" or "a":
                print("You" , weapon_attack , "your" , weapon, "at the",
                      enemyname) # this is where the first error happens,
                                 # says weapon_attack isn't defined.
                attackroll = random.randint(1, 20)
                attackroll = (attackroll+(math.floor(attack/2)))

我可能还有一些不清楚的地方,请随时告诉我做其他事情或问我一些事情。

使用大量全局变量会变得混乱。它没有为您提供太多灵活性,而且正如您所发现的,很难从其他模块访问这些变量。

许多程序员会避免在函数中使用全局语句,函数需要的任何数据都应通过其他方式提供。

使用容器对象可能是一个好的开始,将相关变量放在一起,也许在 dictionary. You could pass an enemy dict (with hp, defense, strength etc.) and a player dict (xp, hp, weapon etc.) in to your function. That would give you access to those values in the function, and the function would even be able to modify those values (because you would be passing an object reference).

enemy = {'hp': 100, 'weapon': 'axe', 'strength': 50}
player = {'xp': 22, 'hp': 150, 'weapon': 'sword'}
def combat(player, enemy):
    #calculate results of combat
    player['hp'] = player['hp'] - damage

另一种策略可能是使用 classes。 类 是可以包含函数和变量的对象定义。您可以实例化 class 的多个实例。例如,一个 Enemy 对象(一个 Enemy class 的实例)将包含一个敌人的 hp 变量,以及在战斗中修改它的函数。