[Python] 纯文本查看 复制代码
import pygame
import random
import sys
import time
# 初始化 Pygame
pygame.init()
# 设置屏幕宽高和标题
WIDTH, HEIGHT = 600, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("幸运抽奖机")
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (231, 76, 60)
YELLOW = (241, 196, 15)
BLUE = (52, 152, 219)
GREEN = (46, 204, 113)
# 加载支持中文的字体文件(确保字体文件与代码在同一目录下)
font_path = "C:\Windows\Fonts\simsun.ttc" # 替换为中文字体文件路径,如微软雅黑或黑体
font_large = pygame.font.Font(font_path, 80)
font_medium = pygame.font.Font(font_path, 50)
font_small = pygame.font.Font(font_path, 30)
# 名单
participants = ["张三", "李四", "王五", "赵六", "孙七", "周八", "吴九", "郑十"]
current_name = ""
# 动画控制
rolling = False
winner = None
start_time = None
duration = 3 # 持续时间(秒)
def draw_text(text, font, color, x, y, center=True):
"""绘制文字"""
surface = font.render(text, True, color)
rect = surface.get_rect()
if center:
rect.center = (x, y)
else:
rect.topleft = (x, y)
screen.blit(surface, rect)
def main():
global rolling, current_name, winner, start_time
clock = pygame.time.Clock()
running = True
while running:
screen.fill(WHITE)
# 标题
draw_text("幸运抽奖机", font_large, BLUE, WIDTH // 2, 50)
# 显示滚动的名字或最终中奖者
if rolling:
draw_text(current_name, font_medium,
BLACK, WIDTH // 2, HEIGHT // 2)
elif winner:
draw_text(f"🎉 恭喜 {winner} 🎉", font_large,
YELLOW, WIDTH // 2, HEIGHT // 2)
# 提示信息
draw_text("按空格键开始抽奖", font_small, GREEN, WIDTH // 2, HEIGHT - 50)
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and not rolling:
rolling = True
winner = None
start_time = time.time()
# 抽奖逻辑
if rolling:
current_name = random.choice(participants) # 随机选择一个名字
# 检查是否停止滚动
elapsed_time = time.time() - start_time
if elapsed_time > duration:
rolling = False
winner = random.choice(participants) # 最终随机选择一个名字
# 更新屏幕
pygame.display.flip()
clock.tick(30)
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()