本文目录导读:
这是一个Python抽奖小程序的完整案例,包含基础版本和进阶版本,你可以根据自己的需求选择使用。
基础版:简单抽奖器
import random
import time
class SimpleLottery:
def __init__(self):
self.participants = []
def add_participants(self, names):
"""添加参与者"""
self.participants.extend(names)
print(f"已添加 {len(names)} 名参与者")
def draw_winner(self):
"""抽取一名获奖者"""
if not self.participants:
print("没有参与者!")
return None
# 模拟抽奖过程
print("🎉 正在抽奖中...")
time.sleep(1)
winner = random.choice(self.participants)
print(f"✨ 恭喜 {winner} 中奖!")
return winner
def draw_multiple(self, count):
"""抽取多名获奖者"""
if not self.participants:
print("没有参与者!")
return []
if count > len(self.participants):
print(f"参与者不足!当前只有 {len(self.participants)} 人")
count = len(self.participants)
print(f"🎉 正在抽取 {count} 名获奖者...")
time.sleep(1.5)
winners = random.sample(self.participants, count)
print(f"✨ 恭喜以下 {count} 位朋友中奖!")
for i, winner in enumerate(winners, 1):
print(f" 第{i}名: {winner}")
return winners
# 使用示例
if __name__ == "__main__":
lottery = SimpleLottery()
# 添加参与者
participants = ["小明", "小红", "小华", "小李", "小张",
"小王", "小赵", "小刘", "小陈", "小周"]
lottery.add_participants(participants)
# 单次抽奖
lottery.draw_winner()
print("\n" + "="*30)
# 多次抽奖
lottery.draw_multiple(3)
进阶版:功能完整的抽奖系统
import random
import time
import json
import os
from datetime import datetime
class AdvancedLottery:
def __init__(self, save_file="lottery_data.json"):
self.participants = []
self.winners = []
self.save_file = save_file
self.load_data()
def add_participant(self, name):
"""添加单个参与者"""
if name not in self.participants:
self.participants.append(name)
print(f"✅ 已添加: {name}")
self.save_data()
else:
print(f"❌ {name} 已存在")
def add_participants_from_list(self, names):
"""从列表批量添加参与者"""
new_count = 0
for name in names:
if name not in self.participants:
self.participants.append(name)
new_count += 1
print(f"✅ 成功添加 {new_count} 名参与者")
self.save_data()
def remove_participant(self, name):
"""移除参与者"""
if name in self.participants:
self.participants.remove(name)
print(f"✅ 已移除: {name}")
self.save_data()
else:
print(f"❌ 未找到: {name}")
def show_participants(self):
"""显示所有参与者"""
if not self.participants:
print("📭 暂无参与者")
return
print(f"📋 当前参与者 ({len(self.participants)}人):")
for i, name in enumerate(self.participants, 1):
print(f" {i}. {name}")
def draw_winner(self, prize_name="奖品"):
"""抽取获奖者"""
if not self.participants:
print("❌ 没有参与者!")
return None
# 排除已中奖者
available = [p for p in self.participants if p not in self.winners]
if not available:
print("❌ 所有参与者都已中奖!")
return None
print(f"\n🎯 正在抽取[{prize_name}]的获奖者...")
# 滚动效果
for _ in range(3):
temp_winner = random.choice(available)
print(f"\r✨ 中奖者是: {temp_winner}", end="")
time.sleep(1)
winner = random.choice(available)
print(f"\n🎉 恭喜 {winner} 获得 [{prize_name}]!")
# 记录中奖信息
self.winners.append(winner)
self.save_data()
return winner
def draw_multiple_winners(self, count, prize_names=None):
"""抽取多名获奖者"""
if not self.participants:
print("❌ 没有参与者!")
return []
available = [p for p in self.participants if p not in self.winners]
if len(available) < count:
print(f"❌ 可用参与者不足,当前剩余 {len(available)} 人")
count = len(available)
if prize_names is None:
prize_names = [f"奖品{i+1}" for i in range(count)]
elif len(prize_names) < count:
prize_names.extend([f"奖品{i+1}" for i in range(len(prize_names), count)])
winners = []
for i in range(count):
winner = self.draw_winner(prize_names[i])
if winner:
winners.append(winner)
return winners
def reset_lottery(self):
"""重置抽奖记录"""
confirm = input("确定要重置所有抽奖记录吗?(y/n): ")
if confirm.lower() == 'y':
self.winners = []
self.save_data()
print("✅ 已重置所有抽奖记录")
def show_winners(self):
"""显示所有获奖者"""
if not self.winners:
print("📭 暂无获奖记录")
return
print(f"🏆 获奖记录 ({len(self.winners)}人):")
for i, name in enumerate(self.winners, 1):
print(f" {i}. {name}")
def save_data(self):
"""保存数据到文件"""
data = {
"participants": self.participants,
"winners": self.winners,
"last_update": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
try:
with open(self.save_file, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"⚠️ 保存数据失败: {e}")
def load_data(self):
"""从文件加载数据"""
if os.path.exists(self.save_file):
try:
with open(self.save_file, 'r', encoding='utf-8') as f:
data = json.load(f)
self.participants = data.get("participants", [])
self.winners = data.get("winners", [])
print(f"📂 已加载 {len(self.participants)} 名参与者,{len(self.winners)} 条获奖记录")
except Exception as e:
print(f"⚠️ 加载数据失败: {e}")
# 交互式菜单
def main():
lottery = AdvancedLottery()
while True:
print("\n" + "="*40)
print("🎯 抽奖系统菜单")
print("="*40)
print("1. 添加参与者")
print("2. 批量添加参与者")
print("3. 查看参与者")
print("4. 移除参与者")
print("5. 单次抽奖")
print("6. 多人抽奖")
print("7. 查看获奖记录")
print("8. 重置抽奖")
print("9. 退出系统")
print("="*40)
choice = input("请输入选项 (1-9): ").strip()
if choice == "1":
name = input("请输入参与者姓名: ").strip()
if name:
lottery.add_participant(name)
elif choice == "2":
names_input = input("请输入参与者姓名(用逗号分隔): ").strip()
if names_input:
names = [name.strip() for name in names_input.split(",") if name.strip()]
lottery.add_participants_from_list(names)
elif choice == "3":
lottery.show_participants()
elif choice == "4":
name = input("请输入要移除的参与者姓名: ").strip()
if name:
lottery.remove_participant(name)
elif choice == "5":
prize = input("请输入奖品名称(直接回车默认为'奖品'): ").strip()
prize = prize if prize else "奖品"
lottery.draw_winner(prize)
elif choice == "6":
try:
count = int(input("请输入要抽取的人数: "))
if count > 0:
lottery.draw_multiple_winners(count)
except ValueError:
print("❌ 请输入有效的数字")
elif choice == "7":
lottery.show_winners()
elif choice == "8":
lottery.reset_lottery()
elif choice == "9":
print("👋 感谢使用抽奖系统,再见!")
break
else:
print("❌ 无效的选项,请重新选择")
if __name__ == "__main__":
main()
使用说明
基础版使用
# 快速使用基础版 lottery = SimpleLottery() lottery.add_participants(["张三", "李四", "王五"]) lottery.draw_winner() # 单次抽奖 lottery.draw_multiple(2) # 抽2名获奖者
进阶版特性
- 数据持久化:自动保存参与者信息和获奖记录
- 防重复中奖:已中奖者不会再次被抽中
- 交互式菜单:完整的命令行界面
- 批量操作:支持批量添加参与者
- 奖项命名:可以为每个奖项设置名称
- 抽奖动画:模拟滚动抽奖效果
扩展建议
你可以根据需求进一步扩展:
- GUI界面:使用tkinter或PyQt开发图形界面
- 权重抽奖:为不同参与者设置不同中奖概率
- 定时抽奖:设置定时自动抽奖
- 导出结果:将抽奖结果导出为Excel或CSV
- 多轮抽奖:支持多轮不同奖项的抽奖
- 实时显示:连接大屏幕实时显示抽奖过程
这个抽奖小程序适合年会、活动、课堂等场景使用,你可以直接运行或根据需求修改。
标签: Python编程