Skip to content

Commit 99a13d4

Browse files
committed
Added Bresenham Line Algorithm basic version for first quadrant
1 parent e2a78d4 commit 99a13d4

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

graphics/bresenham_line_basic.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
"""
2+
Classic Bresenham's Line Drawing Algorithm
3+
------------------------------------------
4+
5+
Draws a line between two points (x1, y1) and (x2, y2)
6+
for slope 0 ≤ m ≤ 1, without floating-point operations.
7+
8+
Reference : https://www.geeksforgeeks.org/dsa/bresenhams-line-generation-algorithm/
9+
10+
>>> classic_bresenham_line((0, 0), (5, 3))
11+
[(0, 0), (1, 1), (2, 1), (3, 2), (4, 2), (5, 3)]
12+
"""
13+
14+
import matplotlib.pyplot as plt
15+
16+
17+
def classic_bresenham_line(
18+
p1: tuple[int, int], p2: tuple[int, int]
19+
) -> list[tuple[int, int]]:
20+
x1, y1 = p1
21+
x2, y2 = p2
22+
23+
dx = x2 - x1
24+
dy = y2 - y1
25+
p = 2 * dy - dx
26+
y = y1
27+
points = []
28+
29+
for x in range(x1, x2 + 1):
30+
points.append((x, y))
31+
if p < 0:
32+
p += 2 * dy
33+
else:
34+
y += 1
35+
p += 2 * (dy - dx)
36+
return points
37+
38+
39+
if __name__ == "__main__":
40+
import doctest
41+
42+
doctest.testmod()
43+
44+
x1 = int(input("Enter x1: "))
45+
y1 = int(input("Enter y1: "))
46+
x2 = int(input("Enter x2: "))
47+
y2 = int(input("Enter y2: "))
48+
49+
points = classic_bresenham_line((x1, y1), (x2, y2))
50+
print("Generated points:", points)
51+
52+
xs, ys = zip(*points)
53+
plt.plot(xs, ys, marker="o")
54+
plt.title("Classic Bresenham's Line Algorithm")
55+
plt.grid()
56+
plt.show()

0 commit comments

Comments
 (0)