2015-05-31 51 views
2

我使用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!" 

好吧,這一切工作方便,丹迪,除了一件事。 當我的程序到達要求回答玩家想要做什麼以迴應遇到腳本中的熊的部分時,整個遊戲腳本重新啓動。但是,這一次,該程序將正常工作。有沒有這個原因,還是我只需要處理它呢?

+0

我實際上是在函數中導入了遊戲,因爲它阻止了頂級的相互導入,因爲這會給我一個屬性錯誤,並在另一個帖子中看到了這一點,頂級投票答案表示這將是解決問題的方法。 –

回答

3

您的代碼有循環依賴關係:game進口encounterencounter進口game。您在game的模塊範圍中也有很多邏輯;模塊級別的邏輯在第一次導入模塊時被評估 - 但是,一個模塊在其所有代碼被評估之前並未完成導入,所以如果最終在其模塊定義代碼的過程中再次導入模塊,那麼奇怪的事情發生。

首先,沒有模塊級代碼 - 使用if __name__ == "__main__":塊。這意味着您的代碼不會在導入時運行,只有在您需要時才能運行。

What does if __name__ == "__main__": do?

其次,沒有圓形的進口 - 如果你需要共享的邏輯並不能證明保持它導入的模塊中,通過創建對進口的第三模塊。儘管如此,看起來您可以將current_hp移動到encounter並從encounter中刪除import game

相關問題