1. 程式人生 > >20行程式碼實現2048

20行程式碼實現2048

Python程式碼(直接複製可玩)

from random import choice
def combline(ls):
    ls=[i for i in ls if i > 0]
    for i in range(len(ls)-1):
        if ls[i]==ls[i+1]:
            ls[i],ls[i+1]=ls[i]*2,0;break
    else:return ls+[0]*(4-len(ls))
    return combline(ls)
left=lambda matric:[combline(matric[i]) for i in
range(4)] matric=[[0 for j in range(4)] for i in range(4)] directions = {'a': left,'d': lambda matric:[list(reversed(i)) for i in left([list(reversed(i)) for i in matric])],'w': lambda matric:[[left([[matric[j][i] for j in range(4)] for i in range(4)])[j][i] for j in range(4)] for i in range(4)],'s'
: lambda matric:[[[list(reversed(i)) for i in left([list(reversed(i)) for i in [[matric[j][i] for j in range(4)] for i in range(4)]])][j][i] for j in range(4)] for i in range(4)]} while True: i, j = choice([(i, j) for i in range(4) for j in range(4) if matric[i][j] == 0]) matric[i][j] = 2 for
i in matric:print(*i, sep='\t') while True: direction = input('w, s, a, d: ').strip() # 上 w 下 s 左 a 右 d if direction in directions: if matric != directions[direction](matric): matric = directions[direction](matric);break

這B裝得還可以吧~下面來還原詳細過程

from random import choice
# combine row __________________________________________________________________________________________________________
def combline(ls):
    # remove zero
    ls = [i for i in ls if i > 0]
    # left combination
    for i in range(len(ls)-1):
        if ls[i] == ls[i+1]:
            ls[i] *= 2
            ls[i+1] = 0
            break
    else:
        # without combination
        return ls + [0] * (4 - len(ls))
    # go on combining
    return combline(ls)
# direction ____________________________________________________________________________________________________________
# left
def left(matric):
    return [combline(matric[i]) for i in range(4)]
# right
def right(matric):
    reverse = [list(reversed(i)) for i in matric]
    reverse = left(reverse)
    reverse_2 = [list(reversed(i)) for i in reverse]
    return reverse_2
# up
def up(matric):
    transpose = [[matric[j][i] for j in range(4)] for i in range(4)]
    transpose = left(transpose)
    transpose_2 = [[transpose[j][i] for j in range(4)] for i in range(4)]
    return transpose_2
# down
def down(matric):
    reverse_transpose = [list(reversed(i)) for i in [[matric[j][i] for j in range(4)] for i in range(4)]]
    reverse_transpose = left(reverse_transpose)
    transpose_reverse = [[[list(reversed(i)) for i in reverse_transpose][j][i] for j in range(4)] for i in range(4)]
    return transpose_reverse
# show _________________________________________________________________________________________________________________
def show_matric(matric):
    print('+-----+-----+-----+-----+')
    for i in matric:
        for j in i:
            if j == 2:
                print('|\033[35m%5d' % j, end='\033[0m')
            elif j >= 1024:
                print('|\033[31m%5d' % j, end='\033[0m')
            elif 2 < j < 1024:
                print('|\033[33m%5d' % j, end='\033[0m')
            else:
                print('|%5d' % j, end='')
        print('|')
        print('+-----+-----+-----+-----+')
# judgment _____________________________________________________________________________________________________________
def defeat(matric):
    if [(i, j) for i in range(4) for j in range(4) if matric[i][j] == 0] == []:
        if matric == left(matric) == right(matric) == up(matric) == down(matric):
            score = sum([sum(i) for i in matric])
            show_matric(matric)
            print('Your score \033[36;7m', score, '\033[0m game over', sep='')
            exit()
# play _________________________________________________________________________________________________________________
def play(matric):
    directions = {'a': left, 'd': right, 'w': up, 's': down}
    while True:
        zero_list = [(i, j) for i in range(4) for j in range(4) if matric[i][j] == 0]
        i, j = choice(zero_list)
        matric[i][j] = 2
        defeat(matric)
        show_matric(matric)
        while True:
            direction = input('w, s, a, d: ').strip()
            if direction in directions:
                if matric != directions[direction](matric):
                    matric = directions[direction](matric)
                    break
# test _________________________________________________________________________________________________________________
# matric0 = [
#     [16384, 8192, 2048, 512],
#     [512, 1024, 128, 256],
#     [16, 32, 64, 32],
#     [4, 16, 0, 0]]
matric0 = [[0 for j in range(4)] for i in range(4)]
play(matric0)

關於2048,核心演算法有3個

1、一維合併
[2,0,2,4] → [8,0,0,0]
def combline(ls):
    # remove zero
    ls = [i for i in ls if i > 0]
    # left combination
    for i in range(len(ls)-1):
        if ls[i] == ls[i+1]:
            ls[i] *= 2
            ls[i+1] = 0
            break
    else:
        # without combination
        return ls + [0] * (4 - len(ls))
    # go on combining
    return combline(ls)
2、矩陣轉置以及還原
[2, 2, 4, 8] ——> [2, 0, 0, 0] ——> [2, 2, 4, 8]
[0, 4, 0, 0] ——> [2, 4, 4, 8] ——> [0, 4, 0, 0]
[0, 4, 0, 0] ——> [4, 0, 0, 0] ——> [0, 4, 0, 0]
[0, 8, 0, 0] ——> [8, 0, 0, 0] ——> [0, 8, 0, 0]
# matric & length & print ______________________________________________________________________________________________________
matric = [
    [2, 2, 4, 8],
    [0, 4, 0, 0],
    [0, 4, 0, 0],
    [0, 8, 0, 0]]
length = len(matric)
def show_matric(matric):
    for i in matric:
        print(i)
    print()
# transpose ----------------------------------------------------------
transpose = [[matric[j][i] for j in range(length)] for i in range(length)]
show_matric(transpose)
# restore
restore = [[transpose[j][i] for j in range(length)] for i in range(length)]
show_matric(restore)
3、轉置 ——> 合併 ——> 還原
[2, 2, 4, 8] ——> [2, 0, 0, 0] ——> [ 2 , 0 , 0 , 0 ] ——> [ 2, 2 , 4 , 8 ]
[0, 4, 0, 0] ——> [2, 4, 4, 8] ——> [ 2 ,16, 0 , 0 ] ——> [ 0,16, 0 , 0 ]
[0, 4, 0, 0] ——> [4, 0, 0, 0] ——> [ 4 , 0 , 0 , 0 ] ——> [ 0, 0 , 0 , 0 ]
[0, 8, 0, 0] ——> [8, 0, 0, 0] ——> [ 8 , 0 , 0 , 0 ] ——> [ 0, 0 , 0 , 0 ]
# combine row __________________________________________________________________________________________________________
def combline(ls):
    # remove zero
    ls = [i for i in ls if i > 0]
    # left combination
    for i in range(len(ls)-1):
        if ls[i] == ls[i+1]:
            ls[i] *= 2
            ls[i+1] = 0
            break
    else:
        # without combination
        return ls + [0] * (4 - len(ls))
    # go on combining
    return combline(ls)
# direction _________________________________________________________________________________________________________________
# left
def left(matric):
    return [combline(matric[i]) for i in range(4)]
# up
def up(matric):
    transpose = [[matric[j][i] for j in range(4)] for i in range(4)] # 轉置
    transpose = left(transpose) # 合併
    restore = [[transpose[j][i] for j in range(4)] for i in range(4)] # 還原轉置
    return restore

最後,還可以自定義策略,讓程式自動玩

from random import choice
# combine row __________________________________________________________________________________________________________
def combline(ls):
    # remove zero
    ls = [i for i in ls if i > 0]
    # left combination
    for i in range(len(ls)-1):
        if ls[i] == ls[i+1]:
            ls[i] *= 2
            ls[i+1] = 0
            break
    else:
        # without combination
        return ls + [0] * (4 - len(ls))
    # go on combining
    return combline(ls)
# direction ____________________________________________________________________________________________________________
# left
def left(matric):
    return [combline(matric[i]) for i in range(4)]
# right
def right(matric):
    reverse = [list(reversed(i)) for i in matric]
    reverse = left(reverse)
    reverse_2 = [list(reversed(i)) for i in reverse]
    return reverse_2
# up
def up(matric):
    transpose = [[matric[j][i] for j in range(4)] for i in range(4)]
    transpose = left(transpose)
    transpose_2 = [[transpose[j][i] for j in range(4)] for i in range(4)]
    return transpose_2
# down
def down(matric):
    reverse_transpose = [list(reversed(i)) for i in [[matric[j][i] for j in range(4)] for i in range(4)]]
    reverse_transpose = left(reverse_transpose)
    transpose_reverse = [[[list(reversed(i)) for i in reverse_transpose][j][i] for j in range(4)] for i in range(4)]
    return transpose_reverse
# show _________________________________________________________________________________________________________________
def show_matric(matric):
    print('+-----+-----+-----+-----+')
    for i in matric:
        for j in i:
            if j == 2:
                print('|\033[35m%5d' % j, end='\033[0m')
            elif j >= 1024:
                print('|\033[31m%5d' % j, end='\033[0m')
            elif 2 < j < 1024:
                print('|\033[33m%5d' % j, end='\033[0m')
            else:
                print('|%5d' % j, end='')
        print('|')
        print('+-----+-----+-----+-----+')
# judgment _____________________________________________________________________________________________________________
def defeat(matric):
    if [(i, j) for i in range(4) for j in range(4) if matric[i][j] == 0] == [