Python没有复制变量用户定义的类,而是制作指针



我试图制作一种下棋算法;野兽";可能的选择和选择最好的。

为了做到这一点,我写了一个类,它代表了板上的情况(显示了坏代码中使用的部分(。

class Chess:
def __init__(self):
#Here is the board 2D array - enemy is downside.
self.board = [[ROOK, KNIGHT, BISHOP, QUEEN, KING, BISHOP, KNIGHT, ROOK], [PAWN for i in range(8)], [EMPTY for i in range(8)], [EMPTY for i in range(8)], [EMPTY for i in range(8)], [EMPTY for i in range(8)], [ENEMYPAWN for i in range(8)], [ENEMYROOK, ENEMYKNIGHT, ENEMYBISHOP, ENEMYKING, ENEMYQUEEN, ENEMYBISHOP, ENEMYKNIGHT, ENEMYROOK]]
def WriteBoard(self):
WriteBoard(self.board)
def Moove(self, x1, y1, x2, y2):
if x1 >= 8 or x1 < 0 or x2 >= 8 or x2 < 0 or y1 >= 8 or y1 < 0 or y2 >= 8 or y2 < 0:
raise IndexError("Parameter is not correct.")
return
#WARNING: Not checking if moove correct.
self.board[y2][x2] = self.board[y1][x1]
self.board[y1][x1] = EMPTY

其中:

EMPTY = 0
PAWN = 2
ROOK = 17
KNIGHT = 10
BISHOP = 14
QUEEN = 45
KING = 60
ENEMYPAWN = -2
ENEMYROOK = -17
ENEMYKNIGHT = -10
ENEMYBISHOP = -14
ENEMYQUEEN = -45
ENEMYKING = -60

下一部分是函数,返回可能的移动得到国际象棋变量和x,y作为参数:

def PossibleMooves(chessBoard, x, y):
possibleMooves = []
target = chessBoard.board[y][x]
if target == EMPTY:
return possibleMooves
helpVar = chessBoard
if target == PAWN:
try:
if helpVar.board[y + 1][x] == EMPTY:
helpVar.Moove(x, y, x, y + 1)
possibleMooves += [res]
index += 1
helpVar = chessBoard
except IndexError as e:
... #print(e)
elif target == ROOK:
...
... #And so on...
return possibleMooves

请注意,尝试。。。except语句有助于建立移动的正确性(像[y+1][x]这样的索引不可能存在(

但问题是:

变量chesBoardhelpVar一起更改,以及赋予函数的变量。

您可以使用以下代码进行检查:

chess = Chess()
print(chess.board[1][1])
results = PossibleMooves(chess, 1, 1)
print(chess.board[1][1])

输出应为:

2
2

但是:

2
0

helpVar = chessBoard意味着您对helpVar所做的每一次更改都将反映在chessBoard中。它们指向同一个对象。如果你想避免它-克隆棋盘并使用副本。

请参阅此处关于python中的copy。(看看deepcopy(

最新更新