Sorry if this is breaking any rules, it's my first time posting here. The project that we're working on is to create Connect 4 in Python. We're currently struggling on how to get the game to save and load.
What we're doing so far is saving our 2D list in a .txt file and trying to load the game by reading it. The problem that we've encountered is when you're trying to read the file, it reads as a string instead of a list. For example:
[['R', 'R', 'Y', 'R', 'Y', 'Y', 'Y'], ['Y', 'Y', 'R', 'R', 'R', 'Y', 'Y'], ['R', 'R', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E', 'E', 'E']]
That gets saved as a string and we'd like to convert it back to be used to place saved dots back where they belong.
def save():
global GAME_LIST
save_file = open("savedGame.txt","w")
print('Game', GAME_LIST)
save_file.write(str(GAME_LIST))
#Will basically be the new def main() once you load a file.
def load():
global PIECES
savedFile = open("savedGame.txt","r")
loadedState = savedFile.readline()
print(loadedState)
grid()
PIECES = {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0}
def newRed(column):
coordinates = {'1': -210, '2': -140, '3': -70, '4': 0, '5': 70, '6': 140, '7': 210}
red = turtle.Turtle()
red.hideturtle()
red.up()
#Pieces * Cell length for Y value
red.goto(coordinates[column], -160 + (PIECES[column] * 70))
PIECES[column] += 1
red.dot(60, 'red')
def newYellow(column):
coordinates = {'1': -210, '2': -140, '3': -70, '4': 0, '5': 70, '6': 140, '7': 210}
#Computer turtle
yellow = turtle.Turtle()
yellow.hideturtle()
yellow.up()
yellow.goto(coordinates[column], -160 + (PIECES[column] * 70))
PIECES[column] += 1
yellow.dot(60, 'yellow')
def toList(stringState):
sublist = []
for characters in stringState:
sublist.append(characters)
print(sublist)
return sublist
def reDot(loadedState):
global ROW
global COLUMN
for sortList in range(ROW):
newList = loadedState[sortList]
for sortSubList in range(COLUMN):
sortSubList = int(sortSubList)
if newList[sortSubList] == "R":
newRed(sortSubList + 1)
elif newList[sortSubList] == "Y":
newYellow(sortSubList + 1)
newList = toList(loadedState)
reDot(newList)
This is a snippet of our code for reference. reDot() is supposed to take the location of 'R'/'Y' and place a dot there.