Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Behind 2048 by morig
def move2048(state, move):
direction = ['left','down','right','up'].index(move)
rotate = lambda s: [[s[3-x][y] for x in range(4)] for y in range(4)]
# rotate the game-board so any move is same as 'left'
for i in range(direction): state = rotate(state)
# check each row
for y, row in enumerate(state):
row = list(sorted(row, key=lambda a:not(a))) # move '0' to the right
for x in range(3):
if row[x] == row[x+1]: # add two of the same numbers
row = row[:x] + [row[x]*2] + row[x+2:] + [0]
state[y] = row
# check special case of game over and win
if any(state[y][x]==2048 for y in range(4) for x in range(4)):
return [['U', 'W', 'I', 'N']] * 4
if not any(state[y][x]==0 for y in range(4) for x in range(4)):
return [['G', 'A', 'M', 'E'], ['O', 'V', 'E', 'R']] * 2
# rotate back, and find the place of last 0, and put 2 there
for i in range((4-direction)%4): state = rotate(state)
emptyx,emptyy = [(x,y) for y in range(4) for x in range(4) if state[y][x]==0][-1]
state[emptyy][emptyx] = 2
return 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!"
Aug. 15, 2014
Comments: