如何在文字冒险游戏中创建"Save"选项?



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

在我的例子中,有一个书面的故事,从一行到另一行,直到最后。所以这很难照本宣科。

我的问题是,如果玩家键入命令保存,而不是"是"或"否",当游戏给你这个选项时,我如何创建一个保存点,玩家可以加载他停止的确切时刻,然后加载并立即跳到这行代码。

例如:

#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")

据我所知,在执行过程中没有内置的方法来保存(或"转到"(特定的代码行。这意味着您将不得不对程序的实际结构进行一些调整。

在我看来,你需要:

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

这个想法的概要是:

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

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

这样,我既可以提供保存游戏的功能,也可以提供如何操作的逻辑。

每一行都有明确的说明,你所要做的就是在";CCD_ 1";构建游戏。

# "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

最新更新