Python2048小游戏核心算法(python系列26)

前言:做核心算法之前我们可以玩一玩这个小游戏来了解一下规则。2048在线试玩

运行效果:

Python2048小游戏核心算法(python系列26)_第1张图片

Python2048小游戏核心算法(python系列26)_第2张图片 Python2048小游戏核心算法(python系列26)_第3张图片

代码案例:

# 2048小游戏

# 1.将列表中零移动到列表的末尾
def move_zeroes():
    x = 0
    for i in range(len(list_nums)):
        if list_nums[i] != 0:
            list_nums[x], list_nums[i] = list_nums[i], list_nums[x]
            x += 1


# 2.将相邻相等的合并
def merge():
    move_zeroes()
    for i in range(len(list_nums) - 1):
        if list_nums[i] == list_nums[i + 1]:
            list_nums[i] *= 2
            list_nums.pop(i + 1)
            list_nums.append(0)


# 向左移动
def move_left():
    global list_nums
    for item in list_map:
        list_nums = item
        merge()


# 向左移动
def move_right():
    global list_nums
    for item in list_map:
        list_nums = item[::-1]
        merge()
        item[::-1] = list_nums

def transpose():
    global list_map
    list_map = list((list(item) for item in zip(*list_map)))


# 向上移动
def move_up():
    transpose()
    move_left()
    transpose()


# 向上移动
def move_down():
    transpose()
    move_right()
    transpose()


def select_num():
    show_all()
    num = input("请操作(wsad):")
    if num == 'w':
        move_up()
        show_all()
    elif num =='s':
        move_down()
        show_all()
    elif num == 'a':
        move_left()
        show_all()
    elif num == 'd':
        move_right()
        show_all()


def show_all():
    for item in list_map:
        for i in item:
            print(i, end='\t')
        print()


if __name__ == '__main__':
    list_nums = None  # type:list | None
    list_map = [
        [2, 0, 2, 0],
        [0, 2, 0, 2],
        [4, 0, 4, 0],
        [0, 2, 0, 2]
    ]
    while True:
        select_num()
        print("---------------------")

你可能感兴趣的:(python,算法)