Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
groupby solution in Clear category for Behind 2048 by gyahun_dash
from itertools import chain, groupby
def transpose(state):
return [list(row) for row in zip(*state)]
def slide(row):
groups = ((n, list(g)) for n, g in groupby(c for c in row if c > 0))
divmods = ((n, divmod(len(group), 2)) for n, group in groups)
compress = list(chain(*([2 * n] * q + [n] * r for n, (q, r) in divmods)))
return compress + [0] * (4 - len(compress))
def move2048(state, move):
orient = transpose if move in ('up', 'down') else list
step = 1 if move in ('left', 'up') else -1
normal = (row[::step] for row in orient(state))
slided = (slide(row) for row in normal)
newstate = orient(row[::step] for row in slided)
line = list(chain(*newstate))
if 2048 in line: return [list('UWIN')] * 4
if 0 not in line: return [list('GAME'), list('OVER')] * 2
row, col = divmod(15 - line[::-1].index(0), 4)
newstate[row][col] = 2
return newstate
June 17, 2014
Comments: