2015-08-16 44 views
1

我目前正在使用本書學習Python The Hard Way來學習Python。在練習43中,我被要求創建自己的遊戲,並且必須遵循以下規則:如何使引擎改變Python中當前的遊戲區域?

  • 我必須使用多個文件。
  • 我必須爲角色可以去的每個區域使用一個類。

在我的遊戲中,我有不同的領域表示爲類,我需要一個引擎來運行它們。引擎應設置起始區域,並在我的角色輸入正確的命令時更改區域。我不明白如何創建一個引擎,我已經看到一些在線,但我永遠不知道他們是如何工作的。我花了數小時試圖爲自己創造一個,而我卻做不到。

這是不同的區域代碼: areas.py:

# Jungle area's are numbered like a keypad on a phone. 
from engine import * 

class Jungle8(object): 
    print "\nYou are south of the jungle.\n" 
class Jungle1(object): 
    print "\nYou are northwest of the jungle.\n" 
class Jungle2(object): 
    print "\nYou are north of the jungle." 
    print "The Monkey Elder is waiting for you.\n" 
class Jungle3(object): 
    print "\nYou are northeast of the jungle.\n" 
class Jungle4(object): 
    print "\nYou are west of the jungle.\n" 
class Jungle5(object): 
    print "\nYou are in the center of the jungle.\n" 
class Jungle6(object): 
    print "\nYou are east of the jungle." 
    print "You can see a cave with a locked door.\n" 
class Jungle7(object): 
    print "\nYou are southwest of the jungle.\n" 
class Jungle9(object): 
    print "\nYou are southeast of the jungle.\n" 

這是引擎的代碼,這基本上是空的:

from areas import * 

class Engine(object): 

    def __init__(self): 
     # No idea on what to do at this point. 

有沒有一種辦法跑課?如果我使用房間的功能,我可以做到這一點,但課程讓我困惑不已。

回答

1

是的,你可以。一個類在具有__call__方法時可以被調用(一個函數)。

class Jungle6(): 
    def __call__(self): 
     print "\nYou are east of the jungle." 
     print "You can see a cave with a locked door.\n" 

作爲示例。

然後,您只需調用實例:

j = Jungle6() 
j() 
+0

就是,Python 3? – Salik12

+0

這應該存在於Python 2.我編輯我的答案,希望更清晰。 – Berserker

+0

非常感謝!這應該幫助我很多! – Salik12