为什么我的模块在Python

时间:2015-05-31 03:38:55

标签: python

我正在使用Python创建一个基于文本的冒险游戏,这是我的代码。

#game.py
import time
import encounter

#Hp at start of game
hp = 100

#Function to display the current hp of the current player
def currenthp(hp):
    if hp < 100:
        print "Your hp is now at %d" % hp
    elif hp <= 0:
        dead()
    else:
        print "You are still healthy, good job!"

print "You start your regular trail."
print "It will be just a little different this time though ;)"

#Start of game
time.sleep(3)
print "You are walking along when suddenly."
time.sleep(1)
print "..."
time.sleep(2)

#Start of first encounter
print "Wild bear appears!."
print "What do you do?"
print "Stand your ground, Run away, be agressive in an attempt to scare the bear"

#first encounter
encounter.bear(hp)

我将所有遭遇放在一个单独的脚本中以保持整洁。这是遭遇脚本。

import time

#Bear encounter
def bear(hp):
    import game
    choice = raw_input("> ")
    if "stand" in choice:
        print "The bear walks off, and you continue on your way"
    elif "run" in choice:
        print "..."
        time.sleep(2)
        print "The bear chases you and your face gets mauled."
        print "You barely make it out alive, however you have sustained serious damage"
        hp = hp-60
        game.currenthp(hp)
    elif "agressive" in choice:
        print "..."
        time.sleep(2)
        print "The bear sees you as a threat and attacks you."
        print "The bear nearly kills you and you are almost dead"
        hp = hp-90
        game.currenthp(hp)
    else:
        print "Well do something!"

这一切都很方便,除了一件事。 当我的程序进入它要求答复玩家想要响应遇到脚本中的熊的部分的部分时,整个游戏脚本重新启动。但是,这次,程序将正常工作。有这个原因还是我必须处理它?<​​/ p>

1 个答案:

答案 0 :(得分:4)

您的代码具有循环依赖关系:game导入encounterencounter导入game。您在game中的模块范围中也有很多逻辑;模块级逻辑在第一次导入模块时进行评估 - 但是,模块未完成导入直到其所有代码都被评估,因此如果您最终在模块定义代码的过程中再次导入模块,奇怪的事情发生了。

首先,没有模块级代码 - 使用if __name__ == "__main__":块。这意味着您的代码只有在您需要时才会在导入时运行。

请参阅What does if __name__ == "__main__": do?

其次,不要进行循环导入 - 如果您需要共享逻辑并且无法证明将其保留在导入的模块中,请创建由两者导入的第三个模块。不过,看起来您可以将current_hp移至encounter并从import game移除encounter