weapon_config_manager.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 武器配置管理器
  5. 从config_manager.py中提取的武器相关配置管理功能
  6. 支持从Excel读取武器配置并与现有JSON配置合并
  7. """
  8. import json
  9. import os
  10. from pathlib import Path
  11. from datetime import datetime
  12. try:
  13. import pandas as pd
  14. PANDAS_AVAILABLE = True
  15. except ImportError:
  16. PANDAS_AVAILABLE = False
  17. print("警告: pandas未安装,无法处理Excel文件")
  18. class WeaponConfigManager:
  19. """武器配置管理器"""
  20. def __init__(self, excel_file_path=None, json_file_path=None):
  21. """初始化武器配置管理器
  22. Args:
  23. excel_file_path: Excel配置文件路径
  24. json_file_path: JSON配置文件路径
  25. """
  26. self.script_dir = Path(__file__).parent
  27. # 设置默认路径
  28. if excel_file_path is None:
  29. self.excel_file = self.script_dir / "方块武器配置" / "方块武器配置表.xlsx"
  30. else:
  31. self.excel_file = Path(excel_file_path)
  32. if json_file_path is None:
  33. self.json_file = self.script_dir.parent / "weapons.json"
  34. else:
  35. self.json_file = Path(json_file_path)
  36. print(f"Excel文件路径: {self.excel_file}")
  37. print(f"JSON文件路径: {self.json_file}")
  38. # 武器配置映射
  39. self.weapon_mapping = {
  40. 'format_type': 'horizontal',
  41. 'param_types': {
  42. 'ID': str,
  43. '名称': str,
  44. '类型': str,
  45. '稀有度': str,
  46. '权重': int,
  47. '伤害': int,
  48. '射速': float,
  49. '射程': int,
  50. '子弹速度': int,
  51. # 方块价格配置字段
  52. '基础每格成本': int,
  53. 'I形状成本': int,
  54. 'H-I形状成本': int,
  55. 'L形状成本': int,
  56. 'S形状成本': int,
  57. 'D-T形状成本': int,
  58. # 英文字段支持
  59. 'id': str,
  60. 'name': str,
  61. 'type': str,
  62. 'rarity': str,
  63. 'weight': int,
  64. 'damage': int,
  65. 'fireRate': float,
  66. 'range': int,
  67. 'bulletSpeed': int,
  68. 'baseCost': int,
  69. 'I_shape_cost': int,
  70. 'HI_shape_cost': int,
  71. 'L_shape_cost': int,
  72. 'S_shape_cost': int,
  73. 'DT_shape_cost': int
  74. }
  75. }
  76. def load_existing_json_config(self):
  77. """加载现有的JSON配置文件"""
  78. try:
  79. if self.json_file.exists():
  80. with open(self.json_file, 'r', encoding='utf-8') as f:
  81. config = json.load(f)
  82. print(f"成功加载现有JSON配置,包含 {len(config.get('weapons', []))} 个武器")
  83. return config
  84. else:
  85. print(f"JSON文件不存在,将创建新配置: {self.json_file}")
  86. return {'weapons': [], 'blockSizes': [], 'rarityWeights': {}}
  87. except Exception as e:
  88. print(f"加载JSON配置失败: {e}")
  89. return {'weapons': [], 'blockSizes': [], 'rarityWeights': {}}
  90. def read_excel_config(self):
  91. """读取Excel配置文件"""
  92. if not PANDAS_AVAILABLE:
  93. raise Exception("pandas未安装,无法读取Excel文件")
  94. if not self.excel_file.exists():
  95. raise Exception(f"Excel文件不存在: {self.excel_file}")
  96. try:
  97. # 读取所有工作表
  98. all_sheets = pd.read_excel(self.excel_file, sheet_name=None)
  99. print(f"成功读取Excel文件,包含工作表: {list(all_sheets.keys())}")
  100. return all_sheets
  101. except Exception as e:
  102. raise Exception(f"读取Excel文件失败: {e}")
  103. def parse_weapon_multi_sheet_data(self, all_sheets_data):
  104. """解析武器配置表的多工作表数据"""
  105. weapons_config = {'weapons': []}
  106. try:
  107. # 解析武器基础配置工作表
  108. base_sheet = None
  109. for sheet_name in ['武器基础配置', 'Weapon Config', 'weapons', '武器配置']:
  110. if sheet_name in all_sheets_data:
  111. base_sheet = all_sheets_data[sheet_name]
  112. break
  113. if base_sheet is not None:
  114. base_config = self.parse_config_data(base_sheet)
  115. if 'items' in base_config:
  116. weapons_config['weapons'] = base_config['items']
  117. print(f"成功解析武器基础配置,共{len(base_config['items'])}个武器")
  118. # 解析武器升级费用配置工作表
  119. upgrade_cost_sheet = None
  120. for sheet_name in ['武器升级费用配置', 'Weapon Upgrade Cost', 'upgrade_costs', '升级费用']:
  121. if sheet_name in all_sheets_data:
  122. upgrade_cost_sheet = all_sheets_data[sheet_name]
  123. print(f"找到升级费用配置工作表: {sheet_name}")
  124. break
  125. if upgrade_cost_sheet is not None:
  126. self._parse_upgrade_cost_data(upgrade_cost_sheet, weapons_config['weapons'])
  127. # 解析游戏内成本配置工作表
  128. cost_sheet = None
  129. for sheet_name in ['游戏内成本配置', 'In Game Cost', 'cost_config', '成本配置']:
  130. if sheet_name in all_sheets_data:
  131. cost_sheet = all_sheets_data[sheet_name]
  132. print(f"找到游戏内成本配置工作表: {sheet_name}")
  133. break
  134. if cost_sheet is not None:
  135. self._parse_cost_config_data(cost_sheet, weapons_config['weapons'])
  136. # 解析稀有度权重配置工作表
  137. rarity_sheet = None
  138. for sheet_name in ['稀有度权重', 'Rarity Weights', 'rarity_weights', '权重配置']:
  139. if sheet_name in all_sheets_data:
  140. rarity_sheet = all_sheets_data[sheet_name]
  141. print(f"找到稀有度权重配置工作表: {sheet_name}")
  142. break
  143. if rarity_sheet is not None:
  144. weapons_config['rarityWeights'] = self._parse_rarity_weights_data(rarity_sheet)
  145. # 解析方块形状配置工作表
  146. block_shape_sheet = None
  147. for sheet_name in ['方块形状配置', 'Block Shape Config', 'block_shapes', '形状配置']:
  148. if sheet_name in all_sheets_data:
  149. block_shape_sheet = all_sheets_data[sheet_name]
  150. print(f"找到方块形状配置工作表: {sheet_name}")
  151. break
  152. if block_shape_sheet is not None:
  153. weapons_config['blockSizes'] = self._parse_block_shape_data(block_shape_sheet)
  154. return weapons_config
  155. except Exception as e:
  156. print(f"解析武器配置失败: {e}")
  157. return {'weapons': []}
  158. def parse_config_data(self, df):
  159. """解析配置数据"""
  160. try:
  161. items = []
  162. # 检查第一行是否为表头
  163. first_row = df.iloc[0] if len(df) > 0 else None
  164. is_header = False
  165. if first_row is not None:
  166. first_cell = str(first_row.iloc[0]).strip() if len(first_row) > 0 else ""
  167. if first_cell in ['武器ID', 'ID', 'weapon_id', 'weaponId']:
  168. is_header = True
  169. print(f"检测到表头行,第一列内容: {first_cell}")
  170. for index, row in df.iterrows():
  171. if is_header and index == 0: # 跳过表头
  172. continue
  173. # 转换行数据为字典
  174. item = {}
  175. for col_index, value in enumerate(row):
  176. if col_index < len(df.columns):
  177. col_name = df.columns[col_index]
  178. if pd.notna(value) and str(value).strip():
  179. # 根据映射转换数据类型
  180. param_type = self.weapon_mapping['param_types'].get(col_name, str)
  181. try:
  182. if param_type == int:
  183. item[col_name] = int(float(value))
  184. elif param_type == float:
  185. item[col_name] = float(value)
  186. else:
  187. item[col_name] = str(value).strip()
  188. except (ValueError, TypeError):
  189. item[col_name] = str(value).strip()
  190. # 检查是否有有效的武器ID
  191. weapon_id = item.get('ID') or item.get('id') or item.get('武器ID')
  192. if weapon_id and str(weapon_id).strip():
  193. items.append(item)
  194. return {'items': items}
  195. except Exception as e:
  196. print(f"解析配置数据失败: {e}")
  197. return {'items': []}
  198. def _parse_upgrade_cost_data(self, upgrade_cost_sheet, weapons_list):
  199. """解析升级费用配置数据"""
  200. try:
  201. print(f"开始处理升级费用配置,工作表行数: {len(upgrade_cost_sheet)}")
  202. upgrade_cost_data = []
  203. # 检查第一行是否为表头
  204. first_row = upgrade_cost_sheet.iloc[0] if len(upgrade_cost_sheet) > 0 else None
  205. is_header = False
  206. if first_row is not None:
  207. first_cell = str(first_row.iloc[0]).strip() if len(first_row) > 0 else ""
  208. if first_cell in ['武器ID', 'ID', 'weapon_id', 'weaponId']:
  209. is_header = True
  210. print(f"检测到表头行,第一列内容: {first_cell}")
  211. for index, row in upgrade_cost_sheet.iterrows():
  212. if is_header and index == 0: # 跳过表头
  213. continue
  214. # 支持多种武器ID字段名
  215. weapon_id = None
  216. for id_field in ['武器ID', 'ID', 'weapon_id', 'weaponId']:
  217. if id_field in row and pd.notna(row[id_field]):
  218. weapon_id = row[id_field]
  219. break
  220. if weapon_id is None:
  221. weapon_id = row.iloc[0] if len(row) > 0 else None
  222. if weapon_id and str(weapon_id).strip():
  223. upgrade_levels = {}
  224. # 从第5列开始是等级1-10的费用,从第15列开始是等级1-10的伤害
  225. for level in range(1, 11):
  226. cost_col_index = 4 + (level - 1)
  227. damage_col_index = 14 + (level - 1)
  228. level_config = {}
  229. # 处理费用
  230. if cost_col_index < len(row):
  231. cost = row.iloc[cost_col_index]
  232. if cost and str(cost).strip() and str(cost) != 'nan':
  233. try:
  234. level_config['cost'] = int(float(cost))
  235. except (ValueError, TypeError):
  236. pass
  237. # 处理伤害
  238. if damage_col_index < len(row):
  239. damage = row.iloc[damage_col_index]
  240. if damage and str(damage).strip() and str(damage) != 'nan':
  241. try:
  242. level_config['damage'] = int(float(damage))
  243. except (ValueError, TypeError):
  244. pass
  245. if level_config:
  246. upgrade_levels[str(level)] = level_config
  247. if upgrade_levels:
  248. upgrade_cost_data.append({
  249. 'weapon_id': str(weapon_id).strip(),
  250. 'levels': upgrade_levels
  251. })
  252. # 将升级费用配置合并到武器数据中
  253. for weapon in weapons_list:
  254. weapon_id = weapon.get('ID', '') or weapon.get('id', '')
  255. if weapon_id:
  256. matching_upgrade = None
  257. for upgrade_data in upgrade_cost_data:
  258. if upgrade_data['weapon_id'] == weapon_id:
  259. matching_upgrade = upgrade_data
  260. break
  261. if matching_upgrade:
  262. weapon['upgradeConfig'] = {
  263. 'maxLevel': 10,
  264. 'levels': matching_upgrade['levels']
  265. }
  266. print(f"✓ 为武器 {weapon_id} 添加了升级费用配置")
  267. except Exception as e:
  268. print(f"解析升级费用配置失败: {e}")
  269. def _parse_cost_config_data(self, cost_sheet, weapons_list):
  270. """解析游戏内成本配置数据"""
  271. try:
  272. print(f"开始处理游戏内成本配置,工作表行数: {len(cost_sheet)}")
  273. # 检查第一行是否为表头
  274. first_row = cost_sheet.iloc[0] if len(cost_sheet) > 0 else None
  275. is_header = False
  276. if first_row is not None:
  277. first_cell = str(first_row.iloc[0]).strip() if len(first_row) > 0 else ""
  278. if first_cell in ['武器ID', 'ID', 'weapon_id', 'weaponId']:
  279. is_header = True
  280. for index, row in cost_sheet.iterrows():
  281. if is_header and index == 0: # 跳过表头
  282. continue
  283. # 获取武器ID
  284. weapon_id = None
  285. for id_field in ['武器ID', 'ID', 'weapon_id', 'weaponId']:
  286. if id_field in row and pd.notna(row[id_field]):
  287. weapon_id = str(row[id_field]).strip()
  288. break
  289. if weapon_id is None:
  290. weapon_id = str(row.iloc[0]).strip() if len(row) > 0 else None
  291. if weapon_id:
  292. # 查找对应的武器并添加成本配置
  293. for weapon in weapons_list:
  294. w_id = weapon.get('ID', '') or weapon.get('id', '')
  295. if w_id == weapon_id:
  296. # 构建成本配置
  297. base_cost = 5 # 默认基础成本
  298. shape_costs = {}
  299. # 读取基础成本
  300. for field in ['武器基础售价', 'baseCost', '基础成本']:
  301. if field in row and pd.notna(row[field]):
  302. try:
  303. base_cost = int(float(row[field]))
  304. break
  305. except (ValueError, TypeError):
  306. pass
  307. # 读取各形状成本
  308. shape_fields = {
  309. 'I': ['I形状成本', 'I形状', 'I_shape', 'I'],
  310. 'H-I': ['H-I形状成本', 'H-I形状', 'HI_shape', 'H-I'],
  311. 'L': ['L形状成本', 'L形状', 'L_shape', 'L'],
  312. 'S': ['S形状成本', 'S形状', 'S_shape', 'S'],
  313. 'D-T': ['D-T形状成本', 'D-T形状', 'DT_shape', 'D-T'],
  314. 'L2': ['L2形状成本', 'L2形状', 'L2_shape', 'L2'],
  315. 'L3': ['L3形状成本', 'L3形状', 'L3_shape', 'L3'],
  316. 'L4': ['L4形状成本', 'L4形状', 'L4_shape', 'L4'],
  317. 'F-S': ['F-S形状成本', 'F-S形状', 'FS_shape', 'F-S'],
  318. 'T': ['T形状成本', 'T形状', 'T_shape', 'T']
  319. }
  320. for shape_key, field_names in shape_fields.items():
  321. for field_name in field_names:
  322. if field_name in row and pd.notna(row[field_name]):
  323. try:
  324. shape_costs[shape_key] = int(float(row[field_name]))
  325. break
  326. except (ValueError, TypeError):
  327. pass
  328. weapon['inGameCostConfig'] = {
  329. 'baseCost': base_cost,
  330. 'shapeCosts': shape_costs
  331. }
  332. print(f"✓ 为武器 {weapon_id} 添加了游戏内成本配置")
  333. break
  334. except Exception as e:
  335. print(f"解析游戏内成本配置失败: {e}")
  336. def _parse_rarity_weights_data(self, rarity_sheet):
  337. """解析稀有度权重配置数据"""
  338. try:
  339. rarity_weights = {}
  340. # 检查第一行是否为表头
  341. first_row = rarity_sheet.iloc[0] if len(rarity_sheet) > 0 else None
  342. is_header = False
  343. if first_row is not None:
  344. first_cell = str(first_row.iloc[0]).strip() if len(first_row) > 0 else ""
  345. if first_cell in ['稀有度', 'rarity', 'Rarity']:
  346. is_header = True
  347. for index, row in rarity_sheet.iterrows():
  348. if is_header and index == 0: # 跳过表头
  349. continue
  350. # 获取稀有度和权重
  351. rarity = None
  352. weight = None
  353. for field in ['稀有度', 'rarity', 'Rarity']:
  354. if field in row and pd.notna(row[field]):
  355. rarity = str(row[field]).strip()
  356. break
  357. if rarity is None:
  358. rarity = str(row.iloc[0]).strip() if len(row) > 0 else None
  359. for field in ['权重', 'weight', 'Weight']:
  360. if field in row and pd.notna(row[field]):
  361. try:
  362. weight = int(float(row[field]))
  363. break
  364. except (ValueError, TypeError):
  365. pass
  366. if weight is None and len(row) > 1:
  367. try:
  368. weight = int(float(row.iloc[1]))
  369. except (ValueError, TypeError):
  370. pass
  371. if rarity and weight is not None:
  372. rarity_weights[rarity] = weight
  373. print(f"✓ 添加稀有度权重: {rarity} = {weight}")
  374. return rarity_weights
  375. except Exception as e:
  376. print(f"解析稀有度权重配置失败: {e}")
  377. return {}
  378. def _parse_block_shape_data(self, block_shape_sheet):
  379. """解析方块形状配置数据"""
  380. try:
  381. block_shapes = []
  382. # 检查第一行是否为表头
  383. first_row = block_shape_sheet.iloc[0] if len(block_shape_sheet) > 0 else None
  384. is_header = False
  385. if first_row is not None:
  386. first_cell = str(first_row.iloc[0]).strip() if len(first_row) > 0 else ""
  387. if first_cell in ['ID', 'id', '形状ID', 'shape_id']:
  388. is_header = True
  389. print(f"检测到方块形状配置表头行,第一列内容: {first_cell}")
  390. for index, row in block_shape_sheet.iterrows():
  391. if is_header and index == 0: # 跳过表头
  392. continue
  393. # 获取方块形状数据
  394. shape_id = None
  395. shape_name = None
  396. shape_matrix = None
  397. grid_count = None
  398. cost_multiplier = None
  399. description = None
  400. # 获取ID
  401. for field in ['ID', 'id', '形状ID', 'shape_id']:
  402. if field in row and pd.notna(row[field]):
  403. shape_id = str(row[field]).strip()
  404. break
  405. if shape_id is None:
  406. shape_id = str(row.iloc[0]).strip() if len(row) > 0 else None
  407. # 获取名称
  408. for field in ['名称', 'name', 'Name', '形状名称']:
  409. if field in row and pd.notna(row[field]):
  410. shape_name = str(row[field]).strip()
  411. break
  412. if shape_name is None and len(row) > 1:
  413. shape_name = str(row.iloc[1]).strip() if pd.notna(row.iloc[1]) else None
  414. # 获取形状矩阵
  415. for field in ['形状矩阵', 'shape', 'matrix', '矩阵']:
  416. if field in row and pd.notna(row[field]):
  417. shape_matrix = str(row[field]).strip()
  418. break
  419. if shape_matrix is None and len(row) > 2:
  420. shape_matrix = str(row.iloc[2]).strip() if pd.notna(row.iloc[2]) else None
  421. # 获取占用格数
  422. for field in ['占用格数', 'gridCount', 'grid_count', '格数']:
  423. if field in row and pd.notna(row[field]):
  424. try:
  425. grid_count = int(float(row[field]))
  426. break
  427. except (ValueError, TypeError):
  428. pass
  429. if grid_count is None and len(row) > 3:
  430. try:
  431. grid_count = int(float(row.iloc[3])) if pd.notna(row.iloc[3]) else None
  432. except (ValueError, TypeError):
  433. pass
  434. # 获取成本倍数
  435. for field in ['成本倍数', 'costMultiplier', 'cost_multiplier', '倍数']:
  436. if field in row and pd.notna(row[field]):
  437. try:
  438. cost_multiplier = int(float(row[field]))
  439. break
  440. except (ValueError, TypeError):
  441. pass
  442. if cost_multiplier is None and len(row) > 4:
  443. try:
  444. cost_multiplier = int(float(row.iloc[4])) if pd.notna(row.iloc[4]) else None
  445. except (ValueError, TypeError):
  446. pass
  447. # 获取描述
  448. for field in ['描述', 'description', 'Description', '说明']:
  449. if field in row and pd.notna(row[field]):
  450. description = str(row[field]).strip()
  451. break
  452. if description is None and len(row) > 5:
  453. description = str(row.iloc[5]).strip() if pd.notna(row.iloc[5]) else None
  454. # 如果有有效的形状ID,则创建形状配置
  455. if shape_id:
  456. # 解析形状矩阵
  457. shape_array = self._parse_shape_matrix(shape_matrix)
  458. block_shape = {
  459. "id": shape_id,
  460. "name": shape_name or shape_id,
  461. "shape": shape_array,
  462. "gridCount": grid_count or len([cell for row in shape_array for cell in row if cell == 1]),
  463. "costMultiplier": cost_multiplier or grid_count or 1,
  464. "description": description or f"{shape_name or shape_id}形状"
  465. }
  466. block_shapes.append(block_shape)
  467. print(f"✓ 添加方块形状配置: {shape_id} ({shape_name})")
  468. return block_shapes
  469. except Exception as e:
  470. print(f"解析方块形状配置失败: {e}")
  471. return []
  472. def _parse_shape_matrix(self, shape_matrix_str):
  473. """解析形状矩阵字符串为二维数组"""
  474. try:
  475. if not shape_matrix_str:
  476. return [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
  477. shape_matrix_str = str(shape_matrix_str).strip()
  478. # 尝试解析JSON格式的矩阵字符串,如 "[0, 1, 0, 0], [1, 1, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0]"
  479. if '[' in shape_matrix_str and ']' in shape_matrix_str:
  480. try:
  481. # 添加外层方括号使其成为有效的JSON数组
  482. json_str = '[' + shape_matrix_str + ']'
  483. import json
  484. shape_array = json.loads(json_str)
  485. # 确保是4x4矩阵
  486. while len(shape_array) < 4:
  487. shape_array.append([0, 0, 0, 0])
  488. for i in range(len(shape_array)):
  489. if len(shape_array[i]) < 4:
  490. shape_array[i].extend([0] * (4 - len(shape_array[i])))
  491. shape_array[i] = shape_array[i][:4]
  492. return shape_array[:4]
  493. except (json.JSONDecodeError, ValueError) as e:
  494. print(f"JSON解析失败: {e}, 尝试其他解析方式")
  495. # 按换行符分割行(原有逻辑保留作为备用)
  496. lines = shape_matrix_str.split('\n')
  497. shape_array = []
  498. for line in lines:
  499. line = line.strip()
  500. if line:
  501. # 将每个字符转换为数字
  502. row = [int(char) for char in line if char in '01']
  503. # 确保每行有4个元素
  504. while len(row) < 4:
  505. row.append(0)
  506. shape_array.append(row[:4]) # 只取前4个元素
  507. # 确保有4行
  508. while len(shape_array) < 4:
  509. shape_array.append([0, 0, 0, 0])
  510. return shape_array[:4] # 只取前4行
  511. except Exception as e:
  512. print(f"解析形状矩阵失败: {e}, 使用默认矩阵")
  513. return [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
  514. def merge_weapon_configs(self, existing_config, excel_config):
  515. """合并现有JSON配置和Excel配置"""
  516. try:
  517. print("开始合并武器配置...")
  518. # 创建现有武器的映射表(按ID索引)
  519. existing_weapons_map = {}
  520. for weapon in existing_config.get('weapons', []):
  521. weapon_id = weapon.get('id')
  522. if weapon_id:
  523. existing_weapons_map[weapon_id] = weapon
  524. print(f"现有武器数量: {len(existing_weapons_map)}")
  525. print(f"Excel武器数量: {len(excel_config.get('weapons', []))}")
  526. # 处理Excel中的武器数据
  527. merged_weapons = []
  528. for excel_weapon in excel_config.get('weapons', []):
  529. weapon_id = excel_weapon.get('ID') or excel_weapon.get('id')
  530. if not weapon_id:
  531. continue
  532. # 转换Excel数据为标准格式
  533. converted_weapon = self._convert_weapon_data(
  534. excel_weapon,
  535. existing_weapons_map.get(weapon_id)
  536. )
  537. if converted_weapon:
  538. merged_weapons.append(converted_weapon)
  539. print(f"✓ 处理武器: {weapon_id}")
  540. # 添加Excel中没有但现有配置中存在的武器
  541. excel_weapon_ids = {w.get('ID') or w.get('id') for w in excel_config.get('weapons', [])}
  542. for weapon_id, existing_weapon in existing_weapons_map.items():
  543. if weapon_id not in excel_weapon_ids:
  544. merged_weapons.append(existing_weapon)
  545. print(f"✓ 保留现有武器: {weapon_id}")
  546. # 构建最终配置
  547. merged_config = existing_config.copy()
  548. merged_config['weapons'] = merged_weapons
  549. # 合并稀有度权重
  550. if 'rarityWeights' in excel_config:
  551. merged_config['rarityWeights'] = excel_config['rarityWeights']
  552. print("✓ 更新稀有度权重配置")
  553. # 合并方块形状配置
  554. if 'blockSizes' in excel_config:
  555. merged_config['blockSizes'] = excel_config['blockSizes']
  556. print(f"✓ 更新方块形状配置,共{len(excel_config['blockSizes'])}个形状")
  557. print(f"合并完成,最终武器数量: {len(merged_weapons)}")
  558. return merged_config
  559. except Exception as e:
  560. print(f"合并武器配置失败: {e}")
  561. return existing_config
  562. def _convert_weapon_data(self, item, existing_weapon=None):
  563. """转换武器数据格式"""
  564. try:
  565. # 支持中英文字段名
  566. weapon_id = item.get('id', item.get('ID', ''))
  567. weapon_name = item.get('name', item.get('名称', ''))
  568. if not weapon_id:
  569. print(f"跳过无效武器数据: 缺少武器ID - {item}")
  570. return None
  571. # 获取基础属性
  572. damage = item.get('damage', item.get('伤害', 10))
  573. fire_rate = item.get('fireRate', item.get('射速', 1.0))
  574. weapon_range = item.get('range', item.get('射程', 100))
  575. bullet_speed = item.get('bulletSpeed', item.get('子弹速度', 100))
  576. weapon_type = item.get('type', item.get('类型', ''))
  577. rarity = item.get('rarity', item.get('稀有度', ''))
  578. weight = item.get('weight', item.get('权重', 1))
  579. # 推断武器类型和稀有度(如果为空)
  580. if not weapon_type:
  581. weapon_type = self._infer_weapon_type(weapon_id)
  582. if not rarity:
  583. rarity = self._infer_rarity(damage)
  584. # 根据稀有度设置权重
  585. if weight == 1:
  586. rarity_weights = {'common': 30, 'uncommon': 20, 'rare': 15, 'epic': 8}
  587. weight = rarity_weights.get(rarity, 20)
  588. # 构建基础武器配置
  589. result = {
  590. 'id': weapon_id,
  591. 'name': weapon_name,
  592. 'type': weapon_type,
  593. 'rarity': rarity,
  594. 'weight': weight,
  595. 'stats': {
  596. 'damage': damage,
  597. 'fireRate': fire_rate,
  598. 'range': weapon_range,
  599. 'bulletSpeed': min(bullet_speed, 50) # 限制子弹速度
  600. }
  601. }
  602. # 如果有现有武器配置,保留其bulletConfig和visualConfig
  603. if existing_weapon:
  604. if 'bulletConfig' in existing_weapon:
  605. result['bulletConfig'] = existing_weapon['bulletConfig']
  606. print(f"为武器 {weapon_id} 保留现有的bulletConfig")
  607. else:
  608. result['bulletConfig'] = self._generate_bullet_config(weapon_id, weapon_type, damage, weapon_range)
  609. if 'visualConfig' in existing_weapon:
  610. result['visualConfig'] = existing_weapon['visualConfig']
  611. print(f"为武器 {weapon_id} 保留现有的visualConfig")
  612. else:
  613. result['visualConfig'] = self._generate_visual_config(weapon_id, weapon_name)
  614. else:
  615. # 生成默认配置
  616. result['bulletConfig'] = self._generate_bullet_config(weapon_id, weapon_type, damage, weapon_range)
  617. result['visualConfig'] = self._generate_visual_config(weapon_id, weapon_name)
  618. # 添加升级配置(如果Excel中有)
  619. if 'upgradeConfig' in item:
  620. result['upgradeConfig'] = item['upgradeConfig']
  621. print(f"为武器 {weapon_id} 添加升级配置")
  622. # 添加游戏内成本配置(如果Excel中有)
  623. if 'inGameCostConfig' in item:
  624. result['inGameCostConfig'] = item['inGameCostConfig']
  625. print(f"为武器 {weapon_id} 添加游戏内成本配置")
  626. return result
  627. except Exception as e:
  628. print(f"转换武器数据失败: {e} - 数据: {item}")
  629. return None
  630. def _infer_weapon_type(self, weapon_id):
  631. """根据武器ID推断武器类型"""
  632. if 'shotgun' in weapon_id or 'cactus' in weapon_id:
  633. return 'shotgun'
  634. elif 'bomb' in weapon_id or 'pepper' in weapon_id:
  635. return 'explosive'
  636. elif 'missile' in weapon_id:
  637. return 'homing_missile'
  638. elif 'boomerang' in weapon_id:
  639. return 'boomerang'
  640. elif 'saw' in weapon_id:
  641. return 'ricochet_piercing'
  642. elif 'carrot' in weapon_id:
  643. return 'piercing'
  644. else:
  645. return 'single_shot'
  646. def _infer_rarity(self, damage):
  647. """根据伤害推断稀有度"""
  648. if damage >= 60:
  649. return 'epic'
  650. elif damage >= 40:
  651. return 'rare'
  652. elif damage >= 25:
  653. return 'uncommon'
  654. else:
  655. return 'common'
  656. def _generate_bullet_config(self, weapon_id, weapon_type, damage, weapon_range):
  657. """生成子弹配置"""
  658. # 基础配置模板
  659. base_config = {
  660. 'count': {'type': 'single', 'amount': 1, 'spreadAngle': 0, 'burstCount': 1, 'burstDelay': 0},
  661. 'trajectory': {'type': 'straight', 'speed': 200, 'gravity': 0, 'arcHeight': 0, 'homingStrength': 0, 'homingDelay': 0},
  662. 'hitEffects': [{'type': 'normal_damage', 'priority': 1, 'damage': damage}],
  663. 'lifecycle': {'type': 'hit_destroy', 'maxLifetime': 5.0, 'penetration': 1, 'ricochetCount': 0, 'returnToOrigin': False},
  664. 'visual': {
  665. 'bulletImages': f'images/PlantsSprite/{sprite_id}',
  666. 'hitEffect': 'Animation/WeaponTx/tx0002/tx0002',
  667. 'trailEffect': True
  668. }
  669. }
  670. # 根据武器类型调整配置
  671. if weapon_type == 'shotgun':
  672. base_config['count'] = {'type': 'spread', 'amount': 5, 'spreadAngle': 30, 'burstCount': 1, 'burstDelay': 0}
  673. base_config['lifecycle']['type'] = 'range_limit'
  674. base_config['lifecycle']['maxRange'] = weapon_range * 2
  675. elif weapon_type == 'piercing':
  676. base_config['hitEffects'] = [{'type': 'pierce_damage', 'priority': 1, 'damage': damage, 'pierceCount': 999}]
  677. base_config['lifecycle'] = {'type': 'range_limit', 'maxLifetime': 5.0, 'penetration': 999, 'ricochetCount': 0, 'returnToOrigin': False, 'maxRange': weapon_range * 2}
  678. elif weapon_type == 'explosive':
  679. base_config['trajectory']['type'] = 'arc'
  680. base_config['hitEffects'] = [{'type': 'explosion', 'priority': 1, 'damage': damage + 20, 'radius': 100, 'delay': 0.1}]
  681. base_config['lifecycle']['type'] = 'ground_impact'
  682. base_config['visual']['hitEffect'] = 'Animation/WeaponTx/tx0007/tx0007'
  683. base_config['visual']['explosionEffect'] = 'Animation/WeaponTx/tx0007/tx0007'
  684. return base_config
  685. def _generate_visual_config(self, weapon_id, weapon_name):
  686. """生成视觉配置"""
  687. # 根据武器ID生成图片编号
  688. weapon_sprite_map = {
  689. 'pea_shooter': '001-1',
  690. 'sharp_carrot': '002',
  691. 'saw_grass': '003',
  692. 'watermelon_bomb': '007',
  693. 'boomerang_plant': '004',
  694. 'hot_pepper': '005',
  695. 'cactus_shotgun': '008',
  696. 'okra_missile': '006',
  697. 'mace_club': '009'
  698. }
  699. sprite_id = weapon_sprite_map.get(weapon_id, '001')
  700. return {
  701. 'weaponSprites': f'images/PlantsSprite/{sprite_id}',
  702. 'fireSound': f'audio/{weapon_id}_shot'
  703. }
  704. def backup_json_config(self):
  705. """备份现有JSON配置"""
  706. try:
  707. if self.json_file.exists():
  708. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  709. backup_file = self.json_file.parent / f"{self.json_file.stem}_backup_{timestamp}.json"
  710. with open(self.json_file, 'r', encoding='utf-8') as src:
  711. with open(backup_file, 'w', encoding='utf-8') as dst:
  712. dst.write(src.read())
  713. print(f"配置已备份到: {backup_file}")
  714. return backup_file
  715. else:
  716. print("JSON文件不存在,无需备份")
  717. return None
  718. except Exception as e:
  719. print(f"备份配置失败: {e}")
  720. return None
  721. def save_json_config(self, config):
  722. """保存配置到JSON文件"""
  723. try:
  724. # 确保目录存在
  725. self.json_file.parent.mkdir(parents=True, exist_ok=True)
  726. with open(self.json_file, 'w', encoding='utf-8') as f:
  727. json.dump(config, f, ensure_ascii=False, indent=2)
  728. print(f"配置已保存到: {self.json_file}")
  729. return True
  730. except Exception as e:
  731. print(f"保存JSON文件失败: {e}")
  732. return False
  733. def import_weapon_config(self):
  734. """导入武器配置的主方法"""
  735. try:
  736. print("开始导入武器配置...")
  737. # 1. 加载现有JSON配置
  738. existing_config = self.load_existing_json_config()
  739. # 2. 读取Excel配置
  740. excel_sheets = self.read_excel_config()
  741. # 3. 解析Excel数据
  742. excel_config = self.parse_weapon_multi_sheet_data(excel_sheets)
  743. # 4. 合并配置
  744. merged_config = self.merge_weapon_configs(existing_config, excel_config)
  745. # 5. 备份现有配置
  746. self.backup_json_config()
  747. # 6. 保存新配置
  748. if self.save_json_config(merged_config):
  749. print("武器配置导入成功!")
  750. return True
  751. else:
  752. print("武器配置保存失败!")
  753. return False
  754. except Exception as e:
  755. print(f"导入武器配置失败: {e}")
  756. return False
  757. def sync_json_to_excel(self):
  758. """将JSON配置同步到Excel文件"""
  759. try:
  760. print("开始将JSON配置同步到Excel文件...")
  761. # 导入生成器模块
  762. from generate_excel_from_json import WeaponExcelGenerator
  763. # 创建Excel生成器
  764. generator = WeaponExcelGenerator(
  765. json_file_path=str(self.json_file),
  766. excel_output_path=str(self.excel_file)
  767. )
  768. # 生成Excel文件
  769. success = generator.generate_excel_file()
  770. if success:
  771. print("✓ JSON配置已成功同步到Excel文件")
  772. return True
  773. else:
  774. print("✗ JSON配置同步到Excel文件失败")
  775. return False
  776. except Exception as e:
  777. print(f"同步JSON到Excel失败: {e}")
  778. return False
  779. def sync_excel_to_json(self):
  780. """将Excel配置同步到JSON文件"""
  781. try:
  782. print("开始将Excel配置同步到JSON文件...")
  783. # 使用现有的导入方法
  784. success = self.import_weapon_config()
  785. if success:
  786. print("✓ Excel配置已成功同步到JSON文件")
  787. return True
  788. else:
  789. print("✗ Excel配置同步到JSON文件失败")
  790. return False
  791. except Exception as e:
  792. print(f"同步Excel到JSON失败: {e}")
  793. return False
  794. def show_sync_menu(self):
  795. """显示同步菜单"""
  796. while True:
  797. print("\n武器配置同步工具")
  798. print("=" * 50)
  799. print("1. 从JSON同步到Excel (推荐)")
  800. print("2. 从Excel同步到JSON")
  801. print("3. 查看文件状态")
  802. print("4. 退出")
  803. print("=" * 50)
  804. choice = input("请选择操作 (1-4): ").strip()
  805. if choice == '1':
  806. print("\n正在从JSON同步到Excel...")
  807. success = self.sync_json_to_excel()
  808. if success:
  809. print("🎉 同步完成!Excel文件已更新")
  810. else:
  811. print("❌ 同步失败!")
  812. elif choice == '2':
  813. print("\n正在从Excel同步到JSON...")
  814. success = self.sync_excel_to_json()
  815. if success:
  816. print("🎉 同步完成!JSON文件已更新")
  817. else:
  818. print("❌ 同步失败!")
  819. elif choice == '3':
  820. self.show_file_status()
  821. elif choice == '4':
  822. print("\n再见!")
  823. break
  824. else:
  825. print("\n❌ 无效选择,请重新输入")
  826. def show_file_status(self):
  827. """显示文件状态"""
  828. print("\n文件状态信息")
  829. print("-" * 30)
  830. # JSON文件状态
  831. if self.json_file.exists():
  832. json_mtime = datetime.fromtimestamp(self.json_file.stat().st_mtime)
  833. print(f"✓ JSON文件: {self.json_file}")
  834. print(f" 最后修改: {json_mtime.strftime('%Y-%m-%d %H:%M:%S')}")
  835. try:
  836. with open(self.json_file, 'r', encoding='utf-8') as f:
  837. config = json.load(f)
  838. weapon_count = len(config.get('weapons', []))
  839. print(f" 武器数量: {weapon_count}")
  840. except Exception as e:
  841. print(f" 读取失败: {e}")
  842. else:
  843. print(f"❌ JSON文件不存在: {self.json_file}")
  844. print()
  845. # Excel文件状态
  846. if self.excel_file.exists():
  847. excel_mtime = datetime.fromtimestamp(self.excel_file.stat().st_mtime)
  848. print(f"✓ Excel文件: {self.excel_file}")
  849. print(f" 最后修改: {excel_mtime.strftime('%Y-%m-%d %H:%M:%S')}")
  850. try:
  851. if PANDAS_AVAILABLE:
  852. sheets = pd.read_excel(self.excel_file, sheet_name=None)
  853. print(f" 工作表数量: {len(sheets)}")
  854. print(f" 工作表名称: {list(sheets.keys())}")
  855. else:
  856. print(" 无法读取详细信息 (pandas未安装)")
  857. except Exception as e:
  858. print(f" 读取失败: {e}")
  859. else:
  860. print(f"❌ Excel文件不存在: {self.excel_file}")
  861. def main():
  862. """主函数"""
  863. print("武器配置管理器")
  864. print("=" * 50)
  865. # 创建武器配置管理器
  866. manager = WeaponConfigManager()
  867. # 显示同步菜单
  868. manager.show_sync_menu()
  869. if __name__ == "__main__":
  870. main()