1 回答
TA贡献1824条经验 获得超6个赞
这段代码一团糟。您将一个名为 的 JPEG 迷宫图像输入Maze到一个二维数组中并将其传递给ShowMaze(Maze)以表明您已正确读取它。但是全局ShowMaze()访问Maze并认为它的论点是从未计算过迷宫中的ShowMaze(possibleRoutes)哪个地方possibleRoutes?另外:X 和 Y 的意义Maze似乎颠倒了;迷宫的行list无缘无故地有一层额外的包裹;包含死代码;你不是把它读成 1 和 0,而是四种不同的颜色代码;绘图代码似乎没有希望。
我已经重新编写了您的代码,只需将迷宫读入列表列表,然后使用标记而不是绘图将其与乌龟一起显示,以简化和加速代码:
from turtle import Screen, Turtle
from PIL import Image
CURSOR_SIZE = 20
PIXEL_SIZE = 5
COLORS = {0: 'white', 1: 'black', 4: 'green', 5: 'red'}
def ShowMaze(maze):
height, width = len(maze), len(maze[0])
screen = Screen()
screen.setup(width * PIXEL_SIZE, height * PIXEL_SIZE)
screen.setworldcoordinates(0, height, width, 0)
turtle = Turtle('square', visible=False)
turtle.shapesize(PIXEL_SIZE / CURSOR_SIZE)
turtle.penup()
screen.tracer(False)
for y in range(height):
for x in range(width):
color = maze[y][x]
if color in COLORS:
turtle.fillcolor(COLORS[color])
else:
turtle.fillcolor("orange") # error color
turtle.stamp()
turtle.forward(1)
turtle.goto(0, turtle.ycor() + 1)
screen.tracer(True)
screen.mainloop()
image = Image.open('ExampleMazePicture.JPG') # Can be many different formats.
width, height = image.size # Get the width and height of the Maze for iterating over
pixels = image.load()
maze = []
for y in range(0, width, 4):
print("Row:", y)
row = []
for x in range(0, width, 4):
node = -1
pixel = pixels[x, y]
if pixel >= (200, 200, 200):
node = 0
elif pixel[0] > 200 and pixel[1] < 200 and pixel[2] < 200:
node = 4
print("End")
elif pixel[0] < 50 and pixel[1] > 200 and pixel[2] < 50:
node = 5
print("Start")
elif pixel <= (50, 50, 50):
node = 1
else:
print(pixel)
row.append(node)
maze.append(row)
ShowMaze(maze)
基于使用“图 1.6:Picobot 的迷宫”的输出。从此页面作为输入:
希望这能为您最终尝试开发的程序提供一个起点。
添加回答
举报