2017-03-17 68 views
1

我正在Python中製作一個簡單的基於文本的RPG。目前我對大多數房間有兩種方法,一種是在他們第一次進入時,一種是在他們返回時。如果沒有其他方法,我可以確保他們之前沒有進入該房間嗎?如何檢查用戶是否已通過方法

例如,如果我有一個名爲tomb()的方法,我創建了另一個名爲tombAlready()的方法,其中包含除了介紹房間的介紹文字以外的相同代碼。

所以,如果我有

slow_type("\n\nTomb\n\n") 
    slow_type("There is an altar in the middle of the room, with passages leading down and west.") 
    choice = None 
    while choice == None: 
    userInput = input("\n>") 
    if checkDirection(userInput) == False: 
     while checkDirection == False: 
     userInput = input("\n>") 
     checkDirection(userInput) 
    userInput = userInput.lower().strip() 
    if userInput == "d": 
     catacombs() 
    elif userInput == "n": 
     altar() 
    elif userInput == "w": 
     throneroom() 
    else: 
     slow_type("You cannot perform this action.") 

然後tombAlready()將有除了slow_type("There is an altar in the middle of the room, with passages leading down and west.")

+0

全局變量? – rassar

+0

你在哪裏建議我定義我的全局變量? – nichilus

+0

添加一個if語句和一個變量從False更改爲真後 – abccd

回答

1

你想要的是與功能相關聯的狀態相同的代碼。使用一個對象與方法:

class Room: 
    def __init__(self, description): 
     self._description = description 
     self._visited = False 

    def visit(self): 
     if not self._visited: 
      print(self._description) 
      self._visited = True 

然後,你可以爲每個房間Room對象:

catacombs = Room('There is a low, arched passageway. You have to stoop.') 
tomb = Room('There is an altar in the middle of the room, with passages leading down and west.') 
throneroom = Room('There is a large chair. It looks inviting.') 

您可以訪問一個房間兩次,但只打印其描述一次:

>>> catacombs.visit() 
There is a low, arched passageway. You have to stoop. 

>>> catacombs.visit() 
+1

謝謝。工程就像一個魅力:) – nichilus

+0

快速問題,順便說一句...如果我有我的房間像'catacombs()'方法我會用我的變量相同的名稱嗎? – nichilus

+0

或更具體地說,我應該在哪裏放置變量,以免干擾程序? – nichilus

相關問題