游戏矩阵大小为 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)