python代码案例分享,python实现代码雨,动画显示

代码实现:
python
# 代码雨列表
class CodeRain:
def __init__(self):
self.column_width = 20
self.columns = WIDTH // self.column_width
self.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() / 10
def 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]))
定义代码精力类:
python
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 code
def update(self):
self.rect = self.rect.move(0, self.speed)
if self.rect.top > HEIGHT:
self.kill()
初始化pygame
python
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) # 控制游戏绘制的最大帧率为30
for 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源码案例」