control_test.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. import json
  2. import os
  3. import sys
  4. import gc
  5. import pygame
  6. import time
  7. import os
  8. import concurrent.futures
  9. from functools import partial
  10. from json import JSONDecodeError
  11. from game.algo import rougeGen as RG
  12. from game.const import window as W, color as C, game as G
  13. from game.const import rouge as R
  14. from game.effect import effect
  15. from game.frame import character, flame
  16. from game.level.level import Level
  17. from game.sprite.hero import Hero
  18. from game.file_loader.fileLoader import load_json
  19. def garbage_collect(last_time):
  20. if time.time() - last_time[0] >= 10:
  21. collected = gc.collect()
  22. # print(f"Garbage collector: collected {collected} objects.")
  23. last_time[0] = time.time()
  24. def rouge_reset():
  25. R.has_ocean_shop = False
  26. R.show_cursor = False
  27. R.coin = 8
  28. R.current_standard_defense = 0
  29. R.monster_defense_delta = 0
  30. R.monster_HP_rate = 1 # 100%
  31. R.player_bomb_self_damage_reduce_rate = 1 # 100%
  32. R.slow_immune = 0
  33. R.reverse_immune = 0
  34. R.root_immune = 0
  35. R.stun_immune = 0
  36. R.random_dmg = False
  37. R.rouge_destiny["RougeTreasureDestiny"] = R.rouge_destiny["RougeTreasureDestinyWizard"] = R.rouge_destiny["RougeTreasureDestinyMachine"] = 0
  38. def _preload_flame(orientation):
  39. try:
  40. flame.get_flame(orientation)
  41. except Exception as e:
  42. print(f"Error processing flame {orientation}: {e}")
  43. def _preload_effect(e):
  44. try:
  45. name = e.split('.')[0]
  46. effect.get_effect(name)
  47. except Exception as e:
  48. print(f"Error processing effect {e}: {e}")
  49. def _preload_character(f):
  50. try:
  51. jf = load_json(G.GAME_PATH + "\\" + "game/frame/character/" + f)
  52. character.get_character(jf, C.CHARACTER_WHITE, dict())
  53. except Exception as e:
  54. print(f"Error processing character {f}: {e}")
  55. class Control:
  56. def __init__(self, test_map_name, is_continue=False, test_hero="Fox"):
  57. self.map_json = None
  58. self.map_file = None
  59. self.map_name_json = None
  60. self.screen = None
  61. self.is_continue = is_continue
  62. self.test_map_name = test_map_name
  63. self.test_hero_name = test_hero
  64. self.cfg_json = None
  65. self.your_name = None # 玩家名称
  66. self.map_set_json = None
  67. self.map_set_at = None # 当前在map_set的第几关 从0开始
  68. self.mapmax_x = None # 当前关宽度
  69. self.mapmax_y = None # 当前关高度
  70. self.music_volume = None # 游戏音乐音量大小
  71. self.sound_volume = None # 游戏音效音量大小
  72. self.frame_rate = None # 游戏帧速率
  73. self.display_frame_rate = None # 显示帧率
  74. self.grid_damage_duration = None # 网格伤害持续时间
  75. self.display_flags = 0 # 画面显示特征
  76. # 游戏值
  77. self.me = None # 玩家Hero对象
  78. self.current_level = None # 当前关卡Level对象
  79. self.orientations = dict() # 方向键与字符串的映射
  80. self.walking_stack = [] # 方向键栈
  81. self.bomb_old = 0 # 连按空格键标志
  82. self.f6_old = False # 连按F6键标志(名字牌显示开关)
  83. self.f7_old = False # 连按F7键标志(名字血量切换)
  84. self.pause_old = False
  85. self.reset_old = False # 连按reset键标志
  86. self.skills_old = [False, False, False, False, False, False, False] # 连按技能键标志
  87. self.message_old = [False, False, False, False]
  88. self.key2idx = dict() # 数字键与技能下标的映射
  89. self.key2message = dict()
  90. self.cfg_space = None # 用户自定义空格
  91. self.cfg_f6 = None # 用户自定义f6
  92. self.cfg_f7 = None # 用户自定义f7
  93. self.cfg_pause = None
  94. self.cfg_reset = None # 用户自定义重启0
  95. self.text_font = None
  96. self.description_shown = False
  97. self.wall_walking = True
  98. R.debug_mode = True
  99. R.test_mode = True
  100. R.rouge_story = ""
  101. pygame.init()
  102. pygame.display.set_caption(W.WINDOW_CAPTION)
  103. self.init_game()
  104. self.preload()
  105. # try:
  106. # self.preload()
  107. # except Exception as e:
  108. # print(e)
  109. self.proceed_game()
  110. # import cProfile
  111. # cProfile.runctx("self.update()", globals=globals(), locals=locals(), sort="tottime")
  112. self.update()
  113. def init_game(self):
  114. # 游戏初始化 读取配置文件
  115. try:
  116. with open(G.GAME_PATH + "\\" + "config.json", encoding="utf-8") as f:
  117. self.cfg_json = json.load(f)
  118. except JSONDecodeError:
  119. with open(G.GAME_PATH + "\\" + "config.json", encoding="utf-8_sig") as f:
  120. self.cfg_json = json.load(f)
  121. self.map_set_at = -1
  122. G.DISPLAY_NPC_NAME_CARD = True
  123. G.DISPLAY_NPC_BLOOD = self.cfg_json["display_npc_blood"]
  124. self.music_volume = self.cfg_json["music_volume"]
  125. self.frame_rate = int(self.cfg_json["frame_rate"])
  126. G.SOUND_VOLUME = self.cfg_json["sound_volume"]
  127. G.DISPLAY_FRAME_RATE = self.cfg_json["display_frame_rate"]
  128. G.FIRST_FRAME_SHORTEN_RATE = float(self.cfg_json["first_frame_shorten_rate"])
  129. G.LOW_CONFIG_MODE = bool(self.cfg_json["low_config_mode"])
  130. self.grid_damage_duration = G.GRID_DMG_DURATION
  131. self.your_name = self.cfg_json["your_name"]
  132. self.init_keys(self.cfg_json["keys"])
  133. self.text_font = pygame.font.Font(G.GAME_PATH+"/res/font/simsun.ttc", 16)
  134. if not self.cfg_json["frame_screen"]:
  135. self.display_flags = pygame.NOFRAME
  136. if self.cfg_json["full_screen"]:
  137. self.display_flags = pygame.FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF
  138. try:
  139. if self.cfg_json["v_sync"] and self.cfg_json["frame_screen"] and not self.cfg_json["full_screen"]:
  140. self.display_flags = pygame.HWSURFACE | pygame.DOUBLEBUF
  141. # self.display_flags = pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.OPENGL
  142. elif self.cfg_json["v_sync"] and not self.cfg_json["frame_screen"]:
  143. self.display_flags |= pygame.HWSURFACE | pygame.DOUBLEBUF
  144. elif self.cfg_json["v_sync"] and self.cfg_json["full_screen"]:
  145. self.display_flags = pygame.FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF
  146. except Exception as e:
  147. print(e)
  148. G.DROP_ITEM = False
  149. G.LAST_MAP_TIME = G.LAST_LEVEL_TIME = pygame.time.get_ticks() // 1000
  150. if not self.is_continue:
  151. self.map_set_json = {
  152. "maps": [self.test_map_name]
  153. }
  154. else:
  155. self.map_set_at = G.CURRENT_LEVEL - 1
  156. self.map_set_json = R.central_mapset
  157. G.TOTAL_LEVEL = len(self.map_set_json["maps"])
  158. G.MAP_SET_NAME = self.cfg_json["map_set"]
  159. G.SHOW_STAT = True
  160. G.MONSTER_RECORD = False
  161. try:
  162. G.SHOW_TIME = bool(self.cfg_json["show_time"])
  163. except Exception as e:
  164. print(e)
  165. if not self.is_continue:
  166. self.map_file = {
  167. "maps": [self.test_map_name]
  168. }
  169. self.map_json = load_json(G.GAME_PATH+"/gtest/test_map/" + self.map_file["maps"][0] + ".json")
  170. else:
  171. self.map_file = {
  172. "maps": [self.test_map_name]
  173. }
  174. self.map_json = load_json(G.GAME_PATH+"/gtest/test_map/" + self.map_file["maps"][0] + ".json")
  175. if "special" in self.map_json["basic"].keys():
  176. if "defense" in self.map_json["basic"]["special"].keys():
  177. G.SPECIAL_DEFENSE = self.map_json["basic"]["special"]["defense"]
  178. else:
  179. G.SPECIAL_DEFENSE = 0
  180. if "damage" in self.map_json["basic"]["special"].keys():
  181. G.SPECIAL_DAMAGE = self.map_json["basic"]["special"]["damage"]
  182. else:
  183. G.SPECIAL_DAMAGE = 0
  184. if "speed" in self.map_json["basic"]["special"].keys():
  185. G.SPECIAL_SPEED = self.map_json["basic"]["special"]["speed"]
  186. else:
  187. G.SPECIAL_SPEED = 0
  188. if "power" in self.map_json["basic"]["special"].keys():
  189. G.SPECIAL_POWER = self.map_json["basic"]["special"]["power"]
  190. else:
  191. G.SPECIAL_POWER = 0
  192. if "bomb" in self.map_json["basic"]["special"].keys():
  193. G.SPECIAL_BOMB = self.map_json["basic"]["special"]["bomb"]
  194. else:
  195. G.SPECIAL_BOMB = 0
  196. else:
  197. G.SPECIAL_DAMAGE = 0
  198. G.SPECIAL_DEFENSE = 0
  199. G.SPECIAL_SPEED = 1
  200. G.SPECIAL_POWER = 0
  201. G.SPECIAL_BOMB = 0
  202. self.screen = pygame.display.set_mode(W.WINDOW_SIZE, flags=self.display_flags)
  203. pygame.display.set_icon(pygame.image.load(G.GAME_PATH+"/res/img/ui/icon.png").convert_alpha())
  204. for i in range(10):
  205. file_name = "itemNum_0_" + str(i) + ".png"
  206. img = pygame.image.load(G.GAME_PATH+"/res/img/ui/number/" + file_name).convert_alpha()
  207. G.NUMBER_IMG.append(img)
  208. def init_keys(self, keys_root):
  209. self.orientations[keys_root["RIGHT"]] = "R"
  210. self.orientations[keys_root["UP"]] = "U"
  211. self.orientations[keys_root["LEFT"]] = "L"
  212. self.orientations[keys_root["DOWN"]] = "D"
  213. self.key2idx[keys_root["1"]] = 0
  214. self.key2idx[keys_root["2"]] = 1
  215. self.key2idx[keys_root["3"]] = 2
  216. self.key2idx[keys_root["4"]] = 3
  217. self.key2idx[keys_root["5"]] = 4
  218. self.key2idx[keys_root["6"]] = 5
  219. self.key2idx[keys_root["7"]] = 6
  220. self.key2message[keys_root["R"]] = 0
  221. self.key2message[keys_root["T"]] = 1
  222. self.key2message[keys_root["Y"]] = 2
  223. self.key2message[keys_root["U"]] = 3
  224. self.cfg_space = keys_root["SPACE"]
  225. self.cfg_f6 = keys_root["F6"]
  226. self.cfg_f7 = keys_root["F7"]
  227. self.cfg_reset = keys_root["RESET"]
  228. try:
  229. self.cfg_pause = keys_root["P"]
  230. except Exception as e:
  231. print(e)
  232. # self.cfg_pause = 112
  233. def preload(self):
  234. if not self.cfg_json["allow_preload"]:
  235. return
  236. # 使用 ThreadPoolExecutor 来并行化 I/O 操作
  237. with concurrent.futures.ThreadPoolExecutor() as executor:
  238. futures = []
  239. ch_root = "game/frame/character/"
  240. # 对所有文件进行异步处理
  241. for f in os.listdir(G.GAME_PATH + "\\" + ch_root):
  242. futures.append(executor.submit(_preload_character, f))
  243. eff_root = "game/effect/effect"
  244. for e in os.listdir(G.GAME_PATH + "\\" + eff_root):
  245. futures.append(executor.submit(_preload_effect, e))
  246. for orientation in flame.ORIENTATIONS:
  247. futures.append(executor.submit(_preload_flame, orientation))
  248. # 等待所有任务完成
  249. for future in concurrent.futures.as_completed(futures):
  250. try:
  251. future.result()
  252. except Exception as e:
  253. print(f"Error during preload: {e}")
  254. def proceed_game(self, is_reset=False):
  255. if self.map_set_at + 1 < len(self.map_set_json["maps"]):
  256. self.map_set_at += 1
  257. map_name = self.map_set_json["maps"][self.map_set_at]
  258. hero_name = self.cfg_json["your_hero"]
  259. character_color = self.cfg_json["your_character_color"]
  260. print(map_name, self.map_set_at)
  261. self.set_level(self.your_name, map_name, hero_name, character_color, is_reset)
  262. else:
  263. # 正常刷新
  264. if not self.description_shown:
  265. self.current_level.update(self.screen)
  266. def proceed_custom_game(self, custom_map):
  267. self.map_set_at = 0
  268. map_name = custom_map
  269. hero_name = self.test_hero_name
  270. character_color = self.cfg_json["your_character_color"]
  271. G.TOTAL_LEVEL = G.CURRENT_LEVEL + 1
  272. self.set_level(self.your_name, map_name, hero_name, character_color)
  273. G.HAS_RECORD = False
  274. def set_level(self, your_name, map_name, hero_name, character_color, is_reset=False):
  275. character_colors = {
  276. "Red": C.CHARACTER_RED, "Blue": C.CHARACTER_BLUE, "SkyBlue": C.CHARACTER_SKYBLUE, "Yellow": C.CHARACTER_YELLOW, "Green": C.CHARACTER_GREEN,
  277. "Orange": C.CHARACTER_ORANGE, "Pink": C.CHARACTER_PINK, "SakuraPink": C.CHARACTER_SAKURAPINK, "Purple": C.CHARACTER_PURPLE,
  278. "Black": C.CHARACTER_BLACK, "White": C.CHARACTER_WHITE, "ForestGreen": C.CHARACTER_FORESTGREEN, "GrassGreen": C.CHARACTER_GRASSGREEN,
  279. "Withered": C.CHARACTER_WITHERED
  280. }
  281. character_color = character_colors[character_color]
  282. # 保留我的技能剩余数
  283. me = Hero(hero_name, (0, 0), character_color)
  284. if self.me is not None and not is_reset:
  285. me.skill_remains = self.me.skill_remains
  286. self.me = me
  287. # 设置新关卡
  288. self.current_level = Level(your_name, map_name, self.me, self.music_volume, self.grid_damage_duration, self)
  289. def update(self):
  290. last_time = [time.time()]
  291. while True:
  292. for event in pygame.event.get():
  293. if event.type == pygame.QUIT:
  294. pygame.display.quit()
  295. pygame.quit()
  296. sys.exit()
  297. if self.current_level is not None:
  298. if self.current_level.finish_flag:
  299. # 如果过关
  300. self.proceed_game()
  301. elif self.current_level.custom_finish_flag:
  302. # 如果过关
  303. self.proceed_custom_game(self.current_level.custom_next_map)
  304. else:
  305. # 正常刷新
  306. if not self.description_shown:
  307. self.current_level.update(self.screen)
  308. self.key_pressed()
  309. pygame.display.flip()
  310. pygame.time.Clock().tick(self.frame_rate)
  311. garbage_collect(last_time)
  312. if time.time() - last_time[0] >= 60:
  313. break
  314. def update_test(self):
  315. import tracemalloc
  316. # import time
  317. # last_time = time.time()
  318. import objgraph
  319. import gc
  320. import matplotlib.pyplot as plt
  321. from guppy import hpy
  322. tracemalloc.start()
  323. mem_usage = []
  324. snapshot_initial = tracemalloc.take_snapshot()
  325. start_time = time.time()
  326. while True:
  327. current, peak = tracemalloc.get_traced_memory() # 获取当前和最大内存使用
  328. mem_usage.append(current / 10**6)
  329. snapshot_current = tracemalloc.take_snapshot()
  330. top_stats = snapshot_current.compare_to(snapshot_initial, 'lineno')
  331. print("[Top 10 memory allocations]")
  332. for stat in top_stats[:10]:
  333. print(stat)
  334. for event in pygame.event.get():
  335. if event.type == pygame.QUIT:
  336. pygame.display.quit()
  337. pygame.quit()
  338. sys.exit()
  339. if self.current_level is not None:
  340. if self.current_level.finish_flag:
  341. # 如果过关
  342. self.proceed_game()
  343. elif self.current_level.custom_finish_flag:
  344. # 如果过关
  345. self.proceed_custom_game(self.current_level.custom_next_map)
  346. else:
  347. # 正常刷新
  348. if not self.description_shown:
  349. self.current_level.update(self.screen)
  350. self.key_pressed()
  351. pygame.display.flip()
  352. pygame.time.Clock().tick(self.frame_rate)
  353. if time.time() - start_time >= 60:
  354. break
  355. # last_time = time.time()
  356. # snapshot = tracemalloc.take_snapshot()
  357. # top_stats = snapshot.statistics('lineno')
  358. # print("[ Top 20 ]")
  359. # for stat in top_stats[:20]:
  360. # print(stat)
  361. tracemalloc.stop()
  362. gc.collect()
  363. plt.figure(figsize=(12, 8))
  364. plt.plot(mem_usage, label='Memory Usage (MB)', color='r')
  365. plt.title('Memory Usage Over Time')
  366. plt.xlabel('Time')
  367. plt.ylabel('Memory Usage (MB)')
  368. plt.legend()
  369. plt.grid(True)
  370. plt.show()
  371. def key_pressed(self):
  372. # 键盘事件检测
  373. keys = pygame.key.get_pressed()
  374. self.player_bomb(keys)
  375. self.player_move(keys)
  376. self.player_f6(keys)
  377. self.player_f7(keys)
  378. # self.player_pause(keys)
  379. self.player_reset(keys)
  380. self.player_skill(keys)
  381. self.player_message(keys)
  382. def player_move(self, keys):
  383. # 玩家移动
  384. for enum in self.orientations.keys():
  385. if keys[enum]:
  386. if enum not in self.walking_stack:
  387. self.walking_stack.insert(0, enum)
  388. else:
  389. if enum in self.walking_stack:
  390. self.walking_stack.remove(enum)
  391. # 取栈顶元素first
  392. first = 0
  393. if len(self.walking_stack) > 0:
  394. first = self.walking_stack[0]
  395. # 判断first是哪个方向
  396. if first == 0:
  397. self.me.set_motion()
  398. else:
  399. self.me.set_motion(self.orientations[first])
  400. if G.IN_BUBBLE:
  401. if self.orientations[first] != G.LAST_KEY:
  402. G.LAST_KEY = self.orientations[first]
  403. G.KEY_QUEUE.append(self.orientations[first])
  404. def player_bomb(self, keys):
  405. if keys[self.cfg_space]:
  406. if self.bomb_old == 0:
  407. self.me.set_bomb()
  408. self.bomb_old += 1
  409. else:
  410. self.bomb_old = 0
  411. def player_f6(self, keys):
  412. if keys[self.cfg_f6]:
  413. if self.f6_old is True:
  414. return
  415. # 按下F6键
  416. G.DISPLAY_NPC_NAME_CARD = not G.DISPLAY_NPC_NAME_CARD
  417. self.f6_old = True
  418. else:
  419. self.f6_old = False
  420. def player_f7(self, keys):
  421. if keys[self.cfg_f7]:
  422. if self.f7_old is True:
  423. return
  424. # 按下F7键
  425. G.DISPLAY_NPC_NAME_CARD = True
  426. G.DISPLAY_NPC_BLOOD = not G.DISPLAY_NPC_BLOOD
  427. self.f7_old = True
  428. else:
  429. self.f7_old = False
  430. def player_pause(self, keys):
  431. if keys[self.cfg_pause]:
  432. if self.pause_old is True:
  433. return
  434. # 按下键
  435. G.PAUSE = not G.PAUSE
  436. self.pause_old = True
  437. else:
  438. self.pause_old = False
  439. def player_reset(self, keys):
  440. if keys[self.cfg_reset]:
  441. if self.reset_old is True:
  442. return
  443. R.battle_district = []
  444. R.se_district = []
  445. R.story_eden, R.story_destiny, R.story_ocean = False, False, False
  446. R.continuing_game = False
  447. R.last_item = None
  448. user_documents_folder = os.path.expanduser("~\\Documents") # 获取用户的"文档"文件夹路径
  449. qqtpve_folder = os.path.join(user_documents_folder, "QQTPVE") # 构建QQTPVE文件夹路径
  450. os.makedirs(qqtpve_folder, exist_ok=True) # 确保QQTPVE文件夹存在,如果不存在则创建
  451. last_game_file_path = os.path.join(qqtpve_folder, "rougeOBLastGame.rougedata") # 构建文件路径
  452. if os.path.exists(last_game_file_path):
  453. os.remove(last_game_file_path)
  454. print("清除旧数据")
  455. rouge_reset()
  456. RG.main_func()
  457. G.CURRENT_LEVEL = 0
  458. self.init_game()
  459. self.proceed_game(is_reset=True)
  460. self.reset_old = True
  461. G.CHEAT = False
  462. G.HAS_RECORD = False
  463. G.LAST_MAP_TIME = G.TIME
  464. G.LAST_LEVEL_TIME = G.TIME
  465. G.ITEM = 0
  466. G.MONSTER_RECORD_LIST = []
  467. G.HAS_RECORD_FULL = False
  468. G.HAS_GOLDEN = False
  469. self.cfg_json = load_json("config.json")
  470. self.map_set_json = {
  471. "maps": [self.test_map_name]
  472. }
  473. G.TOTAL_LEVEL = len(self.map_set_json["maps"])
  474. self.map_name_json = R.map_json_dic["rogueMap1"]
  475. if "environment_effect" in self.map_name_json["basic"].keys():
  476. G.ENVIRONMENT_EFFECT = self.map_name_json["basic"]["environment_effect"]
  477. else:
  478. G.ENVIRONMENT_EFFECT = []
  479. if "player_light" in self.map_name_json["basic"].keys():
  480. self.me.light = self.map_name_json["basic"]["player_light"]
  481. else:
  482. self.reset_old = False
  483. def player_skill(self, keys):
  484. for k in self.key2idx.keys():
  485. idx = self.key2idx[k] # 常量转索引
  486. if keys[k]:
  487. if self.skills_old[idx]:
  488. return
  489. self.me.use_skill(idx)
  490. self.skills_old[idx] = True
  491. else:
  492. self.skills_old[idx] = False
  493. def player_message(self, keys):
  494. for k in self.key2message.keys():
  495. idx = self.key2message[k] # 常量转索引
  496. if keys[k]:
  497. if self.message_old[idx]:
  498. return
  499. if R.debug_mode:
  500. G.LAST_LEVEL_TIME = self.current_level.times_num
  501. # print(R.current_standard_damage, G.SPECIAL_DAMAGE)
  502. R.current_standard_damage -= G.SPECIAL_DAMAGE
  503. R.current_standard_defense -= G.SPECIAL_DEFENSE
  504. self.proceed_game()
  505. self.me.use_message(idx)
  506. self.message_old[idx] = True
  507. else:
  508. self.message_old[idx] = False