【发布时间】:2020-02-17 13:20:23
【问题描述】:
我想制作俄罗斯方块游戏,我需要功能,将 tetramino 人物旋转 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
但它不适用于字符串数组并给出类型错误:
File "Tetris.py", line 85, in rotateFigure
figure[top][i] = prev
TypeError: 'str' object does not support item assignment
如何旋转字符串数组?
【问题讨论】:
-
我会创建一个包含所有旋转位置的列表,然后我就不需要这个函数了
-
"在搜索后我发现类似这样的东西" -- Python 从不 支持“'str' 对象项分配”,所以一定要搜索 Python i> 单独的代码。或者,可以想象,在此基础上编写自己的代码。
-
这段代码适用于 int 矩阵,所以我认为它适用于字符。
标签: python python-3.x matrix tetris