如何将我在文本冒险(函数)中的位置保存到文件中?

2024-09-21 02:40:05 发布

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

我正在开始一个基本的文本冒险游戏。我得到了一个原型,但因为每个选项都是一个函数,所以我不知道如何安全地将我的位置保存到文件中

我考虑过将函数名保存到一个文件中,但是我想不出一个好的方法来在读取文件后将函数名作为str来获取^任意str上的{}是出了名的不安全。我认为dict将每个函数映射到它的名称是str,但似乎随着更多选择的累积,这个dict会使我的脚本膨胀

def choice1():
    while True:
        text = input("A or B?: ")
        if text == "A":
            return False, choice2
        elif text == "B":
            saygameover()
            return True, None
        elif askedforsave(text):
            return True, choice1
        else:
            saytryagain()

def choice2():
    while True:
        text = input("C or D?: ")
        if text == "C":
            print("you win!")
            return True, None
        elif text == "D":
            saygameover()
            return True, None
        elif askedforsave(text):
            return True, choice2
        else:
            saytryagain()

def askedforsave(text):
    if text == "save":
        return True
    else:
        return False

def saytryagain():
    print("try again...")

def saygameover():
    print("game over.")

def play(choice = choice1):
    done = False
    while not done:
        done, choice = choice()
    if choice != None:
        save(choice)

def save(choice):
    pass

def load(file):
    pass
    return choice

Tags: 文件函数textnonefalsetruereturnif
1条回答
网友
1楼 · 发布于 2024-09-21 02:40:05

这就是我目前得到的^当我已经在globals()中检查名称时,{}可能是不必要的,但这是确保使用有效的Python名称而不是表达式的好方法

import types

def load(string):
        # if string is valid Python name
    if (string.isidentifier() and

        # if string in this global scope's symbol table
        string in (thisglobal := globals()) and

        # if object is a non-builtin function
        isinstance(something := thisglobal[string], types.FunctionType)):

        return something
    else:
        return nogame
    
def nogame():
    return True, None

相关问题 更多 >

    热门问题