【问题标题】:Text-based adventure game looping to previous line?基于文本的冒险游戏循环到上一行?
【发布时间】:2018-08-15 20:02:58
【问题描述】:

我正在通过创建基于文本的冒险游戏来学习 Python。我很难弄清楚是否可以调用以前的变量。例如,这是我的代码的 sn-p(关于如何整合的建议会很有帮助哈哈)我有一个 if 语句,允许玩家选择一个输入。

在 ALIEN 输入下,您会看到他们是否选择了 1。他们选择了“接受失败”。

我在这段代码的末尾有相同的结果,玩家在 IMPROV 输入后再次选择“接受失败”。如果选择了该选项,我想循环回第一个外星变量。而不是再次编写相同的 if、elif 语句。这可能吗?

   def main(): #Groups together the entire script, allows for a loop. The enitire script is called main.
import sys #imports system settings and functions
from colorama import init #imports color scheme
init()
init(autoreset=True) #resets color scheme after every use
#Text based adventure game in progress
from colorama import Fore, Back, Style
s_b = Style.BRIGHT # This allows you to shorthand a variable, rather than typing Style.BRIGHT everytime.
f_c = Fore.CYAN
f_g = Fore.GREEN
f_y = Fore.YELLOW
f_r = Fore.RED
print ("")
print ("")
print (f_y + s_b + "                                                                           WELCOME TO THE MAZE                                   ")
print ("")
print ("")
print (s_b + "You have found yourself stuck within a dark room, inside this room are 5 doors.. Your only way out..")
print ("")
print (s_b + "Do you want to enter door 1,2,3,4, or 5?") #This gives the player options to choose.
print ("")
door = input(f_y + s_b + "> ");
# input("> ") means the player can give any variable
# Will only work if the variable is defined down below
if door == "1":
    print ("")
    print (s_b + "Theres an alien eating what appears to be a human arm, though its so damaged it's hard to be sure. There is a knife next to the alien.")
    print ("")
    print (s_b + "what do you want to do?")
    print ("")
    print (f_g + s_b + "1. Go for the knife")
    print ("")
    print (f_g + s_b + "2. Attack alien before it notices you")
    print ("")

    alien = input(f_y + s_b + "> ");

    if alien == "1":
        print ("")
        print (s_b + "You approach the knife slowly, While the alien is distracted. You finally reach the knife, but as you look up, the alien stares back at you.")
        print ("")
        print (s_b + "You make a move to stab the alien, but he is too quick. With one swift motion, the alien thrusts you into the air.")
        print ("")
        print (s_b + "You land hard, as the alien makes it's way towards you again. What should you do?")
        print ("")
        print (f_g + s_b + "1. Accept defeat?")
        print ("")
        print (f_g + s_b + "2. Last ditch effort?")
        print ("")

        improv = input(f_y + s_b + "> ")

        if improv == "1":
            print ("")
            print (s_b + "The alien stands over you, as you grimace in pain. You extend your arms out revealing your chest. Showing the alien you're not afrain of death.")
            print ("")
            print (s_b + "The alien stops, and brings it's face close to yours. You have gained the alien's respect, he walks slowly back to the arm he was consuming.")
            print ("")
            print (s_b + "You lie in shock, What should you do now?")
            print ("")
            print (s_b + f_g + "1. Get up and try to communicate with the alien?")
            print ("")
            print (s_b + f_g + "2. Get up and continue onward through this seemingly dangerous world?")
            print ("")

            onward = input(f_y + s_b + "> ")

            if onward == "1":
                print ("")
                print (s_b + "You take a deep breath, still in pain, you slowly limp your way towards the alien.")
                print ("")
                print (s_b + "As the alien hears you approach, it stops eating the arm and turns towards your direction.")
                print ("")
                print (s_b + "What should you say?")
                print ("")
                print (s_b + f_g + "1. 'Why didn't you kill me?'")
                print ("")
                print (s_b + f_g + "2. 'Help me escape this place.'")
                print ("")

                kill = input(f_y + s_b + "> ")


                if kill == "1":
                    print ("")
                    print (s_b + "You walk close to the alien as he stares into your eyes, you show no fear as you stare right back. 'Why didn't you kill me?' you ask.")
                    print ("")
                    print (s_b + "The alien huffs and responds in the deepest voice imaginable, 'I only kill those who have fear.'")
                    print ("")
                    print (s_b + "You respond..")
                    print ("")
                    print (s_b + f_g + "1. I have fear.")
                    print ("")
                    print (s_b + f_g + "2. You don't scare me, nothing does.")
                    print ("")

                    kill2 = input(f_y + s_b + "> ")

                    if kill2 == "1":
                        print ("")
                        print (s_b + "'I am terrified of you' you say. I am terrified of everything, I had given up.'")
                        print ("")
                        print (s_b + "The alien responds 'This is why you approach me? To express your fear? Have I misread you?'")
                        print ("")
                        print (s_b + "'You haven't misread me, I am ready to die.' you respond.")
                        print ("")
                        print (s_b + "The alien respects your wishes, 'Well, I can arrange that..'")
                        print ("")
                        print (s_b + "The alien swiftly swipes off your head, leaving your body lifeless.")
                        print ("")
                        print (s_b + f_r + "You died.. GAME OVER!! You gave up too soon..")
                        print ("")

                if kill == "2":
                    print ("")
                    print (s_b + "You limp up to the alien, brushing down your clothes.")
                    print ("")
                    print (s_b + "The alien stares at you, seemingly waiting for you to say something.")
                    print ("")
                    print (s_b + "'Help me escape this place' you say.")
                    print ("")
                    print (s_b + "'Help you?' responds the alien with a fighteningly deep voice. 'Why would you think I would help you?'")
                    print ("")
                    print (s_b + f_g + "1. Because you didn't kill me, and I need to get out of this place.")
                    print ("")
                    print (s_b + f_g + "2. Because I will kill you if you dont.")
                    print ("")


            elif onward == "2":
                print ("")
                print (s_b + "You quickly turn over and limp as far from the alien as you can.")
                print ("")
                print (s_b + "This world is dark, so it's difficult to see what's ahead.")
                print ("")
                print (s_b + "You continue onward in hopes to find a way out.")
                print ("")




        elif improv == "2":
            print ("")
            print (s_b + "You quickly scan the area for weapons and shelter. The alien is approaching quickly. You notice a black wall.")
            print ("")
            print (s_b + "There is no way you can reach the wall in time, and even if you do, the alien will just follow..")
            print ("")
            print (s_b + "What should you do?")
            print ("")
            print (f_g + s_b + "1. Attempt to run behind the wall")
            print ("")
            print (f_g + s_b + "2. Accept defeat?")
            print ("")

            wall = input(f_y + s_b + "> ")

            if wall == "1":
                print ("")
                print (s_b + "You scream in agony as you pull yourself up and make a break toward the wall.")
                print ("")
                print (s_b + "You hear the alien directly behind you. You dive behind the wall, landing on a sharp object.")
                print ("")
                print (s_b + "The object is an incredibly sharp sword. The alien hurries around the wall and attacks you.")
                print ("")
                print (s_b + "What should you do?")
                print ("")
                print (s_b + f_g + "1. Attempt to take the alien's limbs off with the sword.")
                print ("")
                print (s_b + f_g + "2. Aim stright for the aliens neck with the sword.")
                print ("")

            elif wall == "2":

                improv = input(f_y + s_b + "> ")

    elif alien == "2":
        print ("")
        print (s_b + "You catch the alien off-guard. He stumbled and hisses in your direction. You scream in terror before he grabs the knife, and punctures your throat as he rips off your limbs.")
        print ("")
        print (s_b + f_r + "You died.. GAME OVER.. Mistakes can't be made this soon.. OUCH")
        print ("")

    else:
        print ("")
        print (s_b + "You froze, you decided to do nothing. In shock, you let the alien notice and approach you. He gashes your face and begins to consume your body.")
        print ("")
        print (s_b + f_r + "You died.. GAME OVER.. How did you die this soon??")
        print ("")

    restart=input(f_y + s_b + "Start over? Yes or No? ").lower()
    if restart == "yes":
        sys.stderr.write("\x1b[2J\x1b[H") ## This will clear out screen in the terminal
        main()

    else:
        exit()  #Remember this to start a loop, from restart=input, to exit()

main()

【问题讨论】:

  • f_gf_ys_b 是什么?像这样的变量名使代码难以阅读。
  • 另外,尝试使用\n 作为换行符,而不是print("")
  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。
  • 您发布的代码在第 1 行终止。它根本不是最小的。您使用了非描述性变量名称。最重要的是,您没有尝试编写循环来解决您的问题,许多教程网站和 Stack Overflow 上的其他问题都很好地介绍了该循环。请进行预期的研究并遵循 SO 指南。我们很乐意为您提供帮助,但我们需要 (1) 对我们来说直截了当; (2) 对我们的存档有用——毕竟这是本网站的章程。
  • 如果他们输入了不允许的内容,例如3,您也没有任何处理

标签: python loops if-statement conditional-statements text-based


【解决方案1】:

您似乎根本没有使用函数。这是你应该做的事情:)

例如,不要每次都重复输入颜色,而是创建一个colored_input

def colored_input():
    return input(Fore.YELLOW + Style.BRIGHT + "> ")

alien = colored_input()

其次,我会合并“事件”,而不是像你那样将它们输入出来。例如,我会将页面分别存储在一个元组中。像这样:

STARTING_TEXT = """
Theres an alien eating what appears to be a human arm, though its so damaged it's hard to be sure. There is a knife next to the alien.
what do you want to do?¨
"""

STARTING_CHOICES = """
Go for the knife
Attack alien before it notices you
"""

EVENT_START = (STARTING_TEXT, STARTING_CHOICES)

三引号创建一个多行字符串。请注意,第一个和最后一个换行符是字符串的一部分,因此您必须稍后将其删除。

当然,你可以直接将文本放入元组中:

EVENT_APPROACH_KNIFE = ("""
You approach the knife slowly, While the alien is distracted. You finally reach the knife, but as you look up, the alien stares back at you.
You make a move to stab the alien, but he is too quick. With one swift motion, the alien thrusts you into the air.
You land hard, as the alien makes it's way towards you again. What should you do?
""", """
Accept defeat?
Last ditch effort?
""")

现在,如果你有一堆这样的“事件”,你可以有一个函数来显示它们并在同一步骤中请求输入:

def run_event(event):  # from here on, the "event" variable will be whichever EVENT_* you call
    text, choices = event  # separates the two items of the tuple
    # Remove whitespace from start and end. This gets rid of the starting and ending newline
    # that I mentioned earlier:
    # (go ahead, remove the following line and see what happens)
    text = text.strip()
    # Now let's get individual lines - split the text on newlines:
    text_lines = text.split("\n")
    # print them with colors:
    for line in text_lines:
        print(Fore.YELLOW + line)
        print() # To print an empty line, you don't even need to add the ""
    # now let's do the same with choices:
    choices = choices.strip()
    choice_lines = choices.split("\n")
    for num, line in enumerate(choice_lines):
        # the "enumerate" gives you "num" as the number of the line
        # but it counts from 0, so we need to add 1
        # (and wrap it in str() because otherwise you can't add it to a string
        print(Fore.GREEN + Style.BRIGHT + str(num + 1) + ". " + line)
        print()
    # finally, ask for player's choice and return it
    return colored_input()

这将大大简化您的代码。假设您事先定义了所有事件,您可以像这样执行 if:

door = run_event(EVENT_DOOR)
if door == "1":
    alien = run_event(EVENT_ALIEN)
    if alien == "1":
        improv = run_event(EVENT_IMPROV)
        ...
    elif alien == "2":
        ...

您可以进一步开发此功能,例如,使用列表而不是多行字符串作为选项,并将事件与选项相关联。

但是,要回答您最初的问题:像这样的结构,您可以将游戏的某些部分变成函数。像这样:

def accept_defeat():
    improv = run_event(EVENT_ACCEPT_DEFEAT)
    if improv == "1":
        ...
    elif improv == "2":
        wall = run_event(EVENT_LAST_DITCH)
        if wall == "1":
            accept_defeat()  # here you're calling the same function again!
        elif ...:
            ...

 # and then somewhere in the main function:
 def main():
      alien = run_event(EVENT_ALIEN):
      if alien == "1":
          accept_defeat()
      elif ...:
          ...

当您从同一个函数中调用一个函数时,您使用的是递归。实际上,这是一个相当糟糕的解决方案:例如,如果您决定连续“接受失败”超过 128 次左右,您将超过递归限制,您的程序将崩溃。

但为了避免递归,您必须以更深层次的方式重新编写程序。 ISTM 在您的技能水平上,此解决方案运行良好。当您达到这种方法的限制时,您可以了解更多信息 - 或者当您觉得自己非常了解此代码并想要更多挑战时:)

【讨论】:

  • 很棒的推荐!!非常感谢。你把一切都说清楚了,你的 cmets 很好地解释了一切。我很欣赏这种洞察力!我会做出这些改变:)
【解决方案2】:

我建议制作一种图表。您必须绘制出所有选项,但您可能已经这样做了。此外,实现循环将有助于处理不可接受的答案。

一种可行的可能性(测试它here,仅供参考,这甚至不如 OP 示例完整,但您可以输入 1 两次以查看它应该如何运行):

# make a class for each event, it'll contain a description and any number of choices
class Event:
  def __init__(self,description,choices,options):
      self.description=description
      self.choices=choices
      # options should be a list the same length as choices with corresponding keys to other events
      self.options=options
  def to_string(self):
      print(self.description+'\n')
      for choice in self.choices:
        print(choice+'\n')
      # point to the next event
      return self.options[self.make_choice()-1]
  def make_choice(self):
    c=0
    # this won't allow a user to enter a value not offered
    while c<1 or c>len(self.choices):
        c=int(input("your choice> "))
    return c

# this is your map
events={'start':Event("You approach the knife slowly, While the alien is distracted. You finally reach the knife, but as you look up, the alien stares back at you.\nYou make a move to stab the alien, but he is too quick. With one swift motion, the alien thrusts you into the air.\nYou land hard, as the alien makes it's way towards you again. What should you do?",["1. Accept defeat?","2. Last ditch effort?"],['defeat','ditch']),'defeat':Event("The alien stands over you, as you grimace in pain. You extend your arms out revealing your chest. Showing the alien you're not afrain of death.\nThe alien stops, and brings it's face close to yours. You have gained the alien's respect, he walks slowly back to the arm he was consuming.\nYou lie in shock, What should you do now?",["1. Get up and try to communicate with the alien?","2. Get up and continue onward through this seemingly dangerous world?"],['communicate','onward']),'communicate':Event("You take a deep breath, still in pain, you slowly limp your way towards the alien.\nAs the alien hears you approach, it stops eating the arm and turns towards your direction.\nWhat should you say?",["1. 'Why didn't you kill me?'","2. 'Help me escape this place.'"],['kill','escape'])}

c='start'
while True:
    t=events[c].to_string()
    # this is how you'd break the loop if you win or lose
    if t=="Game Over":
        break
    elif t=="You Win":
        break
    c=t

【讨论】:

  • 我不确定 OP 是否希望/需要有人为他们编写代码
  • @LioraHaydont 他们已经尝试过了,但他们遇到了figuring out if I could call a previous variable. 的问题,这个答案提供了一个解决方案,我相信一个更优雅的设计
  • 您可以建议他们使用另一种设计并提供指导,而无需为他们编写所有代码。
  • 感谢您的回复!
  • 我犯了一个错误,只发布了一部分代码,没有显示代码如何运行。我的代码很长,我对提到的大多数事情都有解决方案。我非常感谢反馈,我会在有能力的时候再次发布(90 分钟内不能发布超过两次)。我将为脚本提供允许您自己运行它的信息。再次,我很抱歉。这是我的第一篇文章哈哈。
猜你喜欢
  • 2016-08-25
  • 2013-07-08
  • 1970-01-01
  • 2018-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多