python代码案例分享,python实现代码雨,动画显示,pygame使用教程
python代码案例分享,python实现代码雨,动画显示
代码实现:
# 代码雨列表
class CodeRain:def __init__(self):self.column_width = 20self.columns = WIDTH // self.column_widthself.drops = []self.texts = []self.colors = []self.speeds = []self.trail_colors = [] # 轨迹颜色for i in range(self.columns):self.drops.append(random.randint(-100, 0))self.texts.append(randomCode())self.colors.append(randomColor())self.speeds.append(randomSpeed() / 10)self.trail_colors.append((0, random.randint(100, 255), 0)) # 绿色轨迹def update(self):for i in range(self.columns):self.drops[i] += self.speeds[i]if self.drops[i] > HEIGHT:self.drops[i] = random.randint(-100, 0)self.texts[i] = randomCode()self.colors[i] = randomColor()self.speeds[i] = randomSpeed() / 10def draw(self, surface):for i in range(self.columns):if self.drops[i] > 0:# 绘制轨迹效果for j in range(10):if self.drops[i] - j * 15 > 0:trail_text = randomCode()trail_color = (0, max(0, 255 - j * 25), 0) # 渐变绿色trail_surface = font.render(trail_text, True, trail_color)surface.blit(trail_surface, (i * self.column_width, self.drops[i] - j * 15))# 绘制主字符text_surface = font.render(self.texts[i], True, self.colors[i])surface.blit(text_surface, (i * self.column_width, self.drops[i]))
定义代码精力类:
class Code(pygame.sprite.Sprite):def __init__(self):pygame.sprite.Sprite.__init__(self)self.font = pygame.font.Font('./font.ttf', randomSize()) # 随机字体大小self.speed = randomSpeed() # 随机速度self.code = self.getCode() # 随机长度self.image = self.font.render(self.code, True, randomColor()) # 使用已有的文本创建一个位图image,返回值为一个image 随机颜色self.image = pygame.transform.rotate(self.image, random.randint(87, 93)) # 讲图像随机旋转角度self.rect = self.image.get_rect()self.rect.topleft = randomPos() # 随机位置def getCode(self):length = randomLen()code = ''for i in range(length):code += randomCode()return codedef update(self):self.rect = self.rect.move(0, self.speed)if self.rect.top > HEIGHT:self.kill()
初始化pygame
pygame.init() # 初始函数,使用pygame的第一步
screen = pygame.display.set_mode((WIDTH, HEIGHT)) #生成主屏幕screen;第一个参数是屏幕大小
pygame.display.set_caption('Code Rain-居然') # 窗口命名clock = pygame.time.Clock() # 初始化一个clock对象
codesGroup = pygame.sprite.Group() # 精灵组,一个简单的实体容器
while True:clock.tick(24) # 控制游戏绘制的最大帧率为30for event in pygame.event.get():if event.type == QUIT:pygame.quit()sys.exit(0)# screen.fill((1, 1, 1)) # 填充screen.fill((0, 0, 0)) # 填充背景颜色codeobject = Code()codesGroup.add(codeobject) # 添加精灵对象codesGroup.update()codesGroup.draw(screen)pygame.display.update()
最终执行demo类
我整理了一些python代码案例源码以及教程,包含基础教程,自动化,算法,实例案例有几百个案例,python学习佳品
「python源码案例」
https://drive.uc.cn/s/f661de583ee34