Modifying Bresenham's line algorithm
I'm trying to use Bresenham's line algorithm to compute Field of View on a grid. The code I'm using calculates the lines without a problem but I'm having problems getting it to always return the line running from start point to endpoint. What do I need to do so that all lines returned run from (x0,y0) to (x1,y1)
def bresenham_line(self, x0, y0, x1, y1):
steep = abs(y1 - y0) > abs(x1 - x0)
if steep:
x0, y0 = y0, x0
x1, y1 = y1, x1
if x0 > x1:
x0, x1 = x1, x0
y0, y1 = y1, y0
if y0 < y1:
ystep = 1
else:
ystep = -1
deltax = x1 - x0
deltay = abs(y1 - y0)
error = -deltax / 2
y = y0
line = []
for x in range(x0, x1 + 1):
if steep:
l开发者_高级运维ine.append((y,x))
else:
line.append((x,y))
error = error + deltay
if error > 0:
y = y + ystep
error = error - deltax
return line
Remember whether you switched x0 and x1 and then reverse the list if you did.
if x0 > x1:
x0, x1 = x1, x0
y0, y1 = y1, y0
becomes
switched = False
if x0 > x1:
switched = True
x0, x1 = x1, x0
y0, y1 = y1, y0
and at the end, just add:
if switched:
line.reverse()
精彩评论