-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbresenham.py
More file actions
67 lines (48 loc) · 1.27 KB
/
bresenham.py
File metadata and controls
67 lines (48 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import pygame
import matplotlib.pyplot as plt
def bresenham(x1, y1, x2, y2):
points = []
dx = abs(x2 - x1)
dy = abs(y2 - y1)
sx = 1 if x1 < x2 else -1
sy = 1 if y1 < y2 else -1
err = dx - dy
while True:
points.append((x1, y1))
if x1 == x2 and y1 == y2:
break
e2 = 2 * err
if e2 > -dy:
err -= dy
x1 += sx
if e2 < dx:
err += dx
y1 += sy
return points
x1, y1 = 50, 100
x2, y2 = 400, 300
points = bresenham(x1, y1, x2, y2)
pygame.init()
screen = pygame.display.set_mode((500, 400))
pygame.display.set_caption("Bresenham Line - Pygame")
running = True
while running:
screen.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Draw pixels
for x, y in points:
screen.set_at((x, y), (255, 0, 0))
pygame.display.flip()
pygame.quit()
x_vals = [p[0] for p in points]
y_vals = [p[1] for p in points]
plt.figure()
plt.plot(x_vals, y_vals, 'ro')
plt.title("Bresenham Line - Matplotlib")
plt.xlabel("X")
plt.ylabel("Y")
plt.gca().invert_yaxis() # match screen coordinates
plt.grid(True)
plt.show()