# -*- coding:utf-8 -*- # 导入系统文件库 import pygame import random from pygame.locals import * from random import randint # 定义一些窗体参数及加载字体文件 SCREEN_WIDTH = 900 # 窗体宽度 SCREEN_HEIGHT = 600 # 窗体宽度 LOW_SPEED = 4 # 字体移动最低速度 HIGH_SPEED = 20 # 字体移动最快速度 FONT_COLOR = (10, 150, 200) # 字体颜色 FONT_SIZE = 15 # 字体尺寸 FONT_NOM = 20 # 显示字体数量 从0开始 FONT_NAME = "calibrii.ttf" # 注意字体的文件名必须与真实文件完全相同(注意ttf的大小写),且文件名不能是中文 FREQUENCE = 10 # 时间频度 times = 0 # 初始化时间 # 定义随机参数 # 随机下降速度 def randomspeed(): return randint(LOW_SPEED, HIGH_SPEED) def randomposition(): # 随机位置 return randint(0, SCREEN_WIDTH), randint(0, SCREEN_HEIGHT) # 随机数值 def randomvalue(): return randint(0, 100) # this is your own display number range # class of sprite 定义精灵 class Word(pygame.sprite.Sprite): def __init__(self, bornposition): pygame.sprite.Sprite.__init__(self) self.value = randomvalue()# 精灵数值 self.font = pygame.font.Font(None, FONT_SIZE)# 精灵字体 self.image = self.font.render(str(self.value), True, FONT_COLOR)# 精灵外观 self.speed = randomspeed()# 精灵速度 self.rect = self.image.get_rect()# 精灵大小 self.rect.topleft = bornposition# 精灵位置 def update(self):# updata pygame内部方法 self.rect = self.rect.move(0, self.speed) if self.rect.top > SCREEN_HEIGHT: self.kill()# kill pygame内部方法 # init the available modules pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("ViatorSun CodeRain") clock = pygame.time.Clock() group = pygame.sprite.Group() group_count = int(SCREEN_WIDTH / FONT_NOM) # mainloop while True: time = clock.tick(FREQUENCE) for event in pygame.event.get(): if event.type == QUIT: import mouse pygame.quit() exit() screen.fill((0, 0, 0)) for i in range(0, group_count): group.add(Word((i * FONT_NOM, -FONT_NOM))) group.update() group.draw(screen) pygame.display.update() 截图: