我正在使用 视线 算法来解决 路径规划 问题,此处检查其工作,但如下图所示,视线检查给出了错误的结果。 黑色方块 是通过视线检查的路径,功能还应该检查(1,1)上的方块,但不。我该如何解决这些错误?
python代码
import numpy as np
import matplotlib.pyplot as plt
grid = [[0,0,0,0,0,0,0,0],
[0,1,1,0,0,1,1,0],
[0,0,0,0,0,0,0,0],
[0,1,1,0,0,1,1,0],
[0,0,0,0,0,0,0,0]]
start, goal = (0,0), (3,2)
def lineOfSight(p, s):
x0 = p[0]
y0 = p[1]
x1 = s[0]
y1 = s[1]
dy = y1 - y0
dx = x1 - x0
f = 0
if dy < 0:
dy = -dy
sy = -1
else:
sy = 1
if dx < 0:
dx = -dx
sx = -1
else:
sx = 1
result = []
if dx >= dy:
while x0 != x1:
f = f + dy
i1 = x0 + int((sx-1)/2)
i2 = y0 + int((sy-1)/2)
if f >= dx:
result.append((i1,i2))
y0 = y0 + sy
f = f - dx
if f != 0:
result.append((i1,i2))
if dy == 0:
result.append((i1, y0))
result.append((i1, y0-1))
x0 = x0 + sx
else:
while y0 != y1:
f = f + dx
i1 = x0 + int((sx-1)/2)
i2 = y0 + int((sy-1)/2)
if f >= dy:
result.append((i1, i2))
x0 = x0 + sx
f = f - dy
if f != 0:
print((i1, i2))
if dx == 0:
result.append((x0, i2))
result.append((x0-1, i2))
y0 = y0 + sy
return result
check = lineOfSight(start,goal)
def getSquare(point):
x = [point[1], point[1]+1]
y0 = [-point[0], -point[0]]
y1 = [-(point[0]+1), -(point[0]+1)]
return (x,y0,y1)
checked = []
for xy in check:
checked.append(getSquare(xy))
plt.plot(start[1], -start[0], 'sb', label="Start Point")
plt.plot(goal[1], -goal[0], 'sg', label="Goal Point")
maxRow = len(grid)
maxCol = len(grid[0])
listRow = [-i for i in range(maxRow+1)]
listCol = [i for i in range(maxCol+1)]
xHorizontal, yHorizontal = np.meshgrid(listCol, [[0],[-maxRow]])
yVertical, xVertical = np.meshgrid(listRow, [[0],[maxCol]])
plt.plot(xHorizontal, yHorizontal, color='black')
plt.plot(xVertical, yVertical, color='black')
for square in checked:
x, y0, y1 = square
plt.fill_between(x,y0,y1, color='black')
plt.plot([start[1], goal[1]], [-start[0], -goal[0]], '-g')
plt.axis('equal')
plt.show()