Imagine that I have a game and I quit the game in the middle of it and then I enter in the game again and I have 2 options, option 1 is to create a new game and option 2 is to reload the state of where I were. My question is, how can I make that?
Asked
Active
Viewed 110 times
-2
-
4Make a savegame? Save the state of the game to a file? – Sören Jan 31 '22 at 20:12
-
@Sören Exactly that, it can be any kind of python file it doesn't have to be a game, I just want to save the state of the file. – Bernardo Pereira Jan 31 '22 at 20:15
-
@kpie Maybe it does, I need to try it in my program – Bernardo Pereira Jan 31 '22 at 20:21
1 Answers
2
If you want to reload the status of the old game, you have to save the information of the old game to a file and load it from the file the next time you play.
Storing:
import json
with open('file.txt','w') as f:
f.write(json.dumps( myData ))
Loading:
import json
with open("file.txt", "r") as f:
myData = json.load(f)

Simon Walker
- 56
- 5
-
1
-
-
1the myData variable will be saved even if your python program is restarted. So, you can put anything in there that you don't want to be erased. You should put the state of the game inside there. – Simon Walker Jan 31 '22 at 20:34
-
-
Let's say you have a tic tac toe game and X played in the corner and O played beneath. The 'state' of the game is "X-- O-- ---". You would do myData = "X-- O-- ---" and Store the data. Later, you would Load the data and look at the variable to see where the X and the O are. – Simon Walker Jan 31 '22 at 20:42
-
I have a Tic Tac Toe game but i save the state of the board in a list and apparently json cant load lists what can I do? – Bernardo Pereira Jan 31 '22 at 20:51
-
-
This is my error `raise TypeError(f'the JSON object must be str, bytes or bytearray, TypeError: the JSON object must be str, bytes or bytearray, not list` – Bernardo Pereira Jan 31 '22 at 21:01
-
Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/241591/discussion-between-simon-walker-and-bernardo-pereira). – Simon Walker Jan 31 '22 at 21:18