I'm trying to make a loop that saves the progress in a game of connect four when a round ends.The csv has to display the game board as follows. Each blank spot is represented by a '0', an 'O' is represented by a '2' and an 'X' by a 1. Now while this loop is supposed to loop through and change both the rows and the columns in the csv file, i get everyting stacked in one column. Why is that?
if turn == 'X':
turn = "O"
else:
board_deepcopy = copy.deepcopy(my_board)
ans = input('Type s to save your progress : ')
if ans == 's':
nop = input('Type in the name of your save file :')
f = open(nop + '.csv', 'a', newline = '')
writer = csv.writer(f)
for y in range(board_col):
list1 = []
for l in range(board_col):
if my_board[y][l] == 'X':
board_deepcopy[y][l] = '1'
list1.append(board_deepcopy[y][l])
writer.writerow(list1[l])
elif my_board[y][l] == 'O':
board_deepcopy[y][l] = '2'
list1.append(board_deepcopy[y][l])
writer.writerow(list1[l])
else:
board_deepcopy[y][l] = '0'
list1.append(board_deepcopy[y][l])
writer.writerow(list1[l])
f.close()
turn = 'X'
(example of display of board of 8 columns and 8 rows with an 'X' on column 1 and an 'O' on column 2:) windows terminal:
1 2 3 4 5 6 7 8
________________________________________
A|' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|
B|' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|
C|' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|
D|' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|
E|' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|
F|' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|
G|' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '|
H| X O ' ' ' ' ' ' ' ' ' ' ' '|
---------------------------------------
csv display:
A B C D E F G H
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 1
...
16 2
17 0
18 0
19 0
...
64 0
Your
forloop is not doing what you want it to. You are appending to your list, but then you directly save the newly appended element to yourcsv file. What you want to do is to save the entire list after yourinner for loopis done to your file and then go on with theouter for loop. Here is how I think you want to design your loop: