如何在同一个脚本中重复使用一段代码,而不是每次都重新输入?

How can I reuse a section of code repeatedly in the same script, without retyping it every time?

我决定制作一个基于文本的冒险游戏(Think BBC Micro!)来帮助我学习。

到目前为止进展顺利,但我想知道是否有一种方法可以重用要求用户执行下一步操作的代码,而无需重新键入整个内容。我假设有一种方法可以创建一个函数,然后在每次需要时简单地调用该函数,但我不知道该怎么做。

我最常使用的场景是在询问用户他们想去哪个方向(L、F、R)时,我正在这样做:

print("You have arrived at... To your left (L) is ... , ahead (F) is ... To your right (R) is...")
direction = str(input("Which direction do you wish to go? (L/F/R) "))
if direction.upper() not in ("L", "F", "R"):
    print("whats does {} mean? You were meant to type 'L', 'F' or 'R'! Try again..".format(direction))
elif direction.upper() == "L":
    print("You turn left and find...")
elif direction.upper() == "F":
    print("You go forward and find...")
elif direction.upper() == "R":
    print("You turn right and find...")

如何在不每次都重新输入 (copy/pasting) 的情况下为每个新方向重复使用此代码? 也有没有办法通过将代码指向一个新变量来填充每个方向下的print(")

我正在考虑将它放在一个循环中,以便每次运行 if 语句时它递增 1,然后我可以列出对每个操作的所有响应并简单地为它们分配一个名称 L1, L2、L3...F1、F2、F3...R1、R2、R3。通过这种方式,文本可以在块中创建,而不是包含在每个 if/elif 语句中,然后可以通过采用方向 (L, F, R) 值和循环将其放置在 print() 命令中计数 (1, 2, 3) 并将它们组合起来给出变量的名称 (F3).

文本出现,然后再次运行循环询问下一个方向。

这是一种合适的方法吗?如果是,我如何将 if/elif 语句分配给可调用函数?

更新 到目前为止我的代码:

#PLAYER DETAILS
first_name = input("What is your first name? ")
last_name = input("What is your last name? ")
while True:
    middle = input("Do you have a middle name? (y/n) ")
    if middle.upper() not in ("Y", "N"):
        print("whats does {} mean? You were meant to type 'y' or 'n'! Try again.." .format(middle))
    elif middle.upper() == "Y":
        middle_name = input("What is it? ")
        break
    elif middle.upper() == "N":
        middle_name = None
        break
# is_middle_empty = bool(middle_name)
# print(is_middle_empty)
print("So your full name is {} {} {}? ".format(first_name, '' if middle_name is None else middle_name, last_name))
import time
time.sleep(1)
print("Hmmm..")
time.sleep(1)
just_first = str(input("Should I just call you {}? (y/n) ".format(first_name)))
if just_first.upper() == "Y":
   player = first_name
   print("Great, nice to meet you", player)
elif just_first.upper() != "Y":
   name = first_name, "" if middle_name is None else middle_name, last_name
   player = " ".join(name)
   print("Sorry about that, let's stick to {} then." .format(player))
print()

#DIRECTION FUNCTION
def getUserDirection():
    direction = str(input("Which direction do you wish to go? (L/F/R) "))
    direction = direction.upper()
    if direction.upper() not in ("L", "F", "R"):
        print("whats does {} mean? You were meant to type 'y' or 'n'! Try again..".format(direction))
    elif direction.upper() == "L":
        print(L1())
    elif direction.upper() == "F":
        print(F1())
    elif direction.upper() == "R":
        print(R1())
    return

#STORY LINES
def start():
    print("You have arrived at ... To your left (L) is ..., ahead (F) is ... To your right (R) is ...")
def L1():
    print("you go left")
def F1():
    print("You continue forward")
def R1():
    print("You turn right")

#ADVENTURE-1
adventure = input("So do you fancy a quick adventure? (y/n) ")
if adventure.upper() == "Y":
    print("Great then lets set off...")
elif adventure.upper() == "N":
    print("Ah well, I guess we can't all be ubercool adventurers like me, fairwell {}, I hope we meet again some day." .format(player))

#ADVENTURE-2
time.sleep(1)
print(start())
print(getUserDirection())

输出是:

你叫什么名字? b

你姓什么?米

你有中间名吗? (y/n) n

所以你的全名是b m?

嗯嗯..

我应该叫你b吗? (y/n) y

太好了,很高兴认识你 b

那么你喜欢快速冒险吗? (y/n) y

太好了,那我们出发吧...

您已到达...您的左侧(L)是...,前方(F)是...您的右侧(R)是...

None

你想去哪个方向? (L/F/R) f

你继续前进

None

None

进程已完成,退出代码为 0

我已经突出显示了“None”returns,它们为什么在那里?

使用def语句定义一个函数。例如:

def direction_func():
    direction = str(input("Which direction do you wish to go? (L/F/R) "))
    if direction.upper() not in ("L", "F", "R"):
        print("whats does {} mean? You were meant to type 'L', 'F' or 'R'! Try again..".format(direction))
    elif direction.upper() == "L":
        print("You turn left and find...")
    elif direction.upper() == "F":
        print("You go forward and find...")
    elif direction.upper() == "R":
        print("You turn right and find...")
    return direction

然后在你需要的每一段代码中调用这个函数:

direction = direction_func()
print(direction)

您可以在这种情况下使用函数:

def getUserDirection():
    print("You have arrived at... To your left (L) is ... , ahead (F) is ... To your right (R) is...")
    direction = str(input("Which direction do you wish to go? (L/F/R) "))
    direction = direction.upper()
    if direction not in ("L", "F", "R"):
        print("whats does {} mean? You were meant to type 'L', 'F' or 'R'! Try again..".format(direction))
    elif direction == "L":
        print("You turn left and find...")
    elif direction == "F":
        print("You go forward and find...")
    elif direction == "R":
        print("You turn right and find...")
    return direction

然后你可以在任何地方调用它:

userDirection = getUserDirection()

现在您可以在变量 userDirection 中获取用户的当前方向

如果你只想得到正确的结果,每次用户输入错误的值时都要求正确输入,那么你可以递归地再次调用该函数 :

def getUserDirection():
    print("You have arrived at... To your left (L) is ... , ahead (F) is ... To your right (R) is...")
    direction = str(input("Which direction do you wish to go? (L/F/R) "))
    direction = direction.upper()
    if direction not in ("L", "F", "R"):
        print("whats does {} mean? You were meant to type 'L', 'F' or 'R'! Try again..".format(direction))
        direction = getUserDirection()
    elif direction == "L":
        print("You turn left and find...")
    elif direction == "F":
        print("You go forward and find...")
    elif direction == "R":
        print("You turn right and find...")
    return direction