I am trying to save the variables userName, maxHealth, health, and gold as a player plays. I understand pickle may be of help, but I have really not done much with pickle and I don’t know how or where to implement it for my game. The game has a starting amount of these, but I am just trying to save variables and have them be called whenever a user starts up the game so they can continue playing from where they left off.
code snippet
#setup character, maybe put a load/initiate a pickle and save here?
#if there is no save, and save these:
maxHealth = 10
health = 10
exp = 0
gold = 0
print('Greetings adventurer! What is your name?')
userName = input('>> ')
os.system('clear')
print('Welcome, ' + userName + '!')
time.sleep(2)
os.system('clear')
#else load save below
pickle is one form of serialization, you are free to use others: json, protobufs, csv, or even create your own. It’s just you have to get all the state you want to save into a file, which is effectively a string of bytes that you access with open('file_name')
You can open a file and just write out integers, one line on each, and read them back. The problem with this simple approach is a) you can’t change the order, b) it doesn’t capture type information.
serialization standards like pickle preserve all the type information, so you don’t have to worry if you have an int, or string, or dict.
If you want it readable, I suggest to put all the vars you want to save into a dict and use the json package to write and read from a file back to the dict object. If you want stronger type checks, but not as readable, use pickle.
If you have many users and more complex data, you can also use sqlite, which is a whole SQL database library, but doesn’t require a server.
You’d need Repl Database, and CLIAuth (cliauth.repl.co, for transparency I created it) if you want it to be a leaderboard or a database where you can see other player’s progress.
I appreciate that, and that might be something to look at in the future, but I am more concerned with allowing users (or at least myself) to save their state and come back to it. As @Firepup650 points out, it wont persist for anyone but the repl owner, and I’d be fine with this, even if its not ideal. As much as I want others to play my game, I also just enjoy it. But if I can’t save it for everyone, I might as well just keep it as it is lol
You could make it save for everyone by making it read-write to a DB (Which isn’t secure unless you use something like CLIAuth as @python660 mentioned above).
In that case, I will call this matter closed unfortunately. It was just something for fun, and the game is still pretty fun, or at least I think so lol