# 引入必要的库
import pygame
import random
import time
# 定义颜色列表 RGB格式
color_list = [(255,0,0),(255,128,0),(255,255,0),(0,255,0),(0,255,255),(0,0,255),(255,0,255)]
# 定义绘制图形并填充颜色的函数
def draw_rect(screen,color,pos,size):
rect_info = [pos[0],pos[1],size,size]
pygame.draw.rect(screen,color,rect_info)
if __name__ == '__main__':
# 初始化部分
pygame.init()
# 创建窗口
width, height = 600, 600
screen = pygame.display.set_mode((width, height))
# 设置窗口标题
pygame.display.set_caption("Colorful Dynamic Rectangle")
# 主循环
while True:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
# 随机生成颜色和位置
color = random.choice(color_list)
pos = (random.randint(0,width-50),random.randint(0,height-50))
# 清屏操作
screen.fill((255,255,255))
# 绘制图形
draw_rect(screen,color,pos,50)
# 刷新屏幕
pygame.display.flip()
# 程序暂停,等待0.1s
time.sleep(0.1)
color_list = [(255,0,0,50),(255,128,0,50),(255,255,0,50),(0,255,0,50),(0,255,255,50),(0,0,255,50),(255,0,255,50)]
# 添加控制淡入淡出速度的变量
step = 5
# 定义绘制图形并填充颜色的函数
def draw_rect(screen,color,pos,size):
rect_info = [pos[0],pos[1],size,size]
# 颜色渐变过程
for i in range(0,step):
new_color = (color[0]+(i*(color[0]-color_list[color_idx+1][0])/step),
color[1]+(i*(color[1]-color_list[color_idx+1][1])/step),
color[2]+(i*(color[2]-color_list[color_idx+1][2])/step),
color[3]+(i*(color[3]-color_list[color_idx+1][3])/step))
pygame.draw.rect(screen,new_color,rect_info)
pygame.display.flip()
time.sleep(0.02)
pygame.draw.rect(screen,color,rect_info)
标签: 手机流量卡