我试图做一个函数,它在2048板(嵌套列表制作4×4格),这样,所有可能的随机瓷砖
[[0, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2]]
注:我知道这是不是一个现实的2048板,但我选择了简单
的例子和功能应该输出所有的地方的名单随机瓷砖可能出现(或者是2或4)
例如,如果我在上面的板上运行该功能,输出应该是。
[[[2, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2]],
[[4, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2]]]
所以在任何地方都存在一个0,我们想使一个板哪里有0已经被替换为2和其他地方已经换成了4
这里是我的代码,以便远。
def all_rand_tiles(state):
states = []
changed = []
old_states = [None]
while old_states != states:
old_states = states
new_state = state
for row in range(4):
for tile in range(4):
if state[row][tile] == 0:
#AREA WITH PROBLEM BELOW THIS LINE
if [row, tile] not in changed:
new_state[row][tile] = 2
states.append(new_state)
new_state[row][tile] = 4
states.append(new_state)
changed.append([row, tile])
return states
的问题是,当我if语句追加两种不同的状态在最后,这两个州有零变为4.因此函数的输出,如果你在上面板上运行看起来像这样。
[[[4, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2]],
[[4, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2]]]
当我运行new_state[row][tile] = 4
我刚刚创建的状态改变为它有2,有4
你可以看到问题的证明,如果你之前和运行new_state[row][tile] = 4
后打印new_state
糟糕的代码区域。
我非常困惑,我不知道为什么我有这个愚蠢的问题。
编辑:请在发布之前试用您的解决方案。我已向您提供了我正在使用all_rand_tiles
的唯一功能,到目前为止,我一直无法解决已提交的任何答案的问题。
@jonrsharpe请详细说明。 – 2014-08-28 19:50:14
简短的回答可能是“参照平等”。作为一个简单的例子,'a = []; b = a;在b.append(23);打印一个'会打印'[23]',即使你在创建后没有对'a'进行任何明显的修改。 – Kevin 2014-08-28 19:50:27
你正在更换'0'的这块主板是在你刷卡后马上发生的,对吧? – TheSoundDefense 2014-08-28 19:51:58