utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. # -*- coding: utf-8 -*-
  2. import requests
  3. import sys
  4. import os
  5. import threading
  6. import json
  7. from json import JSONDecodeError
  8. import easygui as eg
  9. import tkinter as tk
  10. from game.const import game as G
  11. from game.const import rouge as R
  12. from game.file_loader.fileLoader import load_json, load_png, save_encrypt_single_rouge_file, load_rouge_data
  13. server_ip = "123.249.17.43:5000"
  14. ALLOWED_CHARACTERS = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+[]{}|;:,.<>?/")
  15. def load_online_config():
  16. file_path = os.path.join(os.getcwd(), 'login.json') # 获取绝对路径
  17. if not os.path.exists(file_path):
  18. print("login.json 存在")
  19. login_json = {"online_mode": True, "UID": "", "username": "", "password": ""}
  20. with open(f'login.json', 'w', encoding='utf-8') as file:
  21. json.dump(login_json, file, indent=4, ensure_ascii=False)
  22. try:
  23. with open("login.json", encoding="utf-8") as f:
  24. login_json = json.load(f)
  25. except JSONDecodeError:
  26. with open("login.json", encoding="utf-8_sig") as f:
  27. login_json = json.load(f)
  28. G.UID = login_json["UID"]
  29. G.USERNAME = login_json["username"]
  30. G.PASSWORD = login_json["password"]
  31. def try_login():
  32. try:
  33. with open("login.json", encoding="utf-8") as f:
  34. login_json = json.load(f)
  35. except JSONDecodeError:
  36. with open("login.json", encoding="utf-8_sig") as f:
  37. login_json = json.load(f)
  38. if login_json["online_mode"]:
  39. if G.UID != "":
  40. _result = uid_login(G.UID, G.PASSWORD)
  41. if _result.get('message', '未知错误') == "登录成功":
  42. G.USERNAME = _result['user_info']['name']
  43. G.IS_ONLINE = True
  44. # eg.msgbox(f"{G.USERNAME}({G.UID})登录成功!", "成功")
  45. choice = eg.buttonbox(msg=f"{G.USERNAME}({G.UID})登录成功!", title="欢迎", choices=["进入主界面", "修改名字", "覆盖本地数据"])
  46. if choice == "修改名字":
  47. change_username()
  48. elif choice == "覆盖本地数据":
  49. update_local_data()
  50. return True
  51. if G.USERNAME != "":
  52. _result = username_login(G.USERNAME, G.PASSWORD)
  53. if _result.get('message', '未知错误') == "登录成功":
  54. G.UID = _result['user_info']['UID']
  55. G.IS_ONLINE = True
  56. eg.msgbox(f"{G.USERNAME}({G.UID})登录成功!", "成功")
  57. return True
  58. eg.msgbox(f"登录失败!请检查登录信息或网络连接!", "失败")
  59. G.IS_ONLINE = False
  60. return False
  61. def change_username():
  62. fields = ["新昵称", "当前密码*"]
  63. values = eg.multpasswordbox("修改昵称", "输入信息", fields)
  64. if not values or not all(values):
  65. if values is None:
  66. return
  67. eg.msgbox("新昵称不能为空!", "错误")
  68. change_username()
  69. else:
  70. new_username, password = values
  71. try:
  72. response = requests.post(
  73. f'http://{server_ip}/update_username',
  74. json={"uid": G.UID, "username": G.USERNAME, "new_username": new_username, "password": password},
  75. timeout=5
  76. )
  77. if response.status_code == 200:
  78. login_json = {"online_mode": True, "UID": G.UID, "username": new_username, "password": password}
  79. with open(f'login.json', 'w', encoding='utf-8') as file:
  80. json.dump(login_json, file, indent=4, ensure_ascii=False)
  81. G.USERNAME = new_username
  82. eg.msgbox(f"昵称修改成功!", "结果")
  83. else:
  84. error_msg = response.json().get("message", "未知错误")
  85. eg.msgbox(f"修改失败: {error_msg}", "错误")
  86. change_username()
  87. except requests.exceptions.RequestException as e:
  88. eg.msgbox(f"无法连接服务器: {str(e)}", "网络错误")
  89. change_username()
  90. def update_local_data():
  91. online_data = get_online_data()
  92. user_documents_folder = os.path.expanduser("~\\Documents") # 获取用户的"文档"文件夹路径
  93. qqtpve_folder = os.path.join(user_documents_folder, "QQTPVE") # 构建QQTPVE文件夹路径
  94. os.makedirs(qqtpve_folder, exist_ok=True) # 确保QQTPVE文件夹存在,如果不存在则创建
  95. rouge_file_path = os.path.join(qqtpve_folder, "rougeOB.rougedata") # 构建文件路径
  96. local_data = load_rouge_data(rouge_file_path)
  97. local_text = f"小倩等级{local_data['Fox']['lv']}; " \
  98. f"波波丽等级{local_data['Boboli']['lv']}; " \
  99. f"火影等级{local_data['Naruto_old']['lv']}; " \
  100. f"阿莎等级{local_data['Asha']['lv']}; " \
  101. f"玛利亚等级{local_data['Maria']['lv']}; " \
  102. f"???等级{local_data['Surprise']['lv']}"
  103. oneline_text = f"小倩等级{online_data['Fox']['lv']}; " \
  104. f"波波丽等级{online_data['Boboli']['lv']}; " \
  105. f"火影等级{online_data['Naruto_old']['lv']}; " \
  106. f"阿莎等级{online_data['Asha']['lv']}; " \
  107. f"玛利亚等级{online_data['Maria']['lv']}; " \
  108. f"???等级{online_data['Surprise']['lv']}"
  109. choice = eg.buttonbox(msg=f"是否将本地数据\n{local_text}\n更新为\n{oneline_text}\n?该操作不可重置!", title="注意", choices=["覆盖数据", "取消"])
  110. if choice == "覆盖数据":
  111. rouge_data = {}
  112. for hero in ["Fox","Boboli","Naruto_old","Asha","Maria","Surprise"]:
  113. rouge_data[hero] = online_data[hero]
  114. save_encrypt_single_rouge_file(rouge_data, "rougeOB")
  115. eg.msgbox(f"数据更新成功!", "结果")
  116. return
  117. def get_online_data():
  118. if not G.IS_ONLINE:
  119. return
  120. latest_data = get_profile(G.UID).get('profile', {})
  121. if not latest_data:
  122. return
  123. return latest_data
  124. def show_loading_window():
  125. window = tk.Tk()
  126. window.title("提示")
  127. window.geometry("200x100")
  128. label = tk.Label(window, text="数据同步中,请稍后...")
  129. label.pack(pady=20)
  130. # 存储窗口引用用于关闭
  131. window.after(100, lambda: window.lift())
  132. return window
  133. def save_online():
  134. print("正在同步至服务器...")
  135. latest_data = get_online_data()
  136. if latest_data is None:
  137. return
  138. new_data = {}
  139. real_exp = int(R.rouge_exp * R.diff_exp[R.difficulty])
  140. for hero in R.hero_name.keys():
  141. if hero == R.rouge_hero:
  142. exp = latest_data[hero]["exp"] + real_exp
  143. else:
  144. exp = latest_data[hero]["exp"]
  145. lv = R.current_lv(exp)
  146. new_data[hero] = {"exp": exp, "lv": lv}
  147. new_data['record'] = latest_data['record']
  148. _result = update_profile(G.UID, new_data, G.PASSWORD)
  149. print(_result.get('message', '保存失败'))
  150. print("同步完成")
  151. return
  152. def register():
  153. fields = ["昵称", "密码*"]
  154. values = eg.multpasswordbox("用户注册", "输入信息", fields)
  155. if not values or not all(values):
  156. if values is None:
  157. return
  158. eg.msgbox("昵称和密码不能为空!", "错误")
  159. register()
  160. else:
  161. username, password = values
  162. if any(char not in ALLOWED_CHARACTERS for char in password):
  163. eg.msgbox("密码含有非法字符!", "错误")
  164. try:
  165. response = requests.post(
  166. f'http://{server_ip}/register',
  167. json={"username": username, "password": password},
  168. timeout=5
  169. )
  170. if response.status_code == 201:
  171. uid = response.json().get("UID", "未知")
  172. login_json = {"online_mode": True, "UID": uid, "username": username, "password": password}
  173. with open(f'login.json', 'w', encoding='utf-8') as file:
  174. json.dump(login_json, file, indent=4, ensure_ascii=False)
  175. G.UID = uid
  176. G.USERNAME = username
  177. G.PASSWORD = password
  178. eg.msgbox(f"注册成功(设备更变后可在login.json中凭UID或用户名登录)!\nUID: {uid}", "结果")
  179. else:
  180. error_msg = response.json().get("message", "未知错误")
  181. eg.msgbox(f"注册失败: {error_msg}; 已有账号请自行在login.json中凭UID或用户名登录", "错误")
  182. register()
  183. except requests.exceptions.RequestException as e:
  184. eg.msgbox(f"无法连接服务器: {str(e)}", "网络错误")
  185. register()
  186. def uid_login(uid, password):
  187. url = f'http://{server_ip}/uid_login'
  188. try:
  189. response = requests.post(url, json={'uid': uid, 'password': password})
  190. return response.json()
  191. except requests.exceptions.ConnectionError:
  192. return {'message': '无法连接到服务器'}
  193. def username_login(username, password):
  194. url = f'http://{server_ip}/username_login'
  195. try:
  196. response = requests.post(url, json={'username': username, 'password': password})
  197. return response.json()
  198. except requests.exceptions.ConnectionError:
  199. return {'message': '无法连接到服务器'}
  200. def get_profile(uid):
  201. url = f'http://{server_ip}/get_profile'
  202. try:
  203. response = requests.post(url, json={'uid': uid})
  204. return response.json()
  205. except requests.exceptions.ConnectionError:
  206. return {'message': '无法连接到服务器'}
  207. def update_profile(uid, profile, password):
  208. url = f'http://{server_ip}/update_profile'
  209. try:
  210. response = requests.post(url, json={'uid': uid, 'profile': profile, 'password': password})
  211. return response.json()
  212. except requests.exceptions.ConnectionError:
  213. return {'message': '无法连接到服务器'}
  214. if __name__ == '__main__':
  215. # username = "admin"
  216. # password = "123456"
  217. # result = register(username, password)
  218. # print(result.get('message', '未知错误'))
  219. # print("账号UID: ", result.get('UID', '未知错误'))
  220. #
  221. # username = str(input("登陆用户名: "))
  222. # password = input("登陆密码: ")
  223. # result = username_login(username, password)
  224. # print(result.get('message', '未知错误'))
  225. #
  226. # uid = str(input("登陆UID: "))
  227. # password = input("登陆密码: ")
  228. # result = uid_login(uid, password)
  229. # print(result.get('message', '未知错误'))
  230. uid = input("查询UID: ")
  231. result = get_profile(uid)
  232. print(result.get('name', '未知错误'))
  233. print(result.get('profile', '未知错误'))
  234. new_exp = input("更新后的经验: ")
  235. uid = input("修改的UID: ")
  236. password = input("修改的登陆密码: ")
  237. new_info = {
  238. 'Asha': {'exp': new_exp, 'lv': 1},
  239. 'Boboli': {'exp': 0, 'lv': 1},
  240. 'Fox': {'exp': 0, 'lv': 1},
  241. 'Maria': {'exp': 0, 'lv': 1},
  242. 'Naruto_old': {'exp': 0, 'lv': 1},
  243. 'Surprise': {'exp': 0, 'lv': 1},
  244. 'record': 'null'
  245. }
  246. result = update_profile(uid, new_info, password)
  247. print(result.get('message', '未知错误'))
  248. uid = input("查询UID: ")
  249. result = get_profile(uid)
  250. print(result.get('name', '未知错误'))
  251. print(result.get('message', '未知错误'))