Skip to content

Commit 5e3b031

Browse files
committed
Add midpoint Line Drawing Algorithm
1 parent 71ad663 commit 5e3b031

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

graphics/midpoint_line.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
"""
2+
Midpoint Line Drawing Algorithm
3+
-------------------------------
4+
5+
Handles all lines with arbitrary slopes using the midpoint method.
6+
7+
Referece:
8+
https://www.geeksforgeeks.org/dsa/mid-point-line-generation-algorithm/
9+
10+
>>> midpoint_line((0, 0), (5, 3))
11+
[(0, 0), (1, 1), (2, 1), (3, 2), (4, 2), (5, 3)]
12+
>>> midpoint_line((5, 5), (2, 3))
13+
[(5, 5), (4, 4), (3, 4), (2, 3)]
14+
"""
15+
16+
import matplotlib.pyplot as plt
17+
18+
19+
def midpoint_line(p1: tuple[int, int], p2: tuple[int, int]) -> list[tuple[int, int]]:
20+
x1, y1 = p1
21+
x2, y2 = p2
22+
23+
points = []
24+
25+
dx = x2 - x1
26+
dy = y2 - y1
27+
28+
# Determine the direction of the step
29+
sx = 1 if dx >= 0 else -1
30+
sy = 1 if dy >= 0 else -1
31+
32+
dx = abs(dx)
33+
dy = abs(dy)
34+
35+
if dx > dy:
36+
# Shallow slope: iterate over x
37+
d = dy - dx / 2
38+
x, y = x1, y1
39+
while x != x2 + sx:
40+
points.append((x, y))
41+
if d >= 0:
42+
y += sy
43+
d -= dx
44+
x += sx
45+
d += dy
46+
else:
47+
# Steep slope: iterate over y
48+
d = dx - dy / 2
49+
x, y = x1, y1
50+
while y != y2 + sy:
51+
points.append((x, y))
52+
if d >= 0:
53+
x += sx
54+
d -= dy
55+
y += sy
56+
d += dx
57+
58+
return points
59+
60+
61+
if __name__ == "__main__":
62+
import doctest
63+
64+
doctest.testmod()
65+
66+
x1 = int(input("Enter x1: "))
67+
y1 = int(input("Enter y1: "))
68+
x2 = int(input("Enter x2: "))
69+
y2 = int(input("Enter y2: "))
70+
71+
points = midpoint_line((x1, y1), (x2, y2))
72+
print("Generated points:", points)
73+
74+
xs, ys = zip(*points)
75+
plt.plot(xs, ys, marker="o")
76+
plt.title("Midpoint Line Drawing Algorithm")
77+
plt.grid()
78+
plt.show()

0 commit comments

Comments
 (0)