0919作业 猜年龄函数版

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

  1. 登录函数
  2. 注册函数
  3. 猜年龄函数
  4. 选择奖品函数
age = 18
prize_dict = {0: '布娃娃', 1: '变形金刚', 2: '奥特曼', 3: '<Python从入门到放弃>'}


# 注册功能
def register():
    print('欢迎来到游戏注册环节')
    while True:
        username = input('注册-请输入你的用户名:')
        pwd = input('注册-请输入你的密码:')
        re_pwd = input('注册-请再次确认你的密码: ')
        # 判断两次密码是否相同
        if not pwd == re_pwd:
            print('两次密码不一致,请重新输入\n')
            continue
        # 保存用户信息    
        with open('username_info.txt', 'a', encoding='utf8') as fa:
            fa.write(f'{username}:{pwd}\n')
            print('注册成功')
            break

# 登录功能
def login():
    print('欢迎来到游戏登录环节')
    
    username_inp = input('登录-请输入你的用户名:')
    pwd_inp = input('登录-请输入你的密码:')
    
    with open('username_info.txt', 'r', encoding='utf8') as fr:
        # 用户信息切分,比较
        for user_info in fr:
            username, pwd = user_info.split(':')
            if username.strip() == username_inp and pwd.strip() == pwd_inp:
                print('登录成功')
                break
        else:
            print('登录失败')

# 选择奖品
def prize():
    count = 0
    while count < 2:
        print(f'恭喜你猜对了,请选择你的奖品,奖品列表如下:\n{prize_dict}')
        choice = input('请输入你想要的礼物编号,按q退出')
        if choice != 'n':
            print(f'恭喜你获得奖品: {prize_dict[int(choice)]}')
        else:
            break
        count += 1

# 猜年龄游戏
def game():
    count = 0
    print('欢迎进入猜年龄游戏')
    while count < 3:
        age_inp = input('请输入你猜的年龄:')

        if not age_inp.isdigit():
            print('格式错误')
            continue
        age_inp = int(age_inp)
        if age_inp < age:
            print('猜小了')
        elif age_inp > age:
            print('猜大了')
        else:
            prize()  # 调用prize函数
        count += 1


register()
login()
game()

猜你喜欢

转载自www.cnblogs.com/faye12/p/11550696.html