核心功能实现:
代码1(https://blog.csdn.net/hebtu666/article/details/81663648)
def left():#向左
for i in range(4):#遍历每一行
for j in range(3):#遍历每一行的每个元素
for k in range(j+1,4):#遍历j右边的元素
if l[i][k]!=0:#如果不是零,进行操作。
#是零就可以遍历下个k,因为0不会对本个j和下面的k的合并产生影响。
#注意2048不能跨过一个数进行合并,比如242,2和2不能合并
if l[i][j]==0:#本个j是0
l[i][j]=l[i][k]#把j赋值为k
l[i][k]=0#k为0
#其实就相当于移动了那个元素
#比如:0 2 x x,无论如何先把2移到0那里,也就是2 0 x x
elif l[i][j]==l[i][k]:#如果相等
l[i][j]=2*l[i][j]#合并
l[i][k]=0#k位置就是0
break
#合并后跳出循环,因为本个j位置不能再和其他位置合并了
#比如:2 2 2 x,变为4 2 x 0,2 2 4 x变为4 4 x 0而不是合并为8
else:
break#都不为零,而且不相同,相当于2 4 x x,就算x是2也不能合并
#直接排除本个j位置。
def down():#向下的操作
for i in range(4):
for j in range(3,0,-1):
for k in range(j-1,-1,-1):
if l[k][i]!=0:
if l[j][i]==0:
l[j][i]=l[k][i]
l[k][i]=0
elif l[j][i]==l[k][i]:
l[j][i]=2*l[j][i]
l[k][i]=0
break
else:
break
def up():#向上
for i in range(4):
for j in range(3):
for k in range(j+1,4):
if l[k][i]!=0:
if l[j][i]==0:
l[j][i]=l[k][i]
l[k][i]=0
elif l[j][i]==l[k][i]:
l[j][i]=2*l[j][i]
l[k][i]=0
break
else:
break
def right():#向右
for i in range(4):
for j in range(3,0,-1):
for k in range(j-1,-1,-1):
if l[i][k]!=0:
if l[i][j]==0:
l[i][j]=l[i][k]
l[i][k]=0
elif l[i][j]==l[i][k]:
l[i][j]=2*l[i][j]
l[i][k]=0
break
else:
break
代码2(https://www.jianshu.com/p/dcf6a69a633a)
编写一个基础移动(右移),其余的方向通过转置矩阵实现:
# 基础移动
def basic(board):
global score
global win
# 以右移为基础移动
for i in range(4):
flag = 1
while flag:
flag = 0
j = 2
while j >= 0:
if board[i, j] != 0:
if board[i, j + 1] == board[i, j]:
board[i, j + 1] = 2 * board[i, j]
board[i, j] = 0
flag = 1
elif board[i, j + 1] == 0:
temp = board[i, j]
board[i, j] = board[i, j + 1]
board[i, j + 1] = temp
flag = 1
j -= 1
return board
# 右移
def move_right(board):
return basic(board)
# 上移
def move_up(board):
# 逆置 + 转置
board = board[::-1, ::-1].T
board = basic(board)
board = board[::-1, ::-1].T
return board
# 左移
def move_left(board):
# 逆置
board = board[::-1, ::-1]
board = basic(board)
board = board[::-1, ::-1]
return board
# 下移
def move_down(board):
# 转置
board = board.T
board = basic(board)
board = board.T
return board