【发布时间】:2020-02-16 15:53:15
【问题描述】:
我正在尝试在 python 中为井字游戏实现一个简单的最小最大算法我对以下方法有疑问:
def get_best_move(self, board, empty_cells, turns, points=None):
if points is None:
points = []
#here I loop trough the empty cells on the board and fill it with 'X' or 'O'
for cell in empty_cells:
new_board = copy.deepcopy(board)
new_turns = turns.copy()
if turns[-1] == 'X':
new_board[cell[0]][cell[1]] = 'O'
new_turns.append('O')
elif turns[-1] == 'O':
new_board[cell[0]][cell[1]] = 'X'
new_turns.append('X')
#here i select all the empty cells after a move
new_empty_cells = [[index1,index2] for index1,value1 in enumerate(new_board) for index2,value2 in enumerate(value1) if value2==' ']
#here I check if there is a winner and append the points list with 1,0,-1 accordingly
if self.winner(new_board) == 'X':
return points.append(-1)
elif self.winner(new_board) == 'O':
return points.append(1)
elif len(new_empty_cells) == 0:
return points.append(0)
else:
#here I call this method again if there is no winner or the game is not a draw.
self.get_best_move(new_board, new_empty_cells, new_turns, points)
return print(points)
该方法采用以下参数:
board = [[' ',' ',' '],
[' ',' ',' '],
[' ',' ',' ']]
empty_cells = [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]
turns = ['X']
所以给定这样的棋盘应该有 255168 个可能的结果,因此我希望我的积分列表包含 255168 个 1,0,-1 的值,但我只有这个:
[1]
[1]
[1]
[1]
[1]
[1]
理想情况下,我想为 for 循环中的每个单元格获取一个单独的列表。我有一种感觉,我犯了一些非常明显的错误,但我无法发现它,所以任何帮助将不胜感激。
【问题讨论】:
-
如果这里的代码如你所愿,那么
for cell in empty_cells:只会迭代一次:你总是return在第一次迭代中。 -
您能详细说明一下吗?
-
要么
if将导致return语句,要么在for循环体的底部有一个包罗万象的return print(points),所以无论发生什么,你的@987654330 @ 循环将在其第一次迭代中执行return。这说明清楚了吗? -
是的,我很傻,很明显,谢谢你,我修好了,现在可以了。