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

前言:做核心算法之前我们可以玩一玩这个小游戏来了解一下规则。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("---------------------")

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值