如何检查用户是否已通过某个方法

2024-10-03 23:23:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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.")


Tags: the方法代码in文本anistype
1条回答
网友
1楼 · 发布于 2024-10-03 23:23:13

您需要的是与函数关联的状态。将对象与方法一起使用:

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()

相关问题 更多 >