我无法复制这两个文件中的所有代码,因为它超过1000行,但实际上我正在创建一个具有变量'strength','endurance','strength','的程序灵巧','智慧','智慧'和'运气'(这是一场RPG游戏)我试图让变量'伤害',这是一个'强度'*'灵巧'/ 100的等式,到另一个文件。所有这些变量都在专门用于创建角色的文件中的函数character()内,并且我试图在主游戏的另一个文件中再次调用这些变量,在一个名为fight()的变量中。我尝试了很多东西,比如全局变量和使用return,但没有任何东西对我有用。如果我解释得不好,我很抱歉,如果您有任何问题请发表评论。
有问题的代码。
character.py
def character():
#tons of stuff go here
global damage
damage = strength * dexterity / 100
game.py
def fight():
choice = input('(Type in the corresponding number to choose.) ')
global enemy_health
global damage
if choice == 1:
print ' '
print enemy_health,
enemy_health += -damage
print '-->', enemy_health
感谢您的时间。
答案 0 :(得分:1)
我猜你可以尝试将character.py导入game.py。
game.py :(已编辑)
import character
character_health = character.health
character_strength = character.strength
def fight():
...
但是,请使用课程。
编辑:示例类
game.py:
class Character(object):
def __init__(self, health, strength):
self.health = health
self.strength = strength
self.alive = True
def check_dead(self):
self.alive = not(self.health)
def fight(self, enemy):
self.health -= enemy.strength
enemy.health -= self.strength
self.check_dead()
enemy.check_dead()
if __name__ == "__main__":
player = Character(300, 10) # health = 300, strength = 10
enemy = Character(50, 5) # health = 50, strength = 5
player.fight(enemy)
print("Player's health: {}\nIs he alive? {}\nEnemy's health: {}\nIs he alive? {}".format(player.health, player.alive, enemy.health, enemy.alive))