weapon_config_manager.py 54 KB

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