Merge2048

"""
Clone of 2048 game.
"""

import poc_2048_gui
import random
# Directions, DO NOT MODIFY
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4

# Offsets for computing tile indices in each direction.
# DO NOT MODIFY this dictionary.
OFFSETS = {UP: (1, 0),
           DOWN: (-1, 0),
           LEFT: (0, 1),
           RIGHT: (0, -1)}

def merge(line):
    """
    Helper function that merges a single row or column in 2048
    """
    new_list = list(line)
    for dummy_item in new_list:
        if dummy_item == 0:
            new_list.append(new_list.pop(new_list.index(dummy_item)))

    for dummy_num in range(len(new_list)):
        if (dummy_num + 1) <= (len(new_list) - 1):
            if new_list[dummy_num] == new_list[dummy_num + 1]:
                new_list[dummy_num] *= 2
                new_list.pop(dummy_num + 1)
                new_list.append(0)
                
    return new_list

class TwentyFortyEight:
    """
    Class to run the game logic.
    """

    def __init__(self, grid_height, grid_width):
        
        self._row_ = grid_height
        self._col_ = grid_width
        self._grid_ = []
        self._gamestart_ = False
        self.reset()
        
        self._upmove_ = {UP:[(0, dummy_col) for dummy_col in range(self._col_)]}
        self._downmove_ = {DOWN:[(self._row_ - 1, dummy_col) for dummy_col in range(self._col_)]}
        self._leftmove_ = {LEFT: [(dummy_col, 0) for dummy_col in range(self._row_)]}
        self._rightmove_ = {RIGHT:[(dummy_col, self._col_ - 1) for dummy_col in range(self._row_)]}

    def reset(self):
        """
        Reset the game so the grid is empty except for two
        initial tiles.
        """
        self._gamestart_ = True
        self._grid_ = [[0 for dummy_col in range(self._col_)] for dummy_raw in range(self._row_)]
        self.new_tile()

    def __str__(self):
        """
        Return a string representation of the grid for debugging.
        """
        grid_string = ""
        for dummy_index in range(len(self._grid_)):
            grid_string += str(self._grid_[dummy_index]).strip("[]") + "\n"

        return grid_string

    def get_grid_height(self):
        """
        Get the height of the board.
        """
        return self._row_

    def get_grid_width(self):
        """
        Get the width of the board.
        """
        # replace with your code
        return self._col_

    def move(self, direction):
        """
        Move all tiles in the given direction and add
        a new tile if any tiles moved.
        """
        if direction == UP:
            change = 0
            offset = OFFSETS[UP]
            for dummy_index in self._upmove_[UP]:
                temp_list = []
                for dummy_row in range(self._row_):
                    temp_list.append(self._grid_[dummy_index[0] + (dummy_row * offset[0])]\
                                     [dummy_index[1] + (dummy_row * offset[1])]) 
                    
                merged_val = merge(temp_list)
                for dummy_val in range(len(merged_val)):
                    self._grid_[dummy_val][dummy_index[1]] = merged_val[dummy_val]
                    
                if temp_list != merged_val:
                    change += 1
            if change > 0:
                self.new_tile()
                    
        elif direction == DOWN:
            change = 0
            offset = OFFSETS[DOWN]
            for dummy_index in self._downmove_[DOWN]:
                temp_list = []
                for dummy_row in range(self._row_):
                    temp_list.append(self._grid_[dummy_index[0] + (dummy_row * offset[0])]\
                                     [dummy_index[1] + (dummy_row * offset[1])])
                    
                merged_val = merge(temp_list)
                for dummy_val in range(len(merged_val)):
                    self._grid_[(len(merged_val) - 1) - dummy_val][dummy_index[1]] = merged_val[dummy_val]
                    
                if temp_list != merged_val:
                    change += 1
            if change > 0:
                self.new_tile()
                
        elif direction == LEFT:
            change = 0
            offsets = OFFSETS[LEFT]
            for dummy_list in self._leftmove_[LEFT]:
                temp_list = []
                for dummy_col in range(self._col_):
                    temp_list.append(self._grid_[dummy_list[0] + (dummy_col * offsets[0])]\
                                     [dummy_list[1] + (dummy_col * offsets[1])])
                    
                merged_val = merge(temp_list)
                for dummy_val in range(len(merged_val)):
                    self._grid_[dummy_list[0]][dummy_val] = merged_val[dummy_val]
                    
                if temp_list != merged_val:
                    change += 1
            if change > 0:
                self.new_tile()
                
        elif direction == RIGHT:
            change = 0
            offsets = OFFSETS[RIGHT]
            for dummy_list in self._rightmove_[RIGHT]:
                temp_list = []
                for dummy_col in range(self._col_):
                    temp_list.append(self._grid_[dummy_list[0] + (dummy_col * offsets[0])]
                                     [dummy_list[1] + (dummy_col * offsets[1])])
                    
                merged_val = merge(temp_list)
                for dummy_val in range(len(merged_val)):
                    self._grid_[dummy_list[0]][self._col_ - 1 - dummy_val] = merged_val[dummy_val]
                    
                if temp_list != merged_val:
                    change += 1
            if change > 0:
                self.new_tile()

    def new_tile(self):
        """
        Create a new tile in a randomly selected empty
        square.  The tile should be 2 90% of the time and
        4 10% of the time.
        """
        tile_choice = [2, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 2]
        zeros = []
        for dummy_row in range(self._row_):
            for dummy_col in range(self._col_):
                if self._grid_[dummy_row][dummy_col] == 0:
                    zeros.append((dummy_row, dummy_col)) 
                    
        random.shuffle(zeros)
        if len(zeros) > 0:
            if self._gamestart_:
                for dummy_index in range(2):
                    random.shuffle(tile_choice)
                    self._grid_[zeros[dummy_index][0]][zeros[dummy_index][1]] = tile_choice[0]
                self._gamestart_ = False
            else:
                for dummy_index in range(1):
                    random.shuffle(tile_choice)
                    self._grid_[zeros[dummy_index][0]][zeros[dummy_index][1]] = tile_choice[0]   

    def set_tile(self, row, col, value):
        """
        Set the tile at position row, col to have the given value.
        """
        self._grid_[row][col] = value

    def get_tile(self, row, col):
        """
        Return the value of the tile at position row, col.
        """
        return (self._grid_[row][col])

poc_2048_gui.run_gui(TwentyFortyEight(6, 5))
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s