Created
June 21, 2014 19:16
-
-
Save Snawoot/876b213a5d80fa4c57a1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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