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.
http://www.astrolog.org/labyrnth/algrithm.htm
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
Perhaps it's an overkill but I'd just find the line equation and use a generator expression. To find the equation you can use this example algorithm which will return something like
lambda x: 2*x +1
With that we can do:
f = find_line_equation(A, B) #A B are tuples
points = [(x, f(x)) for x in range(min(A[0], B[0]), max(A[0], B[0]))]
This is assuming you want only integer points. You can also use this loop:
points = []
x = min(A[0], B[0])
increment = 0.1
while x <= max(A[0], B[0]):
points.append((x, f(x))
x += increment
来源:https://stackoverflow.com/questions/23930274/list-of-coordinates-between-irregular-points-in-python