[Python] Problems with loading a json file into OOP code in a Python text adventure [closed]

Discussão em 'Python' iniciado por Stack, Janeiro 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have been writing a text adventure in Python, using Object Oriented features such as classes and inheritance. The current state of the code works, but when I save a game into JSON format and then load it back into classes, I get unexpected results. Specifically an ObjectDoor is loaded as a base class Object. It happens to be one particular door, another door seems to work fine when i manipulate it from a loaded game, but I can't work out where I went wrong.

    I used the json library to convert classes into dictionaries. here is an example of my code.

    def save_game(self, filename="savegame.json"):
    """Save the game state to a JSON file."""
    game_state = {
    "player": self.player.to_dict(),
    "locations": {name: loc.to_dict() for name, loc in self.locations.items()},
    "objects": {name: obj.to_dict() for name, obj in self.allobjects.items()},
    "current_location": self.current_location.name
    }
    with open(filename, "w") as file:
    json.dump(game_state, file, indent=4)

    print(self.wrap_text(f"{Color.OKGREEN}Game saved successfully!{Color.ENDC}"))

    def load_game(self, filename="savegame.json"):
    """Load the game state from a JSON file."""
    try:
    with open(filename, "r") as file:
    game_state = json.load(file)
    self.player = Player.from_dict(game_state["player"])
    self.locations = {name: Location.from_dict(loc) for name, loc in game_state["locations"].items()}
    self.allobjects = {name: Object.from_dict(obj) for name, obj in game_state["objects"].items()}
    self.current_location = self.locations[game_state["current_location"]]

    # Ensure other_side attribute is correctly set for ObjectDoor objects
    for obj in self.allobjects.values():
    if isinstance(obj, ObjectDoor):
    obj.other_side = self.allobjects.get(obj.other_side)

    print(self.wrap_text(f"{Color.OKGREEN}Game loaded successfully!{Color.ENDC}"))
    self.do_short_look("")

    except (FileNotFoundError, json.JSONDecodeError):
    print(self.wrap_text(f"{Color.FAIL}Failed to load the game. Save file may not exist or be corrupted.{Color.ENDC}"))


    You will probably have to look at the code at https://github.com/bjmcgill/Quest-of-the-Mysteries to see the code in more detail. I have uploaded the most recent changes on the master branch. For some reason I could not delete an earlier main branch.

    To reproduce the error: take key, go south twice, unlock and open the entrance_door_manor. go entrance_door_manor. save. load. try to unlock exit_backdoor_manor and it will think it is the base Object class.

    I guess you will probably have to download the code and run it step by step like I did. But I just couldn't find where the error is.

    I think I made a mistake trying to use OOP techniques in my coding. It would have made things a lot simpler if I had kept my data structures as dictionaries, rather than classes.

    Please tell me what you think of my code, and how it could be improved. I used copilot for a lot of the features, but I found out that it made human like errors, so I had to debug it more or less manually.

    Thanks

    P.S. If nobody finds where I went wrong, I will rewrite the code using dictionaries, rather than classes

    Continue reading...

Compartilhe esta Página