让模块文件使用全局变量? [英] Let a module file use a global variable?

查看:103
本文介绍了让模块文件使用全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这只是一个超级简单的解决方案,请原谅我,因为我是Python的新手.现在,我正在尝试制作一个基本的视频游戏,并且为了节省空间,我决定制作一个用于战斗遭遇的模块-这样,每次编写代码时,我要做的就是在该模块中运行该功能,只需要编写敌人的独特变量即可.但是,代码需要了解玩家的HP或玩家拥有哪种武器等知识.我尝试将global放在功能模块中的变量之前,但是当然不起作用,因为它引用模块中的全局变量,而不是主游戏文件.还是有另一种方法可以解决这个问题?如果您需要我附上我的代码,我会很乐意这样做.

Forgive me if this is just a super easy solution as I am pretty new to Python. Right now I'm trying to make a basic video game, and to save space I decided to make a module for a combat encounter -- so that all I have to do when writing the code for each encounter is run the function in that module, only having to write the unique variables of the enemy. However, the code needs to know things like the player's HP, or what kind of weapon the player has. I tried putting global before the variables in the function module, but of course it doesn't work, as that's referencing global variables in the module, not the main game file. Or is there another way to go about this? If you need me to enclose my code, I will gladly do so.

此处为模块中的代码(称为combat).我要它做的是主文件的代码只会说:

Heres the code, in the module (called combat). What I want it to do is the main file's code will just say:

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

根据我的浅浅理解,这是我如何从模块文件中的这一行编辑每个对手的变量.

Which, based off my shallow understanding, is how i edit the variables for each oppoent, its from this line in the module file.

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

基于你们的困惑,我猜我在做一些非常基本的错误.原谅我的(最有可能的)虚弱和低效率的代码编写:

Based off you guys' confusion I'm guessing I'm doing something pretty basic wrong. Forgive my (most likely) cringey and ineffecient code-writing:

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)))

我可能仍然不清楚,可以随时告诉我做其他事情或问我一些事情.

I'm probably still leaving something unclear, feel free to tell me to do something else or ask me something.

推荐答案

使用大量的全局变量可能会造成混乱.它并没有为您提供很大的灵活性,而且正如您所发现的那样,很难从其他模块访问这些变量.

Using large numbers of global variables can get messy. It doesn't provide you much flexibility, and as you're discovering, its hard to access those variables from other modules.

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

Many programmers will avoid using the global statement in a function, any data the function needs should be provided by other means.

使用容器对象可能是一个好的开始,可以将相关变量保持在一起,也许放在 dictionary .您可以将敌人的命令(具有hp,防御,力量等)和玩家的命令(xp,hp,武器等)传递给您的功能.这样您就可以访问函数中的这些值,并且该函数甚至还可以修改这些值(因为您将传递

Using container objects might be a good start, keeping related variables together, perhaps in a 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

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

Another strategy might be to use classes. Classes are object definitions that can contain functions and variables. You can instantiate multiple instances of your class. An Enemy object (instance of an Enemy class) for example would contain an enemy hp variable, and functions that modify it during combat.

这篇关于让模块文件使用全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆