所以我正在尝试创建一个基于文本的游戏,有人建议我将地图数据存储为多维数组,我一直试图弄清楚我是如何做到的,或者我是如何导航的多维数组。在我看来,这将是非常困难,但我不得不问,因为我无法自己解决这个问题。如果这个问题太模糊,请告诉我应该更具体的问题。
答案 0 :(得分: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的外部值,则网格将被更改:
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)
希望这有帮助。
答案 1 :(得分: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]
直接访问元素。
你必须自己完成剩下的工作。 此外,这可能不是最好的方法,你应该使用类播放器等,但这适用于初学者:)