0%

python生成排序算法动画

冒泡排序

用python写了一个冒泡排序的动画

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
68
69
70
71
72
73
74
75
76
77
78
79
80
import pygame
import sys
import random
import time
#初始化pygame
pygame.init()

#设置显示的窗口尺寸
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
screen.fill((255,255,255))

array_size = 10 #数组大小
max_value = 10 #最大值
sort_array = random.sample(range(1, max_value + 1), array_size)
multiplier = screen_height / array_size

# 冒泡排序的动画部分
bubble_sorting = True # 标记是否正在排序
j,k = 0,0 # 当前迭代位置
print(sort_array)

button_show = True

def draw_button():
#定义按钮
button_weight = 100
button_height = 50
button_x = (screen_width-button_weight) / 2
button_y = (screen_height-button_height) / 2
button = pygame.Rect(button_x,button_y,button_weight,button_height)
pygame.draw.rect(screen,color=[100,100,100],rect=button)
#定义字体
font = pygame.font.SysFont(None,size=36)
text = font.render('Start',True,[255,0,0])
text_rect = text.get_rect() #获取文字尺寸
text_rect.center = (screen_width / 2,screen_height / 2)
screen.blit(text,text_rect)
return button

def draw_array(sort_array):
high = [x * multiplier for x in sort_array] #矩形高度
width = screen_width / array_size #矩形宽度
for i,value in enumerate(sort_array):
#计算矩形的x坐标
x = i * width
#计算矩形的y坐标
y = screen_height - high[i]
#绘制矩形
pygame.draw.rect(screen,(152, 251, 152), [x, y, width, high[i]])

#循环显示窗口
while True:
draw_array(sort_array)
if button_show :
button = draw_button()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 当鼠标点击窗口时执行操作
if event.type == pygame.MOUSEBUTTONDOWN:
# 获取鼠标点击位置
mouse_pos = event.pos
# 检查是否点击了按钮
if button.collidepoint(mouse_pos):
for k in range(array_size):
for j in range(0,array_size - k - 1):
if sort_array[j] > sort_array[j + 1]:
sort_array[j], sort_array[j + 1] = sort_array[j + 1], sort_array[j]
print(sort_array)
# 更新窗口显示
screen.fill((255,255,255)) # 清空屏幕
draw_array(sort_array)
pygame.display.update()
time.sleep(1)
button_show = False
pygame.display.update()

-------------本文结束感谢您的阅读-------------

欢迎关注我的其它发布渠道