目录
猜年龄游戏简单版本
要求
- 给定年龄,用户可以猜三次年龄
- 年龄猜对,让用户选择两次奖励
- 用户选择两次奖励后可以退出
# coding=utf-8
'''
1. 给定年龄,用户可以猜三次年龄
2. 年龄猜对,让用户选择两次奖励
3. 用户选择两次奖励后可以退出
'''
def echo_error(red):
print(f"\033[31;1m {red}\033[0m".strip())
def echo_ok(green):
print(f"\033[32;1m {green}\033[0m".strip())
def echo_warn(warning):
print(f"\033[33;1m {warning}\033[0m".strip())
# 定义奖品列表
prize_dict = {
'0': "芭比娃娃",
'1': "变形金刚",
'2': "psp游戏机",
'3': "奥特曼",
'4': "遥控飞机",
'5': "chongqiwawa",
}
prize_msg = '''
0 芭比娃娃
1 变形金刚
2 psp游戏机
3 奥特曼
4 遥控飞机
5 chongqiwawa
'''
age = 18
age_count = 0
jiangpin_list = {}
chooice_count = 1
while age_count < 3:
age_inp = input("请输入年龄:")
if not age_inp.isdigit():
echo_error(f"傻逼吧,你的年龄是这个 {age_inp} 吗,请输入正确的年龄。")
continue
if int(age_inp) > age:
echo_warn("猜大了")
elif int(age_inp) < age:
echo_warn("猜小了")
elif int(age_inp) == age:
echo_ok("猜对了")
print(prize_msg)
while chooice_count < 3:
chooice = input(f"请输入你要领取的第{chooice_count}个奖励:")
if not chooice.isdigit():
echo_error("您输入有误,请重新输入")
continue
if jiangpin_list.get(prize_dict[chooice]) is None:
jiangpin_list[prize_dict[chooice]] = 1
else:
jiangpin_list[prize_dict[chooice]] += 1
chooice_count += 1
echo_ok(f"{prize_dict[chooice]} 领取成功!")
echo_ok(f'''您领取的奖品为
名称 数量''')
for k in jiangpin_list.keys():
print(k,jiangpin_list[k])
break
age_count += 1
猜年龄游戏升级版本
简单功能
提供用户注册、登录功能(使用pickle序列化用户文件)
输出日志到指定文件中
随机生成年龄
from logging_config import load_my_logging_cfg
logger = load_my_logging_cfg() # 固定写法
import random # 导入随机函数
import pickle
import os
def echo_error(red):
print(f"\033[31;1m {red}\033[0m".strip())
def echo_ok(green):
print(f"\033[32;1m {green}\033[0m".strip())
def echo_warn(warning):
print(f"\033[33;1m {warning}\033[0m".strip())
def file_open(file, mode, *args):
if mode == "wb":
data = args[0]
with open(file, mode) as f:
pickle.dump(data, f)
elif mode == "rb":
with open(file, mode) as f:
user_dict = pickle.load(f)
return user_dict
def user_check(username, password, mode):
file = username + ".db"
if mode == "regist":
if not os.path.isfile(file):
user_dict = {"username": username, "password": password, "stat": 0}
file_open(file, "wb", user_dict)
print("注册成功")
else:
print("用户已存在")
elif mode == "login":
if os.path.isfile(file):
user_dict = file_open(file, "rb")
print("登录成功")
return user_dict
else:
print("用户不存在")
return None
def guess_funtion(prize_dict):
age = random.randint(0, 100)
age_count = 1
jiangpin_list = {}
chooice_count = 1
login_count = 1
while True:
print('''
1 注册
2 登录
3 退出
''')
chooice = input("请输入你的选择:")
if not chooice.isdigit():
echo_error("非法输入!")
continue
if chooice == "1":
username = input("请输入你的用户名:")
password = input("请输入你的密码:")
user_check(username, password, "regist")
elif chooice == "3":
break
if chooice == "2":
while login_count < 4:
username = input("请输入你的用户名:")
password = input("请输入你的密码:")
user_check(username,password,"login")
logger.info(f"{username} 第 {login_count} 次登录成功")
while age_count < 4:
print(age)
age_inp = input("请输入年龄:")
if not age_inp.isdigit():
echo_error(f"傻逼吧,你的年龄是这个 {age_inp} 吗,请输入正确的年龄。")
continue
if int(age_inp) > age:
echo_warn("猜大了")
elif int(age_inp) < age:
echo_warn("猜小了")
elif int(age_inp) == age:
logger.info(f"{username} 第 {age_count} 次猜对了")
for i, k in prize_dict.items(): print(i, k)
while chooice_count < 3:
chooice = input(f"请输入你要领取的第{chooice_count}个奖励:")
if not chooice.isdigit():
echo_error("您输入有误,请重新输入")
continue
if jiangpin_list.get(prize_dict[chooice]) is None:
jiangpin_list[prize_dict[chooice]] = 1
else:
jiangpin_list[prize_dict[chooice]] += 1
chooice_count += 1
echo_ok(f"{prize_dict[chooice]} 领取成功!")
echo_ok(f'''您领取的奖品为
名称 数量''')
for k in jiangpin_list.keys():
print(k, jiangpin_list[k])
break
age_count += 1
break
if __name__ == "__main__":
# 定义奖品列表
prize_dict = {
'0': "芭比娃娃",
'1': "变形金刚",
'2': "psp游戏机",
'3': "奥特曼",
'4': "遥控飞机",
'5': "chongqiwawa",
}
guess_funtion(prize_dict)
日志输出模块
import os
import logging.config
# 定义三种日志输出格式 开始
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
'[%(levelname)s][%(message)s]' # 其中name为getLogger()指定的名字;lineno为调用日志输出函数的语句所在的代码行
simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
# 定义日志输出格式 结束
# os.path.abspath(__file__) 获取logging_config.py的路径
logfile_dir = os.path.dirname(os.path.abspath(__file__)) # log文件的目录,需要自定义文件路径 # atm
logfile_dir = os.path.join(logfile_dir, 'log') # C:\Users\oldboy\Desktop\atm\log
logfile_name = '猜年龄游戏.log' # log文件名,需要自定义路径名
# 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir): # C:\Users\oldboy\Desktop\atm\log
os.mkdir(logfile_dir)
# log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name) # C:\Users\oldboy\Desktop\atm\log\log.log
# 定义日志路径 结束
# log配置字典
LOGGING_DIC = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': standard_format
},
'simple': {
'format': simple_format
},
},
'filters': {}, # filter可以不定义
'handlers': {
# 打印到终端的日志
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler', # 打印到屏幕
'formatter': 'simple'
},
# 打印到文件的日志,收集info及以上的日志
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
'formatter': 'standard',
'filename': logfile_path, # 日志文件
'maxBytes': 1024 * 1024 * 5, # 日志大小 5M (*****)
'backupCount': 5,
'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了
},
},
'loggers': {
# logging.getLogger(__name__)拿到的logger配置。如果''设置为固定值logger1,则下次导入必须设置成logging.getLogger('logger1')
'': {
# 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
'handlers': ['default', 'console'],
'level': 'DEBUG',
'propagate': False, # 向上(更高level的logger)传递
},
},
}
def load_my_logging_cfg():
logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置
logger = logging.getLogger(__name__) # 生成一个log实例
# logger.info('It works!') # 记录该文件的运行状态
return logger
if __name__ == '__main__':
load_my_logging_cfg()