在猜年龄的基础上编写登录、注册方法,并且把猜年龄游戏分函数处理,如
-
登录函数
-
注册函数
-
猜年龄函数
-
选择奖品函数
-
登录函数
def login():
login_count = 0
while login_count < 3:
username_inp = input('Please input your username:')
pwd_inp = input('Please input your password:')
with open('user_info.txt', 'r', encoding='utf-8') as fr:
for user_info in fr:
#user_info = user_info.strip('
')
username, pwd = user_info.split(':')
if username_inp == username.strip() and pwd_inp == pwd.strip():
print('登陆成功')
return 1
else:
print('用户名或密码错误,请重新登录')
login_count += 1
if login_count == 3:
return 0
def register():
username_inp = input('Please input your name:')
pwd_inp_count = 0
user_list = {}
user_list[username_inp] = pwd_inp_count
while pwd_inp_count < 3:
pwd_inp = input('Please set your password:')
re_pwd_inp = input('Please input your password again:')
if not pwd_inp == re_pwd_inp:
print('两次密码不符,请重新设置密码')
continue
with open('user_info.txt', 'a', encoding='utf-8') as fa:
fa.write(user_list)
fa.flush()
fa.close()
print('Registered successful')
return 1
def guess_age():
age = 18
inp_count = 0
while inp_count < 3: # 用户猜三次
inp_age = input('请输入你猜的年龄:')
if not inp_age.isdigit():
print('请输入数字')
continue
int_inp_age = int(inp_age)
if int_inp_age > 18: # 猜年龄核心代码
print('猜大了')
elif int_inp_age < 18:
print('猜小了')
else:
print('猜对了')
return 1
def choose_prizes():
prize_choose_count = 0
get_prize_dict = {} # 获取的奖品信息
while prize_choose_count < 2: # 猜对了有两次选择奖品的机会
prize_goods = {'0': '变形金刚', '1': '布娃娃', '2': '奥特曼', '3': '蜘蛛侠'}
print(prize_goods)
prize_choose = input('请输入你想要的奖品:')
if not prize_choose.isdigit():
print('请输入数字')
continue
prize = prize_goods[prize_choose]
print(f'你获得的奖品是{prize}')
if prize in get_prize_dict: # 将选择的奖品放入字典中,奖品作为key
get_prize_dict[prize] += 1
else:
get_prize_dict[prize] = 1
prize_choose_count += 1
print(f'总共获得奖品为:{get_prize_dict}')
start = input('''请选择:1、登录、2、注册 3、游戏:''')
if not start.isdigit():
print('请输入数字')
start = int(start)
if start == 1:
log = login()
if log == 1:
gus = guess_age()
if gus == 1:
choose_prizes()
elif start == 2:
log = login()
if log == 1:
gus = guess_age()
if gus == 1:
choose_prizes()
elif log == 0:
reg = register()
if reg == 1:
gus = guess_age()
if gus == 1:
choose_prizes()