2048游戏

游戏矩阵大小为 4X4

输入第一个数代表滑动方向,1,2,3,4 分别代表上下左右
接下来的4行输入的是矩阵的各行,以空格分隔。
位于滑动方向侧的数字优先合并,如 2 2 2 0,左滑之后为4 2 0 0

输出为滑动合并之后的矩阵

例1

4
0 0 0 0
0 0 2 2
0 0 4 4
0 2 8 8

输出

0 0 0 0
0 0 0 4
0 0 0 8
0 0 2 16

例2

输入

1
0 2 0 0
2 2 4 2
4 0 4 4
4 2 8 8

输出

2 4 16 2
8 2 0  4
0 0 0  8
0 0 0  0

答案

def push(direction,nums): #滑动函数
    if direction == 1:
        for i in range(4):
            act = [ nums[s][i] for s in range(4)]
            res = action(act)
            for k,v in enumerate(res):
                nums[k][i]=v
    elif direction == 2:
        for i in range(4):
            act = [ nums[s][i] for s in range(3,-1,-1)]
            res = action(act)
            res.reverse()
            for k,v in enumerate(res):
                nums[k][i]=v

    elif direction == 3:
        for i in range(4):
            act = nums[i]
            nums[i] = action(act)
    elif direction == 4:
        for i in range(4):
            act = nums[i]
            act.reverse()
            res = action(act)
            res.reverse()
            nums[i] = res
    else:
        pass

def forword(act):#把非零数往前推的函数
    flag = 0
    act1 = [0, 0, 0, 0]
    for j in act:
        if j != 0:
            act1[flag] = j
            flag += 1
    return act1

def action(act):#滑动每行的函数
    act = forword(act)
    for i in range(3):
        if act[i] != 0 and act[i]==act[i+1]:
            act[i]=act[i]+act[i+1]
            act[i+1] = 0
            act = forword(act)
    return act

def print_nums(nums): #打印矩阵的函数
    for i in range(4):
        for j in nums[i]:
            print(j, end=' ')
        print()

# while True:
#     try:
#         direction = int(input())
#         nums = [0]*4
#         for i in range(4):
#             nums[i] = [int(s) for s in input().split(' ')]
#         push(direction,nums)
#         print_nums(nums)
#     except:
#         break

direction = 3
nums0 = [[2,2,0,2],[0,0,0,2],[0,0,4,8],[0,2,4,8]]
nums1 = [[0,0,0,0],[0,2,2,4],[0,2,8,8],[2,4,2,16]]

nums = nums0
print_nums(nums)
print()
push(direction,nums)
print_nums(nums)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值