【发布时间】:2019-04-09 05:20:52
【问题描述】:
我正在尝试在用 python 代码显示的图表中创建精确的迷宫,但我有点打嗝。 我知道可以使用带有 1 和 0 数组的 matplotlib 来绘制它。但是还是没看懂。
有人可以帮助我并指导我吗?谢谢。
Ps:我还是 python 新手,但不管代码有多复杂,我会试着理解它。非常感谢
【问题讨论】:
标签: python matplotlib maze
我正在尝试在用 python 代码显示的图表中创建精确的迷宫,但我有点打嗝。 我知道可以使用带有 1 和 0 数组的 matplotlib 来绘制它。但是还是没看懂。
有人可以帮助我并指导我吗?谢谢。
Ps:我还是 python 新手,但不管代码有多复杂,我会试着理解它。非常感谢
【问题讨论】:
标签: python matplotlib maze
按照你的迷宫,我翻译成找到here的等效结构:
+-+-+-+-+ +-+-+-+-+-+
| | | |
+ + + +-+-+-+ +-+ + +
| | | | | | | |
+ +-+-+ +-+ + + + +-+
| | | | | | |
+ + + + + + + +-+ +-+
| | | | | |
+-+-+-+-+-+-+-+ +-+ +
| | | |
+ +-+-+-+-+ + +-+-+ +
| | | |
+ + + +-+ +-+ +-+-+-+
| | | | | |
+ +-+-+ + +-+ + +-+ +
| | | | | | | |
+-+ +-+ + + + +-+ + +
| | | | | | |
+ +-+ +-+-+-+-+ + + +
| | | | |
+-+-+-+-+-+ +-+-+-+-+
然后对代码稍作修改,使其更具可读性:
import matplotlib.pyplot as plt
maze = []
with open("maze.txt", 'r') as file:
for line in file:
line = line.rstrip()
row = []
for c in line:
if c == ' ':
row.append(1) # spaces are 1s
else:
row.append(0) # walls are 0s
maze.append(row)
plt.pcolormesh(maze)
plt.axes().set_aspect('equal') #set the x and y axes to the same scale
plt.xticks([]) # remove the tick marks by setting to an empty list
plt.yticks([]) # remove the tick marks by setting to an empty list
plt.axes().invert_yaxis() #invert the y-axis so the first row of data is at the top
plt.show()
【讨论】: