1 import pygame, sys, random 2 from pygame.color import THECOLORS 3 4 pygame.init() 5 screen = pygame.display.set_mode([640, 480])#显示对象 6 #[640, 480]是窗口大小,单位像素 7 screen.fill([255, 255, 255])#用白色填充窗口背景 8 9 for i in range(100): 10 width = random.randint(0, 250);height = random.randint(0, 100) 11 top = random.randint(0, 400);left = random.randint(0, 500) 12 color_name = random.choice(list(THECOLORS.keys())) 13 #这个原教材上没有转化成列表形式,所以有错误 14 color = THECOLORS[color_name] 15 line_width = random.randint(1, 3) 16 pygame.draw.rect(screen, color, [left, top, width, height], line_width) 17 18 pygame.display.flip() 19 running = True 20 while running: 21 for event in pygame.event.get(): 22 if event.type == pygame.QUIT: 23 running = False 24 pygame.quit()