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 的迷宮”的輸出。從此頁面作為輸入:
希望這能為您最終嘗試開發的程序提供一個起點。
添加回答
舉報