import pygame
import random
# 初始化Pygame
pygame.init()
# 设置屏幕宽度和高度
width, height = 1920, 1000
screen = pygame.display.set_mode((width, height))
# 定义颜色
BLACK = (0, 0, 0)
# 定义字符宽度和高度
char_width, char_height = 20, 30
# 定义代码雨的速度
speed = 15
# 定义代码雨的数量
num_chars = int(width / char_width)
# 创建字符列表
chars = []
for _ in range(num_chars):
chars.append(chr(random.randint(33, 126)))
# 创建每个字符的位置列表
char_positions = []
for i in range(num_chars):
char_positions.append(random.randint(-height, 10))
clock = pygame.time.Clock()
# 游戏循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 清屏
screen.fill(BLACK)
# 更新字符位置
for i in range(num_chars):
char_positions[i] += speed
if char_positions[i] > height:
char_positions[i] = random.randint(-height, 10)
# 绘制字符
char = chars[i]
font = pygame.font.Font(None, char_height)
text = font.render(char, True, (100, 255, 100))
screen.blit(text, (i * char_width, char_positions[i]))
# 更新屏幕
pygame.display.flip()
# 设置帧率
clock.tick(300)
# 退出游戏
pygame.quit()
运行以上这段代码,你将看到屏幕上出现代码雨的效果。
每个字符都是随机生成的,并以给定的速度向下移动。
当一个字符移动到屏幕底部时,它将被重新放置在屏幕顶部,创建连续的代码雨效果。