jhn wck
jhn wck

Reputation: 1

How to create a "Save" option in a text adventure game?

I would like to know how I could create "savepoints" in my text adventure game.

In my case there is a written story that goes from line to line until it reaches the end. So it's hard scripted.

My question would be, if the player types the command save for example instead of yes or no, when the game gives you that option, how could I create a save-point where the player can load this exact moment where he stopped and then it gets loaded and jumps instantly to this line of code.

For example:

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

Upvotes: 0

Views: 1635

Answers (2)

Robby Frank
Robby Frank

Reputation: 304

I created the entire game for you with the ability to save your progress as requested in the question.

This way I can provide both the function for saving the game, as-well-as the logic for how that could work.

Each line has clear instructions, and all you have to do is add new steps to "steps" to build the game.

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

The main part relating to your question is this function:

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

Upvotes: 1

Tomerikoo
Tomerikoo

Reputation: 19405

As far as I am aware, there is no built-in way to save (or "go-to") a specific line of code during execution. This means you will have to play around a bit with the actual structure of your program.

The way I see it, you need to:

  • decide on certain "checkpoints" in your game, and structure the code into functions around those checkpoints.
  • Then, you can save all those checkpoint-functions sequentially in a list.
  • When then user saves the game, you can just write the checkpoint number to a text file or any other format.
  • Upon "loading" the game, read the number saved in the file and jump to the matching checkpoint-function from the list.

An outline of the idea is:

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, ...]

And when you start a game:

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

Upvotes: 2

Related Questions