How To Save Board Game? Python
Solution 1:
If you only care about reading this file with Python, then pickle it!
import pickle
fp = '/path/to/saved/file.pkl'withopen(fp, 'wb') as f:
pickle.dump(board, f)
Solution 2:
If your game state gets saved in a simple object, like a list of list of integers, like this:
WIDTH = 7HEIGHT = 6board = [[0 for column in range(WIDTH)] for row in range(HEIGHT)]
then you can also use JSON instead of pickle to store this object in a file, like this:
import json
fp = "/path/to/saved/file.txt"withopen(fp, "w") as savefile:
json.dump(board, savefile)
Note that this is basically the same answer Alex gave, with pickle replaced with json. The advantage of pickle is that you can store almost all (not too bizarre) Python objects, while the advantage of json is that this format can be read by other programs, too. Also, loading game state from a pickled objected opens you to the risk of maliciously constructed code inside the pickle, if the saved game file can come from arbitrary locations.
If you also want to save the history how your user got there, you have to implement some other data structure to save that history, but you then can save that other data object in a similar fashion.
Post a Comment for "How To Save Board Game? Python"