I'm making a text based game to better learn python. I made some classes, and I want to code a save state for the game. I could write/read every attribute of each class to a file individually, but obviously that's a hassle. I've used pickle, but I have the save/load in different functions, so pickle works in the function, but when it kicks back to the main, the class reverts back to before the load. So 2 questions: 1. Is there a way to prevent the class from reverting using pickle? Or 2: Is there a way to simplify file.write(class)
?
Here's the code I've been testing with. I've simplified the main so it could be easy to change the attributes and check to see if the load worked properly.
class game:
def __init__(self, position, coins):
self.position = position
self.coins = coins
player = game("start", 10)
#save w/ pickle - works
def save():
save = input("Enter name: ")
with open(save + ".txt", "wb") as file:
pickle.dump(player, file)
#save w/o pickle - works, would require a LOT of code
def save():
save = input("Enter name: ")
with open(save + ".txt", "w") as file:
file.write(player.position)
#file.write(<other attributes>)
#load w/ pickle - player class doesn't transfer out of function
def load():
try:
load = input("Enter name: ")
with open(load + ".txt", "rb") as file:
player = pickle.load(file)
print(player.position)
print(player.coins)
except FileNotFoundError:
print("File doesn't exist.")
#load w/o pickle - works, would require a LOT of code
def load():
try:
load = input("Enter name: ")
with open(load + ".txt", "rb") as file:
player.position = file.read()
#will need to modified to read each line separately
print(player.position)
print(player.coins)
except FileNotFoundError:
print("File doesn't exist.")
a = ""
while a.lower() != "exit":
a = input("Enter input: ")
if a.lower() == "save":
save()
elif a.lower() == "load":
load()
elif a.lower() == "p":
player.position = "pond"
print(player.position)
elif a.lower() == "b":
player.position = "bridge"
print(player.position)
elif a.lower() == "s":
player.position = "start"
print(player.position)
elif a.lower() == "print":
print(player.position)
print(player.coins)
elif a.lower() == "-":
player.coins -= 1
print(player.coins)
Thanks in advance.