Skip to content
Advertisement

Trying to figure out how to properly save and load a game in a save.p file using Pickle module

Problem

My problem consists of me trying to save the position of the player on the board that I created and then loading it when they enter a specified SENTINEL value. Though the problem that I am getting at this current time is referencing something before the assignment. This is how I think I should be loading the game.

What I’ve Tried

I’ve tried defining the values that are said not to be defined or referenced after the assignment earlier, though it ended up still giving me the same error and in the end didn’t make sense to me. I’ve looked up a lot of different problems relating to this but didn’t quite get the grasp on it due to terminology and getting to overwhelmed. Hence why I came here to get a straightforward explanation for my exact problem.

Code

Save Game

def SaveGame(player, board):
    playerData = {}
    playerData['player'] = player
    playerData['board'] = board
    saveGame = open("Save.p","wb")
    pickle.dump(playerData, saveGame)
    saveGame.close()

Load Game (where I’m having trouble)

def LoadGame():

    player, board = pickle.load(open("Save.p","rb"))
    return player, board

Commanding Player (using the save game function)

def CommandPlayer(player,board):

    VALID_INPUTS = ["W","A","S","D","Q"]
   
    row = player["row"]
    col = player["col"]

    while True: # Input validation loop.

        userInput = input("Enter a direction (W)(A)(S)(D) to move in or (Q) to quit.): ").upper()

        if userInput in VALID_INPUTS:
            break

    if userInput == "Q":
        SaveGame(player, board)

Main.py (where I’m having trouble with the loading)

def Main(): 
    
    userinput = input("Welcome to the Character Creator 2000, Enter G to generate your Character and stats  or Enter (L) to load a Game (0) to Quit: ").upper() #Requests User Input
    if userinput == ("L"):
        
        LoadGame()
        player, board = CommandPlayer(player, board)
        os.system('cls')
        ShowBoard(board)

Error Message

Advertisement

Answer

You’re not loading the game data back properly. Your SaveGame) function is saving a dictionary, so that is what pickle.load() will return in LoadGame().

Here’s the right way of doing it:

def LoadGame():
    with open("Save.p", "rb") as pkl_file:
        playerData = pickle.load(pkl_file)
    player = playerData['player']
    board = playerData['board']
    return player, board
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement