- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualizer.py
More file actions
Latest commit
52 lines (47 loc) · 1.87 KB
/
Copy pathvisualizer.py
File metadata and controls
52 lines (47 loc) · 1.87 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
importmath
fromtimeimportsleep
importpygame
fromnumpyimportsort
frompygameimportdisplay
fromisSortedimportis_sorted
classVisualizer:
name=""
array= []
def__init__(self, algorithm):
self.array=algorithm.arr
self.name=algorithm.name
pygame.init()
self.window_width=self.calculate_window_width(len(self.array))
self.window_height=600
self.screen=display.set_mode((self.window_width, self.window_height))
defcalculate_window_width(self, length):
min_width=800
max_width=1200
width=max(min_width, min(max_width, (max_width//length) *length))
returnwidth
defupdate(self, swap1=None, swap2=None, arr=None):
ifarrisnotNone:
self.array=arr
background_color= (255, 255, 255)
default_bar_color= (0, 0, 0)
sorted_color= (0, 255, 0)
highlight_color= (255, 0, 0)
outline_color= (0, 0, 0)
self.screen.fill(background_color)
pygame.display.set_caption(f"Algorithm: {self.name}")
bar_width=self.window_width//len(self.array)
max_value=max(self.array)
fori, valueinenumerate(self.array):
color=default_bar_color
ifswap1==iorswap2==i:
color=highlight_color
ifis_sorted(self.array):
swap1=None
swap2=None
color=sorted_color
bar_height= (value/max_value) *self.window_height
pygame.draw.rect(self.screen, color, (i*bar_width, self.window_height-bar_height, bar_width, bar_height))
ifcolor==sorted_color:
pygame.draw.rect(self.screen, outline_color,
(i*bar_width, self.window_height-bar_height, bar_width, bar_height), 1)
pygame.display.update()