2048游戏的Merge_left功能

时间:2017-03-21 11:32:03

标签: python list nested-lists

我想在游戏2048上定义merge_left功能,这就是我想出的:

def merge_left(mat):
    score=0
    def helper(row,a):
        if not row:
            return a
        x=row[0]
        if len(row)==1:
            return helper(row[1:],a+[x])
        return helper(row[2:], a + [2*x]) if x == row[1] else helper(row[1:], a + [x])
    store=[]
    for row in mat:
        merged = helper([x for x in row if x != 0], [])
        merged = merged + [0]*(len(row)-len(merged))
        store.append(merged)
        score+=accumulate(lambda x,y:x+y,0,merged)
    def is_true(store):
        if store==mat:
            return False
        else:
            return True
    return (store,is_true(store),score)

然而,对于score,我只想要所有新形成的图块的值的总和,而不是所有数字的总和。如何过滤它们以便我只添加新形成的瓷砖? 在这种情况下,我应该使用迭代而不是递归吗?

示例:

merge_left([[2, 2, 0, 2], [4, 0, 0, 0], [4, 8, 0, 4], [0, 0, 0, 2]])
#([[4, 2, 0, 0], [4, 0, 0, 0], [4, 8, 4, 0], [2, 0, 0, 0]], True, 4)

请帮忙。谢谢!

0 个答案:

没有答案