1 ''' 2 1. 在猜年龄的基础上编写登录、注册方法,并且把猜年龄游戏分函数处理,如 3 2. 登录函数 4 3. 注册函数 5 4. 猜年龄函数 6 5. 选择奖品函数 7 ''' 8 import json 9 real_age = 18 10 prize_list = ['好迪洗发水', '绿箭侠', '小猪佩奇', '布娃娃', '再来一次!'] 11 import random 12 user_prize_dict = {} 13 import os 14 15 def register(): 16 while True: 17 username = input('输入用户名>>>(q退出):').strip().lower() 18 if username=='q':break 19 password = input('请输入密码>>>:').strip() 20 re_password = input('请再次确认密码>>>:').strip() 21 if not password == re_password: 22 print('密码不一致,请重输!') 23 continue 24 user_dic = {'name': username, 'password': password} 25 json_user_dic = json.dumps(user_dic) 26 with open(f"{username}.txt", 'w', encoding='utf-8')as f: 27 f.write(json_user_dic) 28 f.flush() 29 print('注册成功!') 30 break 31 32 def login(): 33 count = 0 34 while True: 35 if count == 3: 36 print('错误输入次数过多!') 37 break 38 username = input('请输入用户名>>>:').strip() 39 if not os.path.exists(username + '.txt'): 40 print('该用户不存在!') 41 continue 42 password = input('请输入密码>>>:').strip() 43 with open(f"{username}.txt", 'r', encoding='utf-8') as f: 44 user_json_dic = f.read() 45 user_dic = json.loads(user_json_dic) 46 if username == user_dic['name'] and password == user_dic['password']: 47 print('登录成功!') 48 guess_age() 49 break 50 else: 51 print('用户名或密码错误!') 52 count += 1 53 54 def guess_age(): 55 count = 0 56 print('现在进入猜年龄游戏环节.......\n') 57 while True: 58 count += 1 59 if count == 4: 60 print('抱歉!你三次都猜错了!') 61 again_guess_age = input('请问是否要继续猜3次(y继续,n退出)>>>:').strip().lower() 62 if again_guess_age == 'y': 63 count = 0 64 continue 65 break 66 age = input('请输入你的年龄>>>:').strip() 67 if not age.isdigit(): 68 print('请输入纯数字!') 69 continue 70 71 age = int(age) 72 if age > real_age: 73 print('猜大了!') 74 continue 75 elif age < real_age: 76 print('猜小了!') 77 continue 78 else: 79 print('恭喜你!猜对了!\n') 80 choice_prize() 81 break 82 83 def choice_prize(): 84 count = 1 85 print('进入抽奖环节.....,您共有两次机会!\n') 86 while True: 87 for index, prize in enumerate(prize_list, 1): 88 print(index, prize) 89 choice = input('请按下按钮y随机选择奖品>>>:').strip().lower() 90 if not choice == 'y': 91 print('非法输入!') 92 continue 93 prize_choice = random.randint(1, 15) 94 if prize_choice in [6, 7, 8]: 95 prize_choice = 4 96 elif prize_choice in [9, 10, 11, 12, 13, 14, 15]: 97 prize_choice = 5 98 prize = prize_list[prize_choice - 1] 99 if prize in user_prize_dict: 100 user_prize_dict[prize] += 1 101 else: 102 user_prize_dict[prize] = 1 103 print(f'本次获得奖品为:{prize}\n') 104 if count == 10: 105 if user_prize_dict.get('再来一次!'): 106 user_prize_dict.pop('再来一次!') 107 print(f'总共获得的奖品为:{user_prize_dict}') 108 break 109 count += 1 110 111 112 user_func_dic = { 113 '1': register, 114 '2': login, 115 } 116 while True: 117 print(''' 118 先注册,登陆后才能玩猜年龄游戏哦! 119 1. 注册 120 2. 登录 121 ''' 122 ) 123 choice = input('请选择功能编号(q退出)>>>:').strip().lower() 124 if choice == 'q' : break 125 if not choice in user_func_dic: 126 print('错误输入') 127 continue 128 user_func_dic.get(choice)()View Code