09-09-周二_14-54-59
This commit is contained in:
@@ -173,3 +173,74 @@ def f():
|
|||||||
f()
|
f()
|
||||||
```
|
```
|
||||||
|
|
||||||
|
# 小练习
|
||||||
|
|
||||||
|
- 给前面的基于文件数据库的登录注册加上一个打游戏功能
|
||||||
|
- 使用装饰器验证用户是否登录
|
||||||
|
|
||||||
|
```python
|
||||||
|
def check_auth(func):
|
||||||
|
def inner(name):
|
||||||
|
if len(flag) == 1:
|
||||||
|
func(name)
|
||||||
|
else:
|
||||||
|
print("没登录就别打游戏了!")
|
||||||
|
return inner
|
||||||
|
|
||||||
|
@check_auth
|
||||||
|
def play_game(name):
|
||||||
|
print(f"{name[0]}开始游戏")
|
||||||
|
|
||||||
|
flag = []
|
||||||
|
while True:
|
||||||
|
# 获取文件中保存的用户名和密码信息
|
||||||
|
dic = {}
|
||||||
|
with open("db", "a+", encoding="utf-8") as f:
|
||||||
|
f.seek(0)
|
||||||
|
temp_data = f.readlines()
|
||||||
|
for i in temp_data:
|
||||||
|
data = i.strip()
|
||||||
|
if len(data) == 0:
|
||||||
|
continue
|
||||||
|
temp_db = data.split("✨")
|
||||||
|
dic[temp_db[0]] = temp_db[-1]
|
||||||
|
|
||||||
|
# 登录注册的逻辑
|
||||||
|
print("登录".center(30,"="))
|
||||||
|
print("请选择:\n1.登录\n2.注册\n3.退出登录\n4.打游戏")
|
||||||
|
choice = input(">>>")
|
||||||
|
if choice == "1":
|
||||||
|
username = input("输入用户名:")
|
||||||
|
if username in dic.keys():
|
||||||
|
password = input("输入密码:")
|
||||||
|
if dic[username] == password:
|
||||||
|
print("\033[42;30m 登录成功! \033[0m")
|
||||||
|
flag.append(username)
|
||||||
|
else:
|
||||||
|
print("\033[41;37m 密码错误 \033[0m")
|
||||||
|
else:
|
||||||
|
print("\033[41;37m用户名不存在!\033[0m")
|
||||||
|
elif choice == "2":
|
||||||
|
username = input("输入用户名")
|
||||||
|
if username in dic.keys():
|
||||||
|
print("\033[34;41m 用户名已存在!\033[0m")
|
||||||
|
continue
|
||||||
|
password = input("请输入密码")
|
||||||
|
dic[username] = password
|
||||||
|
print("\033[42;30m 注册成功! \033[0m")
|
||||||
|
elif choice == "3":
|
||||||
|
flag.clear()
|
||||||
|
print("退出成功!")
|
||||||
|
elif choice == "4":
|
||||||
|
play_game(flag)
|
||||||
|
else:
|
||||||
|
print("\033[41;37m输入错误!\033[0m")
|
||||||
|
|
||||||
|
# 将数据写入文件
|
||||||
|
with open("db", "w+", encoding="utf-8") as f:
|
||||||
|
for k,v in dic.items():
|
||||||
|
data = f"{k}✨{v}\n"
|
||||||
|
f.write(data)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user