Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 36 additions & 35 deletions graphics/digital_differential_analyzer_line.py
Original file line number Diff line number Diff line change
@@ -1,52 +1,53 @@
import matplotlib.pyplot as plt


def digital_differential_analyzer_line(
p1: tuple[int, int], p2: tuple[int, int]
) -> list[tuple[int, int]]:
"""
Draws a line between two points using the DDA algorithm.
Draw a line between two points using the Digital Differential Analyzer (DDA)
algorithm.

The DDA algorithm increments the dominant axis in unit steps and updates the
other axis proportionally. After each step coordinates are rounded to the
nearest integer to obtain pixel coordinates.

Args:
- p1: Coordinates of the starting point.
- p2: Coordinates of the ending point.
p1: Starting coordinate (x1, y1).
p2: Ending coordinate (x2, y2).

Returns:
- List of coordinate points that form the line.
A list of integer coordinate tuples representing the rasterized line.
The list includes the end point and excludes the start point.

Examples:
>>> digital_differential_analyzer_line((1, 1), (4, 4))
[(2, 2), (3, 3), (4, 4)]

>>> digital_differential_analyzer_line((0, 0), (0, 5))
[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]

>>> digital_differential_analyzer_line((5, 5), (2, 5))
[(4, 5), (3, 5), (2, 5)]

>>> digital_differential_analyzer_line((3, 3), (3, 3))
[(3, 3)]
"""
x1, y1 = p1
x2, y2 = p2
dx = x2 - x1
dy = y2 - y1

steps = max(abs(dx), abs(dy))
x_increment = dx / float(steps)
y_increment = dy / float(steps)
coordinates = []
x: float = x1
y: float = y1
if steps == 0:
return [p1]

x_inc = dx / float(steps)
y_inc = dy / float(steps)

x, y = float(x1), float(y1)
points: list[tuple[int, int]] = []

for _ in range(steps):
x += x_increment
y += y_increment
coordinates.append((round(x), round(y)))
return coordinates


if __name__ == "__main__":
import doctest

doctest.testmod()

x1 = int(input("Enter the x-coordinate of the starting point: "))
y1 = int(input("Enter the y-coordinate of the starting point: "))
x2 = int(input("Enter the x-coordinate of the ending point: "))
y2 = int(input("Enter the y-coordinate of the ending point: "))
coordinates = digital_differential_analyzer_line((x1, y1), (x2, y2))
x_points, y_points = zip(*coordinates)
plt.plot(x_points, y_points, marker="o")
plt.title("Digital Differential Analyzer Line Drawing Algorithm")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid()
plt.show()
x += x_inc
y += y_inc
points.append((round(x), round(y)))

return points