我正在用Python做一个基于文本的rpg游戏,作为一个自我项目。
我在char.py文件中有一个名为Character的类,并在mapAndclasses.py文件中从中创建了一个播放器对象。对于放置在单独文件中的战斗序列,我需要从mapAndclasses.py获取Character对象。但是,我不知道如何全局使用对象。有可能这样做吗?谢谢;-; !!
Char.py
#Char.py
class character:
def __init__(self,name,job,level,exp,curHp,maxHp,mana,strength,defence,magic,baseCrit,coordsX,coordsY):
self.name = name
self.job = job
self.level = int(level)
self.exp = float(exp)
self.curHp = int(curHp)
self.maxHp = int(maxHp)
self.mana = int(mana)
self.strength = int(strength)
self.defence = int(defence)
self.magic = int(magic)
self.baseCrit = int(baseCrit)
self.coordsX = int(coordsX)
self.coordsY = int(coordsY)
def getCharacterInfo(self):
print("Name:", self.name, "\t\tLevel:", self.level)
print("Job:", self.job, "\t\tExperience:", self.exp)
print("HP:",self.curHp, "/", self.maxHp)
print("Mana:", self.mana)
print("Str:",self.strength)
print("Def:", self.mana)
print("Magic:", self.mana)
print("Base Crit:", self.baseCrit)
mapAndclasses.py
# Load player
def loadPlayer():
saveArray = []
with open("savefile.txt") as f:
for line in f:
var,val = line.strip().split("=")
saveArray.append(val)
f.close();
global inventory
inventory = Inventory.load()
global player
# player = name, job, level, exp, curhp, maxhp, mana, strength, defence, magic, baseCrit, x, y
player = character(saveArray[0],saveArray[1],saveArray[2],saveArray[3],
saveArray[4],saveArray[5],saveArray[6],saveArray[7],
saveArray[8],saveArray[9],saveArray[10], saveArray[11], saveArray[12])
# playerCoords = [row,column]
# player always starts from the left
global playerCoords
playerCoords = [player.getCoordsX(), player.getCoordsY()]
print("\nWelcome back " + saveArray[0])
答案 0 :(得分:2)
__init__.py
。 (这只是将该目录标记为包,即告诉Python它可以从此处提取导入内容。)fightSequence.py
的顶部或您所说的任何位置,通过编写以下内容来导入变量:import mapAndclasses.py
。mapAndclasses.variableName
。答案 1 :(得分:0)
创建一个新的Python文件,例如vars.py
,并将所有变量放在此处。
然后import vars
,它将是全局的。希望对您有帮助!