So I'm trying to create a text based game, and someone suggested I store map data as a multi-dimensional array I have been trying to figure out how I'd do this or how I'd even navigate through a multi dimensional array. It seems to me this would be incredibly difficult but I have to ask because I won't be able to figure it out on my own. If this question is too vague let me know what should be more specific.
问问题
806 次
2 回答
2
多维数组只不过是一个数组,其元素映射到另一个数组,通常其中每个“子数组”的大小都相等(但不严格)。
inner = [ "" ] * 10
outer = [ [].extend(inner) for x in inner ]
这将为您创建一个 10 x 10 元素的方形多维数组。
您可以通过以下方式访问这些元素:
outer[outer_index][inner_index]
只需在网格上可视化外部和内部以及索引,外部遍历 x 轴,内部遍历 y 轴。上面的数组看起来有点像这样:
"" "" "" "" "" "" "" "" "" "" 0
"" "" "" "" "" "" "" "" "" "" 1
"" "" "" "" "" "" "" "" "" "" 2
"" "" "" "" "" "" "" "" "" "" 3
"" "" "" "" "" "" "" "" "" "" 4 (inner)
"" "" "" "" "" "" "" "" "" "" 5
"" "" "" "" "" "" "" "" "" "" 6
"" "" "" "" "" "" "" "" "" "" 7
"" "" "" "" "" "" "" "" "" "" 8
"" "" "" "" "" "" "" "" "" "" 9
0 1 2 3 4 5 6 7 8 9
(outer)
如果我在元素 6 和 8 处更新 external 的值,网格将被更改:
outer[6][8] = "X" # marks the spot
"" "" "" "" "" "" "" "" "" "" 0
"" "" "" "" "" "" "" "" "" "" 1
"" "" "" "" "" "" "" "" "" "" 2
"" "" "" "" "" "" "" "" "" "" 3
"" "" "" "" "" "" "" "" "" "" 4 (inner)
"" "" "" "" "" "" "" "" "" "" 5
"" "" "" "" "" "" "" "" "" "" 6
"" "" "" "" "" "" "" "" "" "" 7
"" "" "" "" "" "" "X" "" "" "" 8
"" "" "" "" "" "" "" "" "" "" 9
0 1 2 3 4 5 6 7 8 9
(outer)
希望这可以帮助。
于 2013-07-08T16:00:03.000 回答
1
手动创建多维列表:
world_map = [['*', '*', '*', '*'],
['*', ' ', 'i', '*'],
['*', ' ', ' ', '*'],
['*', '*', '*', '*']]
*
墙在哪里,i
可能是玩家。要遍历这个世界地图,请使用两个 for 循环:
for row in world_map:
for column in row:
print(column, end="")
print()
这将打印世界地图。
如果您需要向左移动玩家,您可以执行以下操作:
for row in world_map:
for i, column in enumerate(row):
if column == "i":
if i > 0 and row[i - 1] == ' ':
row[i - 1] = 'i'
row[i] = ' '
world_map[row][column]
如果您知道元素的位置,也可以直接访问元素。
你将不得不自己做剩下的事情。此外,这可能不是最好的方法,您应该使用播放器类等,但这对初学者来说很好:)
于 2013-07-08T15:54:20.710 回答