这是一款益智游戏(3x3(。如果可能的话,我必须把拼图中的空白部分移到左边。我不知道如何检查或更改get_empty((返回的目录中键的值。
DEFAULT_BOARD = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
'''
A default board if another board is not specified in the constructor
'''
def get_empty(board):
'''
Finds the position of the empty space in the board
:return: a dictionary eith the row and col of the empty space
'''
for i in range(3):
for j in range(3):
if board[i][j] == 0:
**return {"row": i, "col": j}**
def __init__(self, the_board = DEFAULT_BOARD):
'''
Makes a new node from an initial board
:param the_board: the initial board
'''
if EightGameNode.legal_board(the_board):
# if the board is legal go on
self.board = the_board
else:
# otherwise use the default board
self.board = EightGameNode.DEFAULT_BOARD
self.empty = EightGameNode.get_empty(self.board)
# set the empty space of the board
def move_left(self):
'''
Moving the space to left
:return: a new board position or None if not possible
'''
if self.empty ==
#If the "col" key value is 0 the empty space can't move to the left
return None
else:
#Increase the col value by +1
self.empty
我真的不明白你在问什么。您不应该只更新self.empty
dict,而是应该移动板上的实际值,然后使用您的函数重新计算self.empty
def move_left(self):
r, c = self.empty["row"], self.empty["col"]
# assuming with "move left" you mean to move the "hole" left
if c > 0:
self.board[r][c] = self.board[r][c-1] # move piece to the right into the "hole"
self.board[r][c-1] = 0 # new position of the empty cell
self.empty = EightGameNode.get_empty(self.board)
这将确保self.board
和self.empty
之间的一致性,并使代码更短,并且在不同的move
方法之间不易出现复制粘贴错误。当然,你也可以直接更新self.empty
,这将比再次扫描整个棋盘更快,但如果这实际上是一个人类玩的游戏(而不是例如使用数百万次游戏来训练AI或类似的游戏(,这根本无关紧要。
如果速度真的很重要,并且这造成了太多的减速,那么您可以在if
中像这样更新empty
的位置,并删除下面对get_empty
的调用:
self.empty["col"] -= 1 # update self.empty to new "hole" position
这应该能在中工作
def move_left(self):
'''
Moving the space to left
:return: a new board position or None if not possible
'''
if self.empty["col"] == 0:
return None
else:
self.empty["col"] = self.empty["col"] - 1