Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Behind 2048 by jcg
dict_delta = {'up' : (-1,0), 'right' : (0,1), 'down' : (1,0), 'left' : (0,-1),}
def move2048(board, direction) :
def move(x, y, direction) : # tile move
global dict_delta
nonlocal size, board, changed
for mov in range(size-1) : # max n-1 moves
value = board[x][y]
if value == 0 :
return
new_x, new_y = (x + dict_delta[direction][0],
y + dict_delta[direction][1])
if not(0 <= new_x < size and 0 <= new_y < size) :
break
t = board[new_x][new_y]
if t != 0 and (changed[new_x][new_y] == 1
or changed[x][y] == 1
or t != value ):
break
# real move
board[x][y] = 0
board[new_x][new_y] = value
if t != 0 : # merge
board[new_x][new_y] *= 2
changed[new_x][new_y] = 1
x, y = new_x, new_y
def win() :
for x in range(len(board)) :
for y in range(len(board[x])) :
if board[x][y] == 2048 :
return True
return False
size = len(board)
changed = [[0 for i in range(size)] for j in range(size)]
if direction in {'up','left'} :
order = [(i,j) for i in range(size) for j in range(size)]
elif direction in {'down', 'right'} :
order = [(i,j) for i in reversed(range(size)) for j in reversed(range(size))]
for (i,j) in order :
move(i,j, direction)
if win() :
board = [list('UWIN')]*4
else :
for i in reversed(range(size)) :
for j in reversed(range(size)) :
if board[i][j]==0 :
board[i][j]=2
break
else :
continue
break
else :
board = [list('GAME'),list('OVER')]*2
return board
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!"
June 15, 2014
Comments: