python中的2D数组问题[重复]

s3fp2yjn  于 2023-03-20  发布在  Python
关注(0)|答案(2)|浏览(155)

此问题在此处已有答案

(17个答案)
4小时前关门了。
我正在用python开发一个基于文本的国际象棋项目,我已经在输出控制台中设置了一个非常漂亮的棋盘,但是每当我试图放置一个棋子时,它就会填满整个文件。
我使用的代码如下:

import os
global arrowKey
global speed
newchar = ''
arrowKey = {'\x1b[A': 'up'}
class Pieces:
    Black_rook = '♜'
    Black_knight = '♞'
    Black_bishop = '♝'
    Black_queen = '♛'
    Black_king = '♚'
    Black_pawn = '♟︎'
    White_rook = '♖'
    White_knight = '♘'
    White_bishop = '♗'
    White_queen = '♕'
    White_king = '♔'
    White_pawn = '♙'
class Array:
    def __init__(self, x=16, y=8, board=None):
        self.pos = ()
        self.x = x
        self.y = y
        grid = [' ' + '_' * self.x]
        for _ in range(y):
            row = ['|']
            for _ in range(x):
                row.append(' ')
            row.append('|')
            grid.append(row)
        grid.append(' ' + '‾' * self.x)
        self.grid = grid
        if board != None:
            self.grid = board
    def reload(self, say=None):
        os.system('clear')
        if say != None:
            print(say)
        p = ''
        for i in self.grid:
            p = p + ''.join([x for x in i]) + '\n'
        print(p)
    def insert(self, char, x, y):
        self.pos = (x, y)
        self.grid[y][x] = char
    def move(self, direction, char):
        poslist = []
        for y, i in enumerate(self.grid):
            for x, j in enumerate(i):
                if j == char:
                    poslist.append((x, y))
        count = 0
        for posx, posy in poslist:
            if direction == 'down':
                if self.grid[posy + 1][posx] != '‾':
                    self.insert(' ', posx, posy)
                    self.insert(char, posx, posy + 1)
                    self.pos = (posx, posy + 1)
            if direction == 'up':
                if self.grid[posy - 1][posx] != '_':
                    self.insert(' ', posx, posy)
                    self.insert(char, posx, posy - 1)
                    self.pos = (posx, posy - 1)
            if direction == 'left':
                if self.grid[posy][posx - 1] != '|':
                    self.insert(' ', posx, posy)
                    self.insert(char, posx - 1, posy)
                    self.pos = (posx - 1, posy)
            if direction == 'right':
                if self.grid[posy][posx + 1] != '|':
                    self.insert(' ', posx, posy)
                    self.insert(char, posx + 1, posy)
                    self.pos = (posx + 1, posy)
            count += 1
    def getpos(self, char):
        poslist = []
        for y, i in enumerate(self.grid):
            for x, j in enumerate(i):
                if j == char:
                    poslist.append((x, y))
        return poslist
class Chess(Array):
    def __init__(self):
        row = list(''.join(['.' for i in range(8)]))
        board = [row for i in range(8)]
        super().__init__(board=board)
    def reload(self):
        p = ''
        nums = [i + 1 for i in range(8)]
        nums.reverse()
        for x, i in enumerate(self.grid):
            i = [f'{z} ' for z in i]
            p += f'{nums[x]}  {"".join(i)}\n'
        add = [i + ' ' for i in list('ABCDEFG')]
        add.append('H')
        p += '   ' + ''.join(add) + '\n'
        print(p)
    def move(self, move:str):
        move = move.split(' ')
    def placepiece(self, piece, pos):
        pos = list(pos)
        ykey = [i for i in range(8)]
        ykey.reverse()
        x = [x for x, i in enumerate('ABCDEF') if i == pos[0]][0]
        y = ykey[int(pos[1]) - 1]
        x = int(x)
        return x, y
board = Chess()
x, y = board.placepiece(Pieces.White_pawn, 'E4')
board.grid[y][x] = Pieces.White_pawn
print(board.grid)
board.reload()

我希望在数组的E4处得到一个白色的兵字符,但是它像this一样填满了整个文件。有人能帮我吗?我以前在许多其他项目中使用过2D数组,但是从来没有遇到过这个问题。我很乐意进一步详细说明您需要我做的任何事情。

o4hqfura

o4hqfura1#

问题出在

class Chess(Array):
    def __init__(self):
        row = list(''.join(['.' for i in range(8)]))
        board = [row for i in range(8)]
        super().__init__(board=board)

您正在创建单个列表并在电路板中多次引用它。
更改为:board = [row.copy() for i in range(8)]

nwo49xxi

nwo49xxi2#

问题出在Array构造函数上。在网格列表中,您为棋盘的每一行追加一个名为row的列表。但是,您不是为每一行创建一个新列表,而是反复追加同一行列表。因此,当您修改一行中的单元格时,所有行中的单元格都会被修改。
要解决此问题,您需要为每一行创建一个新列表。您可以通过将行初始化移到创建行的循环中来完成此操作:

grid = [' ' + '_' * self.x]
for _ in range(y):
    row = ['|']
    for _ in range(x):
        row.append(' ')
    row.append('|')
    grid.append(row)
    row = []  # create a new list for the next row
grid.append(' ' + '‾' * self.x)

有了这个改变,你的定位方法应该能正确地工作,并把兵放在你想要的位置。

相关问题