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

2024-01-08 20:05:41

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

运行效果:

?

代码案例:

# 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("---------------------")

文章来源:https://blog.csdn.net/a12345dfsdf/article/details/135061186
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。