0

我正在尝试制作一个循环,以在一轮结束时保存连接四的游戏中的进度。csv 必须按如下方式显示游戏板。每个空白点用“0”表示,“O”用“2”表示,“X”用 1 表示。现在,这个循环应该循环并更改csv 文件,我将所有内容都堆叠在一列中。这是为什么?

        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'

(显示 8 列和 8 行的板的示例,第 1 列有“X”,第 2 列有“O”:) windows 终端:

      1    2    3    4    5    6    7    8
    ________________________________________
   A|' '  ' '  ' '  ' '  ' '  ' '  ' '  ' '|
   B|' '  ' '  ' '  ' '  ' '  ' '  ' '  ' '|
   C|' '  ' '  ' '  ' '  ' '  ' '  ' '  ' '|
   D|' '  ' '  ' '  ' '  ' '  ' '  ' '  ' '|
   E|' '  ' '  ' '  ' '  ' '  ' '  ' '  ' '|
   F|' '  ' '  ' '  ' '  ' '  ' '  ' '  ' '|
   G|' '  ' '  ' '  ' '  ' '  ' '  ' '  ' '|
   H| X    O   ' '  ' '  ' '  ' '  ' '  ' '|
    ---------------------------------------

csv显示:

  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
4

1 回答 1

0

你的for循环没有做你想做的事。您正在追加到您的列表中,但随后您直接将新追加的元素保存到您的csv file. 您要做的是在inner for loop完成文件后保存整个列表,然后继续使用outer for loop. 以下是我认为您想要设计循环的方式:

import csv

board_col = 4
my_board = [['X', '0', '0', '0'], 
            ['0', 'X', '0', '0'], 
            ['0', '0', 'X', '0'], 
            ['0', '0', '0', 'X']]

f = open('try.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':
            list1.append('1')
        elif my_board[y][l] == 'O':
            list1.append('2')
        else:
            list1.append('0')
    writer.writerow(list1)

f.close()
于 2022-01-18T14:01:45.600 回答