我创建了一个新类,它代表井字游戏中的一个位置。基本上我要做的是制作一个包含所有可能的游戏位置的树,其中每个节点都是一个Position
对象,并使用极小极大算法为玩家找到最佳移动。minimax 算法未在下面显示,因为 Position 类未按要求工作。
该类Position
有一个generate_children
方法可以列出Position
可以从当前位置到达的对象。执行程序,我们得到输出,每次迭代后pos_matrix
,当前Position
对象的值都在变化,这是不希望的。我没有触及pos_matrix
循环中当前位置对象的 ,并play_move
制作了矩阵的副本以避免弄乱它。仍然在pos_matrix
改变每次迭代。
怎么了?我该如何调试它?
试过:搬出play_move
课堂,没用。
注意:0
pos_matrix中的A代表空方格,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)