2014-01-20 81 views
0

我試圖找到導入相同的模塊不止一次因某些關鍵壓力機的方式....導入相同的Python模塊不止一次

if event.type == pygame.KEYDOWN: 
    if event.key == pygame.K_1: 
     import forest_level 
    if event.key == pygame.K_2: 
     import sea_level 
    if event.key == pygame.K_3: 
     import desert_level 
    if event.key == pygame.K_4: 
     import underwater_level 
    if event.key == pygame.K_5: 
     import space_level 

說,如果我是在森林級別並去了海平面,我將如何恢復到森林水平?

GAME CODE

+0

一個模塊只導入一次,後面的導入只是從'sys.modules'中獲取已經導入的模塊對象。你將不得不使用reload()來強制Python重新加載已經導入的模塊。 –

回答

2

你不能。

我將不得不猜測你的代碼的結構,因爲你還沒有提供一個Short, Self Contained, Correct (Compilable), Example

你可能有幾個模塊看起來像:

# foo_level.py 
print "foo" 

與主模塊於:

# main.py 
while True: 
    key = raw_input() 
    if key == "foo": 
     import foo_level 
    # and so on. 

import聲明是專爲將代碼插入範圍,而不是實際執行任意代碼。

把所有的代碼要運行函數中的多次:

# foo_level.py 
def do_stuff(): 
    print "foo" 

,而是,進口所有模塊一次,一開始並調用循環中的新功能:

# main.py 
import foo_level 
while True: 
    key = raw_input() 
    if key == "foo": 
     foo_level.do_stuff() 
    # and so on. 
+0

我很抱歉,但我不明白這一點,所以你說的創建一個新的模塊,所有級別定義它,然後另一個模塊,它允許你從新創建的一個調用水平? – user2921888

+1

請參閱我的編輯,我希望更清楚。 – SingleNegationElimination

+0

謝謝,順便說一句,我的遊戲代碼是在鏈接... – user2921888