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