在python中为游戏2048创建高效的合并功能

时间:2016-04-20 05:19:19

标签: python list merge array-merge

我知道有很多关于这个主题的帖子,但是我采取了稍微不同的方法。

def merge(line):
    """
    Function that merges a single row or column in 2048.
    """
    #remove all non zeros
    no_zeros = [ num for num in line if num != 0 ] 

    #make a pair of all adjacent numbers 
    pairs = zip(no_zeros[:-1] , no_zeros[1:])
    #create a boolean value for each pair depending whether elements are equal  
    is_pair = map( lambda (x,y): x == y , pairs ) 

    merged = []
    count = 0
    last = False #if elements in the last pair are euqal this is true 
    #merging algo 
    for i,pair in enumerate(is_pair):
        if last == False and pair == True :
            merged.append(pairs[i][0]*2)
            last = True #As this is a valid pair the next pair will not need to be 
                        #checked as the first number is the last number from this pair
        # The following two statements allows the pair to be checked it's
        # numbers have not been checked in any previous pair 
        if last == True: 
            count += 1
        if count == 2:
            last = False
            count = 0 

    return merged

print merge([2, 0, 2, 4, 0])
print 'should return [4, 4, 0, 0]'
print '-------------------------------'
print merge([0, 0, 2, 2])
print 'should return [4, 0, 0, 0]'
print '-------------------------------'
print merge([2, 2, 0, 0])
print 'should return [4, 0, 0, 0]'
print 'to merge [2, 2, 2, 2, 2]'
print '-------------------------------'
print merge([2, 2, 2, 2, 2])
print 'should return [4, 4, 2, 0, 0]'
print '-------------------------------'
print merge([8, 16, 16, 8])
print 'should return [8, 32, 8, 0]'

到目前为止,我的代码合并了所有对。但是,如果数字不是没有一对,则还需要将其修改为“合并列表”。我无法弄清楚我的生活如何以一种简单的方式做到这一点,其他的是给每个数字一个独特的标记然后如果该标记没有被合并,它被添加到&# 39;合并&#39 ;.我试图实现这个,它变得非常复杂。

任何帮助将不胜感激

任何建议

修改

我用另外两个陈述解决了我的问题:

# This allows 'un-paired' numbers to be added to 'merged' 
if not last and not pair: 
    merged.append(pairs[i][0])
# The above doesn't take into account the last digit, if 'pairs' has len=1 which is solved by:
if i == len(is_pair)-1 and i>1 and (last or not pair) :
    merged.append(pairs[i][1])

1 个答案:

答案 0 :(得分:1)

在您的特定情况下,在我看来,如果lastpair都是False,您可以添加当前对的第一个元素。为此,您需要循环pairs(而不是is_pair),然后检查当前对是否实际上是一对。类似的东西:

for pair in pairs:
    if not last_is_pair:
        is_pair = pair[0] == pair[1]
        if is_pair:
            merged.append(pair[0]*2)
        else:
            merged.append(pair[0])
        last_is_pair = is_pair