我创建了一个新类,代表游戏中的一个位置 Tic Tac Toe .基本上我想做的是制作一棵游戏位置的所有可能性的树,其中每个节点都是一个 Position
对象,并使用 minimax 算法为玩家找到最佳移动。 minimax 算法未在下方显示,因为 Position 类未按要求工作。
Position
类有一个generate_children
方法,它生成一个Position
对象的列表,这些对象可以从当前位置到达。执行该程序,我们得到的输出是,在每次迭代后,当前 Position
对象的 pos_matrix
都会发生变化,这是不希望发生的。我没有触及循环中当前 Position 对象的 pos_matrix
并且 play_move
制作矩阵的副本以避免弄乱它。 pos_matrix
仍在每次迭代中发生变化。
发生了什么?如何调试?
尝试过:将 play_move
移出类,但没有用。
注意:pos_matrix中的0
代表空方 block ,1
代表“X”和-1
代表“O”。
此外,kiska_chance
的意思是“谁的机会”。 :P
class Position:
def __init__(self, parent_):
self.parent = parent_
self.children = []
self.best_move = []
self.pos_matrix = []
self.last_move = []
def set_pos_matrix(self, pos_matrix_):
self.pos_matrix = list(pos_matrix_)
# Avoiding copying problems by creating copy of list
def set_last_move(self, last_move_):
self.last_move = list(last_move_)
# Avoiding copying problems by creating copy of list
def play_move(self, move, kiska_chance):
m2 = list(self.pos_matrix)
x, y = move
m2[x][y] = kiska_chance
return m2
def generate_children(self, kiska_chance):
children_ = []
for move in self.get_possible_moves():
# Passing a Position object into the possible moves with
# parent as self.
pos_temp = Position(self)
pos_temp.set_pos_matrix(self.play_move(move, kiska_chance))
pos_temp.set_last_move(move)
print self.pos_matrix
children_.append(pos_temp)
self.children = children_
return children_
def get_possible_moves(self):
dem_moves = []
for i in xrange(3):
for j in xrange(3):
if self.pos_matrix[i][j]==0:
dem_moves.append([i, j])
return dem_moves
pos = Position(None)
pos.set_pos_matrix([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
pos.generate_children(1)
最佳答案
您在 self.pos_matrix
中有嵌套列表。您只是在复制外部列表。因此,列表中的所有列表仍由两个列表共享。您需要复制列表中的列表。查看更正后的代码:
def play_move(self, move, kiska_chance):
m2 = list(list(l) for l in self.pos_matrix)
x, y = move
m2[x][y] = kiska_chance
return m2
也在:
def set_pos_matrix(self, pos_matrix_):
self.pos_matrix = list(list(l) for l in pos_matrix_)
# Avoiding copying problems by creating copy of list and lists in list
关于python - 实例变量自动修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32323030/