Imagine we have two randomly selected points between 0 and 100 for both x and y.
For example:
(95,7), (35,6)
Now using the simple pygame.draw.line() function we could easily draw a line between these points without any gaps.
My question is, how could we find a list of all the coordinates in a single pixel thick line between the two points without any gaps in the line?
Secondly, is this even possible?
I am using this list of pixel for the crack maze algorithm that needs to "shoot" another pixel while regarding any blocking walls that may interfere with its path.
By irregular, I refer to points which would not generate simple straight lines.
For example, it would be easy to find all the points between:
(0,5) and (5,5)
This has already been covered in this question:
解决方案
Use Bresenham's line algorithm. You can find a simple python implementation here. Here’s a modified version of that implementation, which, given a starting and ending point, can return a list of intermediate points:
def line(x0, y0, x1, y1):
"Bresenham's line algorithm"
points_in_line = []
dx = abs(x1 - x0)
dy = abs(y1 - y0)
x, y = x0, y0
sx = -1 if x0 > x1 else 1
sy = -1 if y0 > y1 else 1
if dx > dy:
err = dx / 2.0
while x != x1:
points_in_line.append((x, y))
err -= dy
if err < 0:
y += sy
err += dx
x += sx
else:
err = dy / 2.0
while y != y1:
points_in_line.append((x, y))
err -= dx
if err < 0:
x += sx
err += dy
y += sy
points_in_line.append((x, y))
return points_in_line