Я использовал JSON Библиотека для преобразования классов в словарей. Вот пример моего кода. < /p>
Код: Выделить всё
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}"))
Спасибо
Подробнее здесь: https://stackoverflow.com/questions/793 ... -adventure