Skip to content

Instantly share code, notes, and snippets.

@Snawoot
Created June 21, 2014 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Snawoot/876b213a5d80fa4c57a1 to your computer and use it in GitHub Desktop.
Save Snawoot/876b213a5d80fa4c57a1 to your computer and use it in GitHub Desktop.
from itertools import groupby, chain
LOSE = [['G', 'A', 'M', 'E'], ['O', 'V', 'E', 'R'], ['G', 'A', 'M', 'E'], ['O', 'V', 'E', 'R']]
WIN = [['U', 'W', 'I', 'N'], ['U', 'W', 'I', 'N'], ['U', 'W', 'I', 'N'], ['U', 'W', 'I', 'N']]
def collide_row(row):
tiles = []
for k,g in groupby(filter(bool,row)):
l = len(list(g))
if l % 2:
tiles.append(k)
tiles.extend([k*2]*(l/2))
return [0]*(len(row)-len(tiles))+tiles
def put_last_tile(S):
l = len(S)-1
for i in xrange(l, -1, -1):
for j in xrange(l, -1, -1):
if S[i][j] == 0:
S[i][j] = 2
return True
return False
def move2048(state, move):
if move == "right":
new_state = [ collide_row(row) for row in state ]
if move == "left":
new_state = [ collide_row(row[::-1])[::-1] for row in state ]
if move == "down":
new_state = map(list,zip(*[ collide_row(column) for column in zip(*state) ]))
if move == "up":
new_state = map(list,zip(*[ collide_row(column[::-1])[::-1] for column in zip(*state) ]))
if 2048 in chain.from_iterable(new_state):
return WIN
if put_last_tile(new_state):
return new_state
else:
return LOSE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment