【问题标题】:How to create a "Save" option in a text adventure game?如何在文字冒险游戏中创建“保存”选项?
【发布时间】:2022-01-09 12:25:33
【问题描述】:

我想知道如何在我的文字冒险游戏中创建“保存点”。

在我的例子中,有一个书面故事从一行到另一行一直到最后。 所以很难编写脚本。

我的问题是,如果玩家键入命令 save 而不是 yes 或 no,当游戏为您提供该选项时,我如何创建一个保存点,让玩家可以在他停止时加载这个确切的时刻然后它被加载并立即跳转到这行代码。

例如:

#gamestart

print("Hi welcome to the game...")
...
...
input1 = input("You want to go?(Y/N)")

while input1 != "Y":
    # do something
# and here, what if I want to save? In my case I want to return to this exact question or line

print("blalab")

【问题讨论】:

标签: python adventure


【解决方案1】:

据我所知,没有内置方法可以在执行期间保存(或“转到”)特定代码行。这意味着您将不得不对程序的实际结构进行一些尝试。

在我看来,你需要:

  • 决定游戏中的某些“检查点”,并将代码构造成围绕这些检查点的函数。
  • 然后,您可以将所有这些检查点功能按顺序保存在一个列表中。
  • 当用户保存游戏时,您可以将检查点编号写入文本文件或任何其他格式。
  • “加载”游戏时,读取文件中保存的数字并从列表中跳转到匹配的检查点功能。

这个想法的大纲是:

def checkpoint_1():
    input1 = input("Do you want to go right?(Y/N)")
    if input1 == "Y":
        checkpoint_2()
    elif input1 == "N":
        checkpoint_3()
    elif input1 == "save":
        open("save.txt", 'w').write('1')

checkpoints = [start, checkpoint_1, checkpoint_2, ...]

当你开始游戏时:

def main():
    try:
        saved_checkpoint = int(open("save.txt").read())
        checkpoints[saved_checkpoint]()
    except FileNotFoundError:
        start()

【讨论】:

  • 嘿,谢谢!还有另一种保存变量的选项吗?例如,如果角色有键或其他东西: def Cave(): foundKey=True... 我如何将这个 foundKey=True 变量保存在 txt 中?所以当我加载它时,它会将 True bool 插入到 foundKey 中。
  • 这几乎是一个单独的问题,因为它使事情变得非常复杂和改变。我要做的是创建一个字典,其中包含您想要保存的所有不同值以及一些默认值。然后将此数据写入 json 并在游戏开始时加载。我会做一个小编辑来证明当我回家时
【解决方案2】:

我为您创建了整个游戏,并能够按照问题中的要求保存您的进度。

这样我既可以提供保存游戏的功能,也可以提供其工作方式的逻辑。

每一行都有明确的说明,您只需在“steps”中添加新步骤即可构建游戏。

# "steps" is a dictionary containing all the steps in the game.
# The key of each dict item is its ID.
# "Text" is the text / question that will display.
# "Yes" and "No" correspond to the ID of the next question based on the answer.
# If item contains "Game Over": True, the game will end when we reach that item's ID.

steps = {
    1: {"Text": "You see a door in front of you... Do you walk into the door?", "Yes": 2, "No": 3},
    2: {"Text": "The door won't open... Use force?", "Yes": 4, "No": 5},
    3: {"Text": "OK, never-mind.", "Game Over": True},
    # add more steps to the game here...
}


def load_game_progress():
    try:  # Try loading the local save game file ("game_progress.txt").
        with open('game_progress.txt') as f:
            if input("Load existing game? (Y/N) ").lower() == "y":
                return int(f.readlines()[0])  # If player chose to load game, load last index from save file.
            else:
                print("Starting a new game...")
                return 1  # If player chose to start a new game, set index to 1.
    except:  # If save game file wasn't found, start a new game instead.
        print("Starting a new game...")
        return 1


def process_answer(i):
    answer = input(steps[i]['Text'] + " (Y/N/Save) ")  # Print the item's text and ask for Y or N

    if answer.lower() == "y":  # If answer is "Y" or "n"
        return steps[i]['Yes']  # Go to item index of "Yes" for that item

    if answer.lower() == "n":  # If answer is "N" or "n"
        return steps[i]['No']  # Go to item index of "No" for that item

    if answer.lower() == "save":  # If answer is "save".
        with open('game_progress.txt', 'w') as f:
            f.write(str(i))  # Create / overwrite save game file.
            print("Saved game. Going back to question:")
        return i  # Mark answers as accepted

    print('\n⚠ Wrong answer; please write "Y", "N", or "SAVE" - then click ENTER.\n')  # If answer is none of the above.
    return i


if __name__ == '__main__':
    index = load_game_progress()

    while not steps[index].get("Game Over", False):  # While this step doesn't have a Key "Game Over" with value of True
        index = process_answer(index)

    print(steps[index]['Text'])  # print the text of the item that ends the game.
    print("Congratulations! You finished the game.")

与您的问题有关的主要部分是此功能:

def load_game_progress():
    try:  # Try loading the local save game file ("game_progress.txt").
        with open('game_progress.txt') as f:
            if input("Load existing game? (Y/N) ").lower() == "y":
                return int(f.readlines()[0])  # If player chose to load game, load last index from save file.
            else:
                print("Starting a new game...")
                return 1  # If player chose to start a new game, set index to 1.
    except:  # If save game file wasn't found, start a new game instead.
        print("Starting a new game...")
        return 1

【讨论】:

    猜你喜欢
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    相关资源
    最近更新 更多