Python实现猜年龄游戏代码实例
1.在猜年龄的基础上编写登录、注册方法,并且把猜年龄游戏分函数处理,如
2.登录函数
3.注册函数
4.猜年龄函数
5.选择奖品函数
代码如下
importjson
real_age=18
prize_list=['好迪洗发水','绿箭侠','小猪佩奇','布娃娃','再来一次!']
importrandom
user_prize_dict={}
importos
defregister():
whileTrue:
username=input('输入用户名>>>(q退出):').strip().lower()
ifusername=='q':break
password=input('请输入密码>>>:').strip()
re_password=input('请再次确认密码>>>:').strip()
ifnotpassword==re_password:
print('密码不一致,请重输!')
continue
user_dic={'name':username,'password':password}
json_user_dic=json.dumps(user_dic)
withopen(f"{username}.txt",'w',encoding='utf-8')asf:
f.write(json_user_dic)
f.flush()
print('注册成功!')
break
deflogin():
count=0
whileTrue:
ifcount==3:
print('错误输入次数过多!')
break
username=input('请输入用户名>>>:').strip()
ifnotos.path.exists(username+'.txt'):
print('该用户不存在!')
continue
password=input('请输入密码>>>:').strip()
withopen(f"{username}.txt",'r',encoding='utf-8')asf:
user_json_dic=f.read()
user_dic=json.loads(user_json_dic)
ifusername==user_dic['name']andpassword==user_dic['password']:
print('登录成功!')
guess_age()
break
else:
print('用户名或密码错误!')
count+=1
defguess_age():
count=0
print('现在进入猜年龄游戏环节.......\n')
whileTrue:
count+=1
ifcount==4:
print('抱歉!你三次都猜错了!')
again_guess_age=input('请问是否要继续猜3次(y继续,n退出)>>>:').strip().lower()
ifagain_guess_age=='y':
count=0
continue
break
age=input('请输入你的年龄>>>:').strip()
ifnotage.isdigit():
print('请输入纯数字!')
continue
age=int(age)
ifage>real_age:
print('猜大了!')
elifage>>:').strip().lower()
ifnotchoice=='y':
print('非法输入!')
continue
prize_choice=random.randint(1,15)
ifprize_choicein[6,7,8]:
prize_choice=4
elifprize_choicein[9,10,11,12,13,14,15]:
prize_choice=5
prize=prize_list[prize_choice-1]
ifprizeinuser_prize_dict:
user_prize_dict[prize]+=1
else:
user_prize_dict[prize]=1
print(f'本次获得奖品为:{prize},您还有{2-count}次机会!\n')
ifcount==2:
ifuser_prize_dict.get('再来一次!'):
user_prize_dict.pop('再来一次!')
print(f'总共获得的奖品为:{user_prize_dict}')
break
count+=1
user_func_dic={
'1':register,
'2':login,
}
whileTrue:
print('''
先注册,登陆后才能玩猜年龄游戏哦!
1.注册
2.登录
'''
)
choice=input('请选择功能编号(q退出)>>>:').strip().lower()
ifchoice=='q':break
ifnotchoiceinuser_func_dic:
print('错误输入')
continue
user_func_dic.get(choice)()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。