|
| 1 | +import matplotlib.pyplot as plt |
| 2 | + |
| 3 | + |
| 4 | +def digital_differential_analyzer_line( |
| 5 | + p1: tuple[int, int], p2: tuple[int, int] |
| 6 | +) -> list[tuple[int, int]]: |
| 7 | + """ |
| 8 | + Draws a line between two points using the DDA algorithm. |
| 9 | +
|
| 10 | + Args: |
| 11 | + - p1: Coordinates of the starting point. |
| 12 | + - p2: Coordinates of the ending point. |
| 13 | + Returns: |
| 14 | + - List of coordinate points that form the line. |
| 15 | +
|
| 16 | + >>> digital_differential_analyzer_line((1, 1), (4, 4)) |
| 17 | + [(2, 2), (3, 3), (4, 4)] |
| 18 | + """ |
| 19 | + x1, y1 = p1 |
| 20 | + x2, y2 = p2 |
| 21 | + dx = x2 - x1 |
| 22 | + dy = y2 - y1 |
| 23 | + steps = max(abs(dx), abs(dy)) |
| 24 | + x_increment = dx / float(steps) |
| 25 | + y_increment = dy / float(steps) |
| 26 | + coordinates = [] |
| 27 | + x: float = x1 |
| 28 | + y: float = y1 |
| 29 | + for _ in range(steps): |
| 30 | + x += x_increment |
| 31 | + y += y_increment |
| 32 | + coordinates.append((int(round(x)), int(round(y)))) |
| 33 | + return coordinates |
| 34 | + |
| 35 | + |
| 36 | +if __name__ == "__main__": |
| 37 | + import doctest |
| 38 | + |
| 39 | + doctest.testmod() |
| 40 | + |
| 41 | + x1 = int(input("Enter the x-coordinate of the starting point: ")) |
| 42 | + y1 = int(input("Enter the y-coordinate of the starting point: ")) |
| 43 | + x2 = int(input("Enter the x-coordinate of the ending point: ")) |
| 44 | + y2 = int(input("Enter the y-coordinate of the ending point: ")) |
| 45 | + coordinates = digital_differential_analyzer_line((x1, y1), (x2, y2)) |
| 46 | + x_points, y_points = zip(*coordinates) |
| 47 | + plt.plot(x_points, y_points, marker="o") |
| 48 | + plt.title("Digital Differential Analyzer Line Drawing Algorithm") |
| 49 | + plt.xlabel("X-axis") |
| 50 | + plt.ylabel("Y-axis") |
| 51 | + plt.grid() |
| 52 | + plt.show() |
0 commit comments