Skip to content Skip to sidebar Skip to footer

How To Save Board Game? Python

I have programmed Connect 4 using python, and I wanted to make a Save option although I'm unsure how I would save all of the users inputs. Which would be mainly all the counters th

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"