weapon_config_manager.py 53 KB

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