我正在创建一个基于文本的冒险游戏以使用 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)
Run Code Online (Sandbox Code Playgroud)
为了整洁,我把我所有的遭遇都放在一个单独的脚本中。这是遭遇脚本。
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!"
Run Code Online (Sandbox Code Playgroud)
好吧,这一切都很方便,除了一件事。当我的程序到达它要求玩家回答遇到脚本中的熊时,它会做什么的部分时,整个游戏脚本将重新启动。但是,这一次,程序将正常运行。这有什么原因吗,还是我只需要处理它?
您的代码具有循环依赖项:game导入encounter和encounter导入game。您在模块范围内也有很多逻辑game;模块级逻辑在第一次导入模块时被评估——但是,一个模块直到它的所有代码都被评估后才完成导入,所以如果你最终在模块定义代码的过程中再次导入模块,奇怪的事情发生。
首先,没有模块级代码——使用if __name__ == "__main__":块。这意味着您的代码不会在导入时运行,只有在您需要时才会运行。
请参阅if __name__ == "__main__": do?
其次,不要循环导入——如果您需要共享逻辑并且无法证明将其保留在导入的模块中,请创建由两者导入的第三个模块。不过,在这里,您似乎可以移动current_hp到encounter并删除import gamefrom encounter。
| 归档时间: |
|
| 查看次数: |
3726 次 |
| 最近记录: |