Python 8字谜游戏。如何检查和更改代表游戏板平铺的目录键值
这是一个八字游戏(3x3)。我必须把拼图中的空白移到左边(如果可能的话)。我不知道如何检查或更改get_empty()返回的目录中键的值 这应该行得通Python 8字谜游戏。如何检查和更改代表游戏板平铺的目录键值,python,Python,这是一个八字游戏(3x3)。我必须把拼图中的空白移到左边(如果可能的话)。我不知道如何检查或更改get_empty()返回的目录中键的值 这应该行得通 def move_left(self): ''' Moving the space to left :return: a new board position or None if not possible ''' if self.empty["col"] == 0: r
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
我不确定我真的理解你的要求。您不应该只更新
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
但这并不能正确地更新电路板。它只是让
self.empty
指向一个不是空单元格的单元格。请阅读我不知道如何检查或更改get_empty()返回的目录中键的值
。。。这里OP提到了如何更改get_empty()
返回的键的值。您是对的,新值不是空的。但我的猜测是,逻辑可能会在其他一些功能中处理——这是针对人工智能的,而不是针对人类玩家的。在这种情况下,这个解决方案不起作用吗?它仍然会起作用,但正如我所说的,它会稍微慢一点。基本上,你会再次扫描电路板的所有字段以找到空单元格,而实际上你已经知道移动后它会在哪里。
self.empty["col"] -= 1 # update self.empty to new "hole" position