bresenham's line algorithm

mail@pastecode.io avatar
unknown
python
7 months ago
893 B
0
Indexable
Never
def bresenham_line(x1, y1, x2, y2):
    dx = abs(x2 - x1)
    dy = abs(y2 - y1)
    slope_error = dy - dx
    x, y = x1, y1

    # Determine the direction of the line
    if x1 < x2:
        x_step = 1
    else:
        x_step = -1

    if y1 < y2:
        y_step = 1
    else:
        y_step = -1

    # Plot the initial point
    print(f"({x}, {y})")

    # Main loop
    while x != x2 or y != y2:
        # Plot the next point
        print(f"({x}, {y})")

        # Update x and y
        x += x_step

        # Update slope error
        slope_error_new = slope_error - 2 * dx

        # Check for a y-step
        if slope_error_new >= -dy:
            slope_error -= 2 * dx
            y += y_step

        slope_error += 2 * dy  # Always update slope error by 2 * dy

# Example usage
x1, y1 = 2, 3
x2, y2 = 9, 8
bresenham_line(x1, y1, x2, y2)
Leave a Comment