我在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 :(得分: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()