在猜年龄的基础上编写登录、注册方法,并且把猜年龄游戏分函数处理

'''
在猜年龄的基础上编写登录、注册方法,并且把猜年龄游戏分函数处理,如
2. 登录函数
3. 注册函数
4. 猜年龄三次函数
5. 选择三次奖品函数
'''
import random
def username_pwd():
    username=input('请输入你的用户名:').strip()
    pwd=input('请输入你的密码:').strip()
    return username,pwd
def register():
    count=0
    while count<2:
        username, pwd = username_pwd()
        pwd_re = input('请再次输入你的密码:').strip()
        if pwd_re == pwd:
            print(f'用户{username}注册成功')
            with open('user_info.txt', 'a', encoding='utf8')as fa:
                fa.write(f'{username}:{pwd}
')
                fa.flush()
                break
        else:
            count+=1
            print(f'用户{username}两次密码不正确:')
def login():
    while True:
        username,pwd=username_pwd()
        user_info=f'{username}:{pwd}
'
        with open('user_info.txt','r',encoding='utf8')as fr:
            user_dict=fr.read()
            if user_info in user_dict:
                print(f'用户{username}登录成功:')
                break
            else:
                print(f'用户{username}登录失败:')
def guess_age():
    count=0
    while count<3:
        age=random.randint(18,50)
        chose_age=input('猜年龄游戏开始,请输入你的年龄或q退出:').strip()
        if chose_age=='q':
            break
        if not chose_age.isdigit():
            print('请输入整数字:')
            continue
        chose_age=int(chose_age)
        if chose_age>50 or chose_age<18:
            print('请输入大于18而小于50之间的整数:')
            continue
        if chose_age>age:
            count+=1
            print('猜大了')
        elif chose_age<age:
            count+=1
            print('猜小了')
        else:
            print('恭喜你猜对了')
            break
def chose_prize():
    prize={
        '1':'布娃娃',
        '2':'手机',
        '3':'电脑',
        '4':'充气娃娃',
        '5':'狗粮',
    }
    prize_dict={}
    count=0
    while count<3:
        for k ,v in prize.items():
            print(k,v)
        choice = input('请选择三次你的奖品或q退出:').strip()
        if choice == 'q':
            break
        if choice not in prize:
            print('请输入正确的数字:')
            continue
        prize_info = prize[choice]
        print(f'你得到的奖品是:{prize_info}')
        if prize_info in prize_dict:
            count+=1
            prize_dict[prize_info] += 1
        else:
            count+=1
            prize_dict[prize_info] = 1
    print(f'你得到的总奖品是{prize_dict}')


func_msg={
    '1':register,
    '2':login,
    '3':guess_age,
    '4':chose_prize,
}
while True:
    print('''
    1 注册
    2 登录
    3 猜年龄游戏
    4 选择奖品
    q 退出
    ''')
    choice=input('请选择功能或q退出:').strip()
    if choice=='q':
        break
    if not choice.isdigit:
        print('请输入数字:')
        continue
    if choice not in func_msg:
        print('请输入正确的数字:')
        continue
    func_msg[choice]()
原文地址:https://www.cnblogs.com/jinhongquan/p/11550887.html