Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Behind 2048 by Mahoter
def move2048(state, move):
res = [[],[],[],[]]
if move == 'up' or move == 'down':
col = [[],[],[],[]]
for row in state:
col[0] += [row[0]]
col[1] += [row[1]]
col[2] += [row[2]]
col[3] += [row[3]]
else:
col = []
for row in state:
col += [row]
if move == "right" or move == "down":
a = 0
while a <=3:
col[a] += [col[a].reverse()]
col[a].pop()
a += 1
c = 0
for x in col:
a = 0
b = 0
for y in x:
if y>0:
b += 1
while a < b:
if x[a] == 0:
x.pop(a)
x += [0]
else:
a += 1
a = 0
while a <= 3:
if a < 3 and x[a] == x[a+1]:
x[a] += x[a+1]
b = a + 1
if b == 3:
x[b] = 0
else:
while b < 3:
x[b] = x[b+1]
x[b+1] = 0
b += 1
a += 1
if move == 'up':
res[0] += [x[0]]
res[1] += [x[1]]
res[2] += [x[2]]
res[3] += [x[3]]
elif move == 'down':
res[3] += [x[0]]
res[2] += [x[1]]
res[1] += [x[2]]
res[0] += [x[3]]
else:
res[c] = x
c += 1
if move == "right":
a = 0
while a <=3:
col[a] += [col[a].reverse()]
col[a].pop()
a += 1
a = 3
while a >= 0:
b = 3
while b >= 0:
if a == 0 and b == 0 and res[a][b] != 0:
return [['G','A','M','E'], ['O','V','E','R'], ['G','A','M','E'], ['O','V','E','R']]
elif res[a][b] == 0:
res[a][b] = 2
a = 0
b = 0
b -= 1
a -= 1
for r in res:
for cel in r:
if cel == 2048:
return [['U','W','I','N'], ['U','W','I','N'], ['U','W','I','N'], ['U','W','I','N']]
return res
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert move2048([[0, 2, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 2, 0, 0]], 'up') == [[0, 4, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 2]], "Start. Move Up!"
assert move2048([[4, 0, 0, 0],
[0, 4, 0, 0],
[0, 0, 0, 0],
[0, 0, 8, 8]], 'right') == [[0, 0, 0, 4],
[0, 0, 0, 4],
[0, 0, 0, 0],
[0, 0, 2, 16]], "Simple right"
assert move2048([[2, 0, 2, 2],
[0, 4, 4, 4],
[8, 8, 8, 16],
[0, 0, 0, 0]], 'right') == [[0, 0, 2, 4],
[0, 0, 4, 8],
[0, 8, 16, 16],
[0, 0, 0, 2]], "Three merging"
assert move2048([[256, 0, 256, 4],
[16, 8, 8, 0],
[32, 32, 32, 32],
[4, 4, 2, 2]], 'right') == [[0, 0, 512, 4],
[0, 0, 16, 16],
[0, 0, 64, 64],
[0, 2, 8, 4]], "All right"
assert move2048([[4, 4, 0, 0],
[0, 4, 1024, 0],
[0, 256, 0, 256],
[0, 1024, 1024, 8]], 'down') == [['U', 'W', 'I', 'N'],
['U', 'W', 'I', 'N'],
['U', 'W', 'I', 'N'],
['U', 'W', 'I', 'N']], "We are the champions!"
assert move2048([[2, 4, 8, 16],
[32, 64, 128, 256],
[512, 1024, 2, 4],
[8, 16, 32, 64]], 'left') == [['G', 'A', 'M', 'E'],
['O', 'V', 'E', 'R'],
['G', 'A', 'M', 'E'],
['O', 'V', 'E', 'R']], "Nobody moves!"
Jan. 18, 2016