python游戏2048列表中的索引

时间:2016-01-18 01:03:47

标签: python list

我正在使用codesculpter学习课程python project 2048。 我尝试4 x 45 x 5时代码正常,但4 x 5height != width时的任何其他代码都显示错误。我想我必须在__init__或其他地方搞砸了,但我无法弄明白。

有人可以给我一些建议吗?

这是我到目前为止所尝试的内容:

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
    """

    # creat output list and remove 0
    after_merge=[]
    storage = []


    for num_1 in range(len(line)):
        after_merge.append(0)
        if line[num_1] != 0 :
            storage.append(line[num_1])


    # sum number        
    for num_2 in range(len(storage)):
        if num_2+2> len(storage):
            break
        elif storage[num_2]==storage[num_2+1]:
            storage[num_2]*=2
            storage.pop(num_2+1)

    # replace 0 in after merge          
    for num in range(len(storage)):
        after_merge[num]=storage[num]

    return after_merge


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

    def __init__(self, grid_height, grid_width):
        self.grid_height = grid_height
        self.grid_width = grid_width
        self.cell=[]
        self.indices = {}
        self.indices[UP] = [[0,n] for n in range(grid_width)] 
        self.indices[LEFT] = [[n,0] for n in range(grid_height)] 
        self.indices[RIGHT] = [[n, grid_width - 1] for n in range(grid_height)]
        self.indices[DOWN] = [[grid_height - 1, n]for n in range(grid_width)]

        self.ranges = {}
        self.ranges[UP] = grid_height
        self.ranges[DOWN] = grid_height
        self.ranges[LEFT] = grid_width
        self.ranges[RIGHT] = grid_width

        #self.reset()

    def reset(self):
        """
        Reset the game so the grid is empty except for two
        initial tiles.
        """
        self.cell = [[0*(col+row) for row in range(self.grid_height)] for col in range (self.grid_width)]
        for count in range(2):
            self.new_tile()

    def __str__(self):
        """
        Return a string representation of the grid for debugging.
        """
        a_str = ""
        for row in range(self.grid_height):
            for col in range (self.grid_width):
                a_str += ( str(self.cell[row][col]) + " " )
            a_str += '\n'
        return a_str


    def get_grid_height(self):
        """
        Get the height of the board.
        """
        # replace with your code
        return self.grid_height

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

    def move(self, direction):
        """
        Move all tiles in the given direction and add
        a new tile if any tiles moved.
        """
        a_list = []
        has_moved = False
        for index in self.indices[direction]:
            for step in range(self.ranges[direction]):
                a_list.append(self.cell[index[0] + OFFSETS[direction][0] * step]
                              [index[1] + OFFSETS[direction][1] * step])
            merged_list = merge(a_list)

            if merged_list != a_list:
                for step in range(self.ranges[direction]):
                    self.cell[index[0] + OFFSETS[direction][0] * step]   \
                    [index[1] + OFFSETS[direction][1] * step] = merged_list[step]
                has_moved = True
            a_list = []

        if has_moved:
            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.
        """
        # replace with your code
        row=0
        col=0
        available_positions = []
        for row in range(self.grid_height):
            for col in range(self.grid_width):
                if self.cell[row][col] == 0:
                        available_positions.append([row, col])
        if not available_positions:
            print "There are no available positions."

        random_pos=random.choice(available_positions)
        rand_val=random.randint(1,10)
        if rand_val>=9:
            new_tile=4
        else:
            new_tile=2

        self.set_tile(random_pos[0], random_pos[1], new_tile)



    def set_tile(self, row, col, value):
        """
        Set the tile at position row, col to have the given value.
        """
        # replace with your code
        self.cell[row][col] = value

    def get_tile(self, row, col):
        """
        Return the value of the tile at position row, col.
        """
        # replace with your code
        return self.cell[row][col]



poc_2048_gui.run_gui(TwentyFortyEight(4, 4))

2 个答案:

答案 0 :(得分:0)

好的,我没有一直调试,但这是我找到的。 cell应具有维度grid_height * grid_width。正确的吗?

然而,就在这个循环之前:

for row in range(self.grid_height):
    for col in range(self.grid_width):
        print(row," ",col);
        if self.cell[row][col] == 0:
                available_positions.append([row, col])
if not available_positions:
    print "There are no available positions."

我发现细胞的大小是相反的。那是grid_width * grid_height。将这两行放在嵌套循环之前,自己查看。

print("cell size",len(self.cell)," ",len(self.cell[0]))
print("grid size",self.grid_height," ",self.grid_width)

当维度不同时,这会导致IndexErrorif self.cell[row][col] == 0:。话虽如此,你应该逐步了解如何填写网格和单元格。确保它们对应正确。

希望有所帮助!

答案 1 :(得分:0)

我做了一个快速调试,我在调用move()时得到了一个IndexError。通过浏览,您似乎期望填充self.cell,但它只会通过您的reset()函数填充。如果您的UI模块在初始化时调用reset,则可能看不到...

当row和col不是同一个数字时,会出现第二个IndexError。这(在另一个答案中提到)是因为您的2D数组表示是col *行,而不是row * col

下面是(4,6)的打印输出,它有4个COLUMN和6个ROW。您可能只需要在表示中交换两个:

[0, 0, 0, 0]
[2, 0, 2, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]

您的语法可能有所改进,但您可以启动您的单元格(根据您的使用情况进行测试......)

self.cell = [[[0] * self.grid_width] for row in xrange(self.grid_height)]

最后,我相信您可能会在new_tile中获得IndexError,因为Python列表从第0个元素开始。你想要从0到n-1:

    for row in range(self.grid_height-1):
        for col in range(self.grid_width-1):