Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Behind 2048 by ChubinOleg
# migrated from python 2.7
def move2048(state, move):
def move_cell(x, y, dx, dy):
x1, y1 = x, y
while 0 <= y+dy < 4 and 0 <= x+dx < 4 and not state[y+dy][x+dx]:
y += dy
x += dx
old_value = state[y1][x1]
state[y1][x1] = 0
if 0 <= y+dy < 4 and 0 <= x+dx < 4 and state[y+dy][x+dx] == old_value:
if old_value == 1024:
return True
state[y+dy][x+dx] = str(2 * old_value)
else:
state[y][x] = old_value
dx = {'left': -1, 'right': +1}.get(move, 0)
dy = {'up': -1, 'down': +1}.get(move, 0)
y_range = list(range(3, -1, -1)) if move == 'down' else list(range(4))
x_range = list(range(3, -1, -1)) if move == 'right' else list(range(4))
for y in y_range:
for x in x_range:
result = move_cell(x, y, dx, dy)
if result is True:
return [list('UWIN') for _ in state]
for y in range(3, -1, -1):
for x in range(3, -1, -1):
if not state[y][x]:
state[y][x] = 2
break
else:
continue
break
else:
return [list('GAME'), list('OVER'), list('GAME'), list('OVER')]
return [list(map(int, i)) for i in state]
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!"
Sept. 30, 2014
Comments: