python - 如何检查用户是否已经通过某种方法

标签 python python-3.x

我正在用 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/

相关文章:

python-3.x - 对于来自 seaborn 的计数图,Matplotlib 的替代方案是什么?

python - 项目欧拉问题 18 : finding the best route in a triangular grid

python - numpy数组内存分配

python - pytz时区转换性能

python-3.x - Pandas:在列上应用函数列表,每列一个函数

Python:字典作为实例变量

python - Anaconda 中的 PyBrain - 导入错误 : No module named 'structure'

python - 如何在 Python 中将 HTML 表格转换为数组

python-3.x - 子图的通用 x 标签

python-3.x - 无法导入tpot