python 中的字符矩阵旋转

Characters matrix rotation in python

我想制作俄罗斯方块游戏,我需要功能,将俄罗斯方块旋转 90 度。 tetramino 图是字符串数组 4x4:

figure  = [
    "..#.",
    "..#.",
    "..#.",
    "..#."
];
figure = rotateFigure(figure);

搜索后我发现了这样的东西:

def rotateFigure(figure): 

    if not len(figure): 
        return      
    """ 
        top : starting row index 
        bottom : ending row index 
        left : starting column index 
        right : ending column index 
    """
    top = 0
    bottom = len(figure)-1

    left = 0
    right = len(figure[0])-1

    while left < right and top < bottom: 
        # Store the first element of next row, 
        # this element will replace first element of 
        # current row 
        prev = figure[top+1][left] 

        # Move elements of top row one step right 
        for i in range(left, right+1): 
            curr = figure[top][i] 
            figure[top][i] = prev 
            prev = curr 

        top += 1

        # Move elements of rightmost column one step downwards 
        for i in range(top, bottom+1): 
            curr = figure[i][right] 
            figure[i][right] = prev 
            prev = curr 

        right -= 1

        # Move elements of bottom row one step left 
        for i in range(right, left-1, -1): 
            curr = figure[bottom][i] 
            figure[bottom][i] = prev 
            prev = curr 

        bottom -= 1

        # Move elements of leftmost column one step upwards 
        for i in range(bottom, top-1, -1): 
            curr = figure[i][left] 
            figure[i][left] = prev 
            prev = curr 

        left += 1

    return figure

但它不适用于字符串数组并给出 typeError:

File "Tetris.py", line 85, in rotateFigure
    figure[top][i] = prev
TypeError: 'str' object does not support item assignment

如何旋转字符串数组?

此解决方案利用了 zip() 可用于转置数组(列表列表)的事实:

figure = list(zip(*reversed(figure)))       # 90° clockwise
figure = list(reversed(list(zip(*figure)))) # 90° counterclockwise