Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Behind 2048 by mortonfox
def rotate(state):
return [list(reversed([row[i] for row in state])) for i in range(len(state))]
def collide(row):
row = [n for n in row if n != 0]
if len(row) > 1:
for i in range(len(row) - 1, 0, -1):
if row[i] == row[i-1]:
row = collide(row[:i-1]) + [row[i] * 2] + row[i+1:]
break
return ([0, 0, 0, 0] + row)[-4:]
# Only need to handle shifting to the right because we can rotate before/after.
def shift(state):
return [collide(row) for row in state]
ROTATE_TABLE = { 'up': 1, 'down': 3, 'left': 2, 'right': 0 }
def ins_cell(state):
for row in range(len(state) - 1, -1, -1):
for col in range(len(state[row]) - 1, -1, -1):
if state[row][col] == 0:
state[row][col] = 2
return state
def is_win(state):
return any(any(cell == 2048 for cell in row) for row in state)
def move2048(state, move):
newstate = state
rot_count = ROTATE_TABLE[move]
for i in range(rot_count):
newstate = rotate(newstate)
newstate = shift(newstate)
for i in range(4 - rot_count):
newstate = rotate(newstate)
ins_cell(newstate)
if is_win(newstate):
return [['U', 'W', 'I', 'N']] * 4
if state == newstate:
return [['G', 'A', 'M', 'E'], ['O', 'V', 'E', 'R']] * 2
return newstate
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. 9, 2018
Comments: