Python/graphics/digital_differential_analyzer_line.py
pre-commit-ci[bot] edf7c372a9
[pre-commit.ci] pre-commit autoupdate (#12623)
* [pre-commit.ci] pre-commit autoupdate

updates:
- [github.com/astral-sh/ruff-pre-commit: v0.9.10 → v0.11.0](https://github.com/astral-sh/ruff-pre-commit/compare/v0.9.10...v0.11.0)
- [github.com/abravalheri/validate-pyproject: v0.23 → v0.24](https://github.com/abravalheri/validate-pyproject/compare/v0.23...v0.24)

* Fix ruff issues

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Christian Clauss <cclauss@me.com>
2025-03-18 09:53:49 +01:00

53 lines
1.5 KiB
Python

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.
Args:
- p1: Coordinates of the starting point.
- p2: Coordinates of the ending point.
Returns:
- List of coordinate points that form the line.
>>> digital_differential_analyzer_line((1, 1), (4, 4))
[(2, 2), (3, 3), (4, 4)]
"""
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
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()