我正在用 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("房间中间有一个祭坛,有向下和向西的 channel 。")
最佳答案
您想要的是与函数关联的状态。使用带有方法的对象:
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()
关于python - 如何检查用户是否已经通过某种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42867342/