Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Behind 2048 by Moff
from itertools import product
class Game2048(object):
def __init__(self, grid):
self.grid = grid
self.size = len(self.grid)
def merge(self, dest_iterator, src_iterator):
for (dr, dc), (sr, sc) in zip(dest_iterator, src_iterator):
if self.grid[dr][dc] == self.grid[sr][sc]:
self.grid[dr][dc] *= 2
self.grid[sr][sc] = 0
def calc_move(self, direction):
if direction == 'up':
self.move_vertical(False)
self.merge(product(range(self.size - 1), range(self.size)),
product(range(1, self.size), range(self.size)))
self.move_vertical(False)
elif direction == 'down':
self.move_vertical(True)
self.merge(product(range(self.size - 1, 0, -1), range(self.size)),
product(range(self.size - 2, -1, -1), range(self.size)))
self.move_vertical(True)
elif direction == 'left':
self.move_horizontal(False)
self.merge(product(range(self.size), range(self.size - 1)),
product(range(self.size), range(1, self.size)))
self.move_horizontal(False)
elif direction == 'right':
self.move_horizontal(True)
self.merge(product(range(self.size), range(self.size - 1, 0, -1)),
product(range(self.size), range(self.size - 2, -1, -1)))
self.move_horizontal(True)
@staticmethod
def press_array(array, is_zeroes_first):
if is_zeroes_first:
return [x for x in array if x == 0] + [x for x in array if x > 0]
else:
return [x for x in array if x > 0] + [x for x in array if x == 0]
def move_vertical(self, is_zeroes_first):
for col in range(self.size):
for row, x in zip(range(self.size),
self.press_array([self.grid[row][col] for row in range(self.size)], is_zeroes_first)):
self.grid[row][col] = x
def move_horizontal(self, is_zeroes_first):
for row in range(self.size):
for col, x in zip(range(self.size),
self.press_array([self.grid[row][col] for col in range(self.size)], is_zeroes_first)):
self.grid[row][col] = x
def place_empty_cell(self):
for row in range(self.size-1, -1, -1):
for col in range(self.size-1, -1, -1):
if self.grid[row][col] == 0:
self.grid[row][col] = 2
return True
return False
def win(self):
return any(self.grid[row][col] == 2048 for row in range(self.size) for col in range(self.size))
def move2048(grid, move):
game = Game2048(grid)
game.calc_move(move)
if game.win():
return [['U', 'W', 'I', 'N'], ['U', 'W', 'I', 'N'], ['U', 'W', 'I', 'N'], ['U', 'W', 'I', 'N']]
elif game.place_empty_cell():
return game.grid
else:
return [['G', 'A', 'M', 'E'], ['O', 'V', 'E', 'R'], ['G', 'A', 'M', 'E'], ['O', 'V', 'E', 'R']]
July 30, 2015