我下面定义了一个Snake类以及一个Move方法,该方法应该根据一个动作来计算头部的新位置,将该元素附加到blocks数组中,然后添加到蛇的block数组中,然后弹出该元素的第一个元素列表。
class Snake:
actions = [np.array([-1, 0]), np.array([1, 0]), np.array([0, -1]), np.array([0, 1])]
def __init__(self, start_position, start_direction_idx):
"""
:type start_position: 2x1 numpy Array
"""
self.startPosition = None
self.alive = True
self.direction = start_direction_idx
self.length = 1
self.currentPosition = start_position
self.blocks = deque([start_position])
self.blockAtEndofTail = None
def move(self, action):
if self.isMovingBackwards(action):
action = self.direction
else:
self.direction = action
print('Blocks before anything', self.blocks)
print('Current position before action',self.currentPosition)
self.currentPosition += self.actions[self.direction]
print('Current position after action', self.currentPosition)
print('Blocks before pop',self.blocks)
self.blockAtEndofTail = self.blocks.popleft()
print('Blocks after pop', self.blocks)
self.blocks.append(self.currentPosition)
print('Blocks after append', self.blocks)
print(self.blocks)
下面是我运行程序时得到的一些示例输出。
Blocks before anything deque([array([10, 10])])
Current position before action [10 10]
Current position after action [ 9 10]
Blocks before pop deque([array([ 9, 10])])
Blocks after pop deque([])
Blocks after append deque([array([ 9, 10])])
deque([array([ 9, 10])])
我得到了上面的内容,但我期望下面的内容:
Blocks before anything deque([array([10, 10])])
Current position before action [10 10]
Current position after action [ 9 10]
Blocks before pop deque([array([ 10, 10])])
Blocks after pop deque([])
Blocks after append deque([array([ 9, 10])])
deque([array([ 9, 10])])
如何通过我的方法更改双端队列中的值?
blocks
双端队列中的值实际上是对currentPosition
所引用的同一numpy数组的引用,因为它们都是从start_position
初始化的。如果希望它们独立,请尝试使用copy
:]中内置的Snake.__init__
函数复制值本身,而不是引用。self.blocks = deque([start_position.copy()])