| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- 武器配置管理器
- 从config_manager.py中提取的武器相关配置管理功能
- 支持从Excel读取武器配置并与现有JSON配置合并
- """
- import json
- import os
- from pathlib import Path
- from datetime import datetime
- try:
- import pandas as pd
- PANDAS_AVAILABLE = True
- except ImportError:
- PANDAS_AVAILABLE = False
- print("警告: pandas未安装,无法处理Excel文件")
- class WeaponConfigManager:
- """武器配置管理器"""
-
- def __init__(self, excel_file_path=None, json_file_path=None):
- """初始化武器配置管理器
-
- Args:
- excel_file_path: Excel配置文件路径
- json_file_path: JSON配置文件路径
- """
- self.script_dir = Path(__file__).parent
-
- # 设置默认路径
- if excel_file_path is None:
- self.excel_file = self.script_dir / "方块武器配置" / "方块武器配置表.xlsx"
- else:
- self.excel_file = Path(excel_file_path)
-
- if json_file_path is None:
- self.json_file = self.script_dir.parent / "weapons.json"
- else:
- self.json_file = Path(json_file_path)
-
- print(f"Excel文件路径: {self.excel_file}")
- print(f"JSON文件路径: {self.json_file}")
-
- # 武器配置映射
- self.weapon_mapping = {
- 'format_type': 'horizontal',
- 'param_types': {
- 'ID': str,
- '名称': str,
- '类型': str,
- '稀有度': str,
- '权重': int,
- '伤害': int,
- '射速': float,
- '射程': int,
- '子弹速度': int,
- # 方块价格配置字段
- '基础每格成本': int,
- 'I形状成本': int,
- 'H-I形状成本': int,
- 'L形状成本': int,
- 'S形状成本': int,
- 'D-T形状成本': int,
- # 英文字段支持
- 'id': str,
- 'name': str,
- 'type': str,
- 'rarity': str,
- 'weight': int,
- 'damage': int,
- 'fireRate': float,
- 'range': int,
- 'bulletSpeed': int,
- 'baseCost': int,
- 'I_shape_cost': int,
- 'HI_shape_cost': int,
- 'L_shape_cost': int,
- 'S_shape_cost': int,
- 'DT_shape_cost': int
- }
- }
-
- def load_existing_json_config(self):
- """加载现有的JSON配置文件"""
- try:
- if self.json_file.exists():
- with open(self.json_file, 'r', encoding='utf-8') as f:
- config = json.load(f)
- print(f"成功加载现有JSON配置,包含 {len(config.get('weapons', []))} 个武器")
- return config
- else:
- print(f"JSON文件不存在,将创建新配置: {self.json_file}")
- return {'weapons': [], 'blockSizes': [], 'rarityWeights': {}}
- except Exception as e:
- print(f"加载JSON配置失败: {e}")
- return {'weapons': [], 'blockSizes': [], 'rarityWeights': {}}
-
- def read_excel_config(self):
- """读取Excel配置文件"""
- if not PANDAS_AVAILABLE:
- raise Exception("pandas未安装,无法读取Excel文件")
-
- if not self.excel_file.exists():
- raise Exception(f"Excel文件不存在: {self.excel_file}")
-
- try:
- # 读取所有工作表
- all_sheets = pd.read_excel(self.excel_file, sheet_name=None)
- print(f"成功读取Excel文件,包含工作表: {list(all_sheets.keys())}")
- return all_sheets
- except Exception as e:
- raise Exception(f"读取Excel文件失败: {e}")
-
- def parse_weapon_multi_sheet_data(self, all_sheets_data):
- """解析武器配置表的多工作表数据"""
- weapons_config = {'weapons': []}
-
- try:
- # 解析武器基础配置工作表
- base_sheet = None
- for sheet_name in ['武器基础配置', 'Weapon Config', 'weapons', '武器配置']:
- if sheet_name in all_sheets_data:
- base_sheet = all_sheets_data[sheet_name]
- break
-
- if base_sheet is not None:
- base_config = self.parse_config_data(base_sheet)
- if 'items' in base_config:
- weapons_config['weapons'] = base_config['items']
- print(f"成功解析武器基础配置,共{len(base_config['items'])}个武器")
-
- # 解析武器升级费用配置工作表
- upgrade_cost_sheet = None
- for sheet_name in ['武器升级费用配置', 'Weapon Upgrade Cost', 'upgrade_costs', '升级费用']:
- if sheet_name in all_sheets_data:
- upgrade_cost_sheet = all_sheets_data[sheet_name]
- print(f"找到升级费用配置工作表: {sheet_name}")
- break
-
- if upgrade_cost_sheet is not None:
- self._parse_upgrade_cost_data(upgrade_cost_sheet, weapons_config['weapons'])
-
- # 解析游戏内成本配置工作表
- cost_sheet = None
- for sheet_name in ['游戏内成本配置', 'In Game Cost', 'cost_config', '成本配置']:
- if sheet_name in all_sheets_data:
- cost_sheet = all_sheets_data[sheet_name]
- print(f"找到游戏内成本配置工作表: {sheet_name}")
- break
-
- if cost_sheet is not None:
- self._parse_cost_config_data(cost_sheet, weapons_config['weapons'])
-
- # 解析稀有度权重配置工作表
- rarity_sheet = None
- for sheet_name in ['稀有度权重', 'Rarity Weights', 'rarity_weights', '权重配置']:
- if sheet_name in all_sheets_data:
- rarity_sheet = all_sheets_data[sheet_name]
- print(f"找到稀有度权重配置工作表: {sheet_name}")
- break
-
- if rarity_sheet is not None:
- weapons_config['rarityWeights'] = self._parse_rarity_weights_data(rarity_sheet)
-
- return weapons_config
-
- except Exception as e:
- print(f"解析武器配置失败: {e}")
- return {'weapons': []}
-
- def parse_config_data(self, df):
- """解析配置数据"""
- try:
- items = []
-
- # 检查第一行是否为表头
- first_row = df.iloc[0] if len(df) > 0 else None
- is_header = False
- if first_row is not None:
- first_cell = str(first_row.iloc[0]).strip() if len(first_row) > 0 else ""
- if first_cell in ['武器ID', 'ID', 'weapon_id', 'weaponId']:
- is_header = True
- print(f"检测到表头行,第一列内容: {first_cell}")
-
- for index, row in df.iterrows():
- if is_header and index == 0: # 跳过表头
- continue
-
- # 转换行数据为字典
- item = {}
- for col_index, value in enumerate(row):
- if col_index < len(df.columns):
- col_name = df.columns[col_index]
- if pd.notna(value) and str(value).strip():
- # 根据映射转换数据类型
- param_type = self.weapon_mapping['param_types'].get(col_name, str)
- try:
- if param_type == int:
- item[col_name] = int(float(value))
- elif param_type == float:
- item[col_name] = float(value)
- else:
- item[col_name] = str(value).strip()
- except (ValueError, TypeError):
- item[col_name] = str(value).strip()
-
- # 检查是否有有效的武器ID
- weapon_id = item.get('ID') or item.get('id') or item.get('武器ID')
- if weapon_id and str(weapon_id).strip():
- items.append(item)
-
- return {'items': items}
-
- except Exception as e:
- print(f"解析配置数据失败: {e}")
- return {'items': []}
-
- def _parse_upgrade_cost_data(self, upgrade_cost_sheet, weapons_list):
- """解析升级费用配置数据"""
- try:
- print(f"开始处理升级费用配置,工作表行数: {len(upgrade_cost_sheet)}")
- upgrade_cost_data = []
-
- # 检查第一行是否为表头
- first_row = upgrade_cost_sheet.iloc[0] if len(upgrade_cost_sheet) > 0 else None
- is_header = False
- if first_row is not None:
- first_cell = str(first_row.iloc[0]).strip() if len(first_row) > 0 else ""
- if first_cell in ['武器ID', 'ID', 'weapon_id', 'weaponId']:
- is_header = True
- print(f"检测到表头行,第一列内容: {first_cell}")
-
- for index, row in upgrade_cost_sheet.iterrows():
- if is_header and index == 0: # 跳过表头
- continue
-
- # 支持多种武器ID字段名
- weapon_id = None
- for id_field in ['武器ID', 'ID', 'weapon_id', 'weaponId']:
- if id_field in row and pd.notna(row[id_field]):
- weapon_id = row[id_field]
- break
-
- if weapon_id is None:
- weapon_id = row.iloc[0] if len(row) > 0 else None
-
- if weapon_id and str(weapon_id).strip():
- upgrade_levels = {}
- # 从第5列开始是等级1-10的费用,从第15列开始是等级1-10的伤害
- for level in range(1, 11):
- cost_col_index = 4 + (level - 1)
- damage_col_index = 14 + (level - 1)
-
- level_config = {}
-
- # 处理费用
- if cost_col_index < len(row):
- cost = row.iloc[cost_col_index]
- if cost and str(cost).strip() and str(cost) != 'nan':
- try:
- level_config['cost'] = int(float(cost))
- except (ValueError, TypeError):
- pass
-
- # 处理伤害
- if damage_col_index < len(row):
- damage = row.iloc[damage_col_index]
- if damage and str(damage).strip() and str(damage) != 'nan':
- try:
- level_config['damage'] = int(float(damage))
- except (ValueError, TypeError):
- pass
-
- if level_config:
- upgrade_levels[str(level)] = level_config
-
- if upgrade_levels:
- upgrade_cost_data.append({
- 'weapon_id': str(weapon_id).strip(),
- 'levels': upgrade_levels
- })
-
- # 将升级费用配置合并到武器数据中
- for weapon in weapons_list:
- weapon_id = weapon.get('ID', '') or weapon.get('id', '')
- if weapon_id:
- matching_upgrade = None
- for upgrade_data in upgrade_cost_data:
- if upgrade_data['weapon_id'] == weapon_id:
- matching_upgrade = upgrade_data
- break
-
- if matching_upgrade:
- weapon['upgradeConfig'] = {
- 'maxLevel': 10,
- 'levels': matching_upgrade['levels']
- }
- print(f"✓ 为武器 {weapon_id} 添加了升级费用配置")
-
- except Exception as e:
- print(f"解析升级费用配置失败: {e}")
-
- def _parse_cost_config_data(self, cost_sheet, weapons_list):
- """解析游戏内成本配置数据"""
- try:
- print(f"开始处理游戏内成本配置,工作表行数: {len(cost_sheet)}")
-
- # 检查第一行是否为表头
- first_row = cost_sheet.iloc[0] if len(cost_sheet) > 0 else None
- is_header = False
- if first_row is not None:
- first_cell = str(first_row.iloc[0]).strip() if len(first_row) > 0 else ""
- if first_cell in ['武器ID', 'ID', 'weapon_id', 'weaponId']:
- is_header = True
-
- for index, row in cost_sheet.iterrows():
- if is_header and index == 0: # 跳过表头
- continue
-
- # 获取武器ID
- weapon_id = None
- for id_field in ['武器ID', 'ID', 'weapon_id', 'weaponId']:
- if id_field in row and pd.notna(row[id_field]):
- weapon_id = str(row[id_field]).strip()
- break
-
- if weapon_id is None:
- weapon_id = str(row.iloc[0]).strip() if len(row) > 0 else None
-
- if weapon_id:
- # 查找对应的武器并添加成本配置
- for weapon in weapons_list:
- w_id = weapon.get('ID', '') or weapon.get('id', '')
- if w_id == weapon_id:
- # 构建成本配置
- base_cost = 5 # 默认基础成本
- shape_costs = {}
-
- # 读取基础成本
- for field in ['武器基础售价', 'baseCost', '基础成本']:
- if field in row and pd.notna(row[field]):
- try:
- base_cost = int(float(row[field]))
- break
- except (ValueError, TypeError):
- pass
-
- # 读取各形状成本
- shape_fields = {
- 'I': ['I形状', 'I_shape', 'I'],
- 'H-I': ['H-I形状', 'HI_shape', 'H-I'],
- 'L': ['L形状', 'L_shape', 'L'],
- 'S': ['S形状', 'S_shape', 'S'],
- 'D-T': ['D-T形状', 'DT_shape', 'D-T']
- }
-
- for shape_key, field_names in shape_fields.items():
- for field_name in field_names:
- if field_name in row and pd.notna(row[field_name]):
- try:
- shape_costs[shape_key] = int(float(row[field_name]))
- break
- except (ValueError, TypeError):
- pass
-
- weapon['inGameCostConfig'] = {
- 'baseCost': base_cost,
- 'shapeCosts': shape_costs
- }
- print(f"✓ 为武器 {weapon_id} 添加了游戏内成本配置")
- break
-
- except Exception as e:
- print(f"解析游戏内成本配置失败: {e}")
-
- def _parse_rarity_weights_data(self, rarity_sheet):
- """解析稀有度权重配置数据"""
- try:
- rarity_weights = {}
-
- # 检查第一行是否为表头
- first_row = rarity_sheet.iloc[0] if len(rarity_sheet) > 0 else None
- is_header = False
- if first_row is not None:
- first_cell = str(first_row.iloc[0]).strip() if len(first_row) > 0 else ""
- if first_cell in ['稀有度', 'rarity', 'Rarity']:
- is_header = True
-
- for index, row in rarity_sheet.iterrows():
- if is_header and index == 0: # 跳过表头
- continue
-
- # 获取稀有度和权重
- rarity = None
- weight = None
-
- for field in ['稀有度', 'rarity', 'Rarity']:
- if field in row and pd.notna(row[field]):
- rarity = str(row[field]).strip()
- break
-
- if rarity is None:
- rarity = str(row.iloc[0]).strip() if len(row) > 0 else None
-
- for field in ['权重', 'weight', 'Weight']:
- if field in row and pd.notna(row[field]):
- try:
- weight = int(float(row[field]))
- break
- except (ValueError, TypeError):
- pass
-
- if weight is None and len(row) > 1:
- try:
- weight = int(float(row.iloc[1]))
- except (ValueError, TypeError):
- pass
-
- if rarity and weight is not None:
- rarity_weights[rarity] = weight
- print(f"✓ 添加稀有度权重: {rarity} = {weight}")
-
- return rarity_weights
-
- except Exception as e:
- print(f"解析稀有度权重配置失败: {e}")
- return {}
-
- def merge_weapon_configs(self, existing_config, excel_config):
- """合并现有JSON配置和Excel配置"""
- try:
- print("开始合并武器配置...")
-
- # 创建现有武器的映射表(按ID索引)
- existing_weapons_map = {}
- for weapon in existing_config.get('weapons', []):
- weapon_id = weapon.get('id')
- if weapon_id:
- existing_weapons_map[weapon_id] = weapon
-
- print(f"现有武器数量: {len(existing_weapons_map)}")
- print(f"Excel武器数量: {len(excel_config.get('weapons', []))}")
-
- # 处理Excel中的武器数据
- merged_weapons = []
- for excel_weapon in excel_config.get('weapons', []):
- weapon_id = excel_weapon.get('ID') or excel_weapon.get('id')
- if not weapon_id:
- continue
-
- # 转换Excel数据为标准格式
- converted_weapon = self._convert_weapon_data(
- excel_weapon,
- existing_weapons_map.get(weapon_id)
- )
-
- if converted_weapon:
- merged_weapons.append(converted_weapon)
- print(f"✓ 处理武器: {weapon_id}")
-
- # 添加Excel中没有但现有配置中存在的武器
- excel_weapon_ids = {w.get('ID') or w.get('id') for w in excel_config.get('weapons', [])}
- for weapon_id, existing_weapon in existing_weapons_map.items():
- if weapon_id not in excel_weapon_ids:
- merged_weapons.append(existing_weapon)
- print(f"✓ 保留现有武器: {weapon_id}")
-
- # 构建最终配置
- merged_config = existing_config.copy()
- merged_config['weapons'] = merged_weapons
-
- # 合并稀有度权重
- if 'rarityWeights' in excel_config:
- merged_config['rarityWeights'] = excel_config['rarityWeights']
- print("✓ 更新稀有度权重配置")
-
- print(f"合并完成,最终武器数量: {len(merged_weapons)}")
- return merged_config
-
- except Exception as e:
- print(f"合并武器配置失败: {e}")
- return existing_config
-
- def _convert_weapon_data(self, item, existing_weapon=None):
- """转换武器数据格式"""
- try:
- # 支持中英文字段名
- weapon_id = item.get('id', item.get('ID', ''))
- weapon_name = item.get('name', item.get('名称', ''))
-
- if not weapon_id:
- print(f"跳过无效武器数据: 缺少武器ID - {item}")
- return None
-
- # 获取基础属性
- damage = item.get('damage', item.get('伤害', 10))
- fire_rate = item.get('fireRate', item.get('射速', 1.0))
- weapon_range = item.get('range', item.get('射程', 100))
- bullet_speed = item.get('bulletSpeed', item.get('子弹速度', 100))
- weapon_type = item.get('type', item.get('类型', ''))
- rarity = item.get('rarity', item.get('稀有度', ''))
- weight = item.get('weight', item.get('权重', 1))
-
- # 推断武器类型和稀有度(如果为空)
- if not weapon_type:
- weapon_type = self._infer_weapon_type(weapon_id)
-
- if not rarity:
- rarity = self._infer_rarity(damage)
-
- # 根据稀有度设置权重
- if weight == 1:
- rarity_weights = {'common': 30, 'uncommon': 20, 'rare': 15, 'epic': 8}
- weight = rarity_weights.get(rarity, 20)
-
- # 构建基础武器配置
- result = {
- 'id': weapon_id,
- 'name': weapon_name,
- 'type': weapon_type,
- 'rarity': rarity,
- 'weight': weight,
- 'stats': {
- 'damage': damage,
- 'fireRate': fire_rate,
- 'range': weapon_range,
- 'bulletSpeed': min(bullet_speed, 50) # 限制子弹速度
- }
- }
-
- # 如果有现有武器配置,保留其bulletConfig和visualConfig
- if existing_weapon:
- if 'bulletConfig' in existing_weapon:
- result['bulletConfig'] = existing_weapon['bulletConfig']
- print(f"为武器 {weapon_id} 保留现有的bulletConfig")
- else:
- result['bulletConfig'] = self._generate_bullet_config(weapon_id, weapon_type, damage, weapon_range)
-
- if 'visualConfig' in existing_weapon:
- result['visualConfig'] = existing_weapon['visualConfig']
- print(f"为武器 {weapon_id} 保留现有的visualConfig")
- else:
- result['visualConfig'] = self._generate_visual_config(weapon_id, weapon_name)
- else:
- # 生成默认配置
- result['bulletConfig'] = self._generate_bullet_config(weapon_id, weapon_type, damage, weapon_range)
- result['visualConfig'] = self._generate_visual_config(weapon_id, weapon_name)
-
- # 添加升级配置(如果Excel中有)
- if 'upgradeConfig' in item:
- result['upgradeConfig'] = item['upgradeConfig']
- print(f"为武器 {weapon_id} 添加升级配置")
-
- # 添加游戏内成本配置(如果Excel中有)
- if 'inGameCostConfig' in item:
- result['inGameCostConfig'] = item['inGameCostConfig']
- print(f"为武器 {weapon_id} 添加游戏内成本配置")
-
- return result
-
- except Exception as e:
- print(f"转换武器数据失败: {e} - 数据: {item}")
- return None
-
- def _infer_weapon_type(self, weapon_id):
- """根据武器ID推断武器类型"""
- if 'shotgun' in weapon_id or 'cactus' in weapon_id:
- return 'shotgun'
- elif 'bomb' in weapon_id or 'pepper' in weapon_id:
- return 'explosive'
- elif 'missile' in weapon_id:
- return 'homing_missile'
- elif 'boomerang' in weapon_id:
- return 'boomerang'
- elif 'saw' in weapon_id:
- return 'ricochet_piercing'
- elif 'carrot' in weapon_id:
- return 'piercing'
- else:
- return 'single_shot'
-
- def _infer_rarity(self, damage):
- """根据伤害推断稀有度"""
- if damage >= 60:
- return 'epic'
- elif damage >= 40:
- return 'rare'
- elif damage >= 25:
- return 'uncommon'
- else:
- return 'common'
-
- def _generate_bullet_config(self, weapon_id, weapon_type, damage, weapon_range):
- """生成子弹配置"""
- # 基础配置模板
- base_config = {
- 'count': {'type': 'single', 'amount': 1, 'spreadAngle': 0, 'burstCount': 1, 'burstDelay': 0},
- 'trajectory': {'type': 'straight', 'speed': 200, 'gravity': 0, 'arcHeight': 0, 'homingStrength': 0, 'homingDelay': 0},
- 'hitEffects': [{'type': 'normal_damage', 'priority': 1, 'damage': damage}],
- 'lifecycle': {'type': 'hit_destroy', 'maxLifetime': 5.0, 'penetration': 1, 'ricochetCount': 0, 'returnToOrigin': False},
- 'visual': {
- 'bulletImages': f'images/PlantsSprite/{sprite_id}',
- 'hitEffect': 'Animation/WeaponTx/tx0002/tx0002',
- 'trailEffect': True
- }
- }
-
- # 根据武器类型调整配置
- if weapon_type == 'shotgun':
- base_config['count'] = {'type': 'spread', 'amount': 5, 'spreadAngle': 30, 'burstCount': 1, 'burstDelay': 0}
- base_config['lifecycle']['type'] = 'range_limit'
- base_config['lifecycle']['maxRange'] = weapon_range * 2
- elif weapon_type == 'piercing':
- base_config['hitEffects'] = [{'type': 'pierce_damage', 'priority': 1, 'damage': damage, 'pierceCount': 999}]
- base_config['lifecycle'] = {'type': 'range_limit', 'maxLifetime': 5.0, 'penetration': 999, 'ricochetCount': 0, 'returnToOrigin': False, 'maxRange': weapon_range * 2}
- elif weapon_type == 'explosive':
- base_config['trajectory']['type'] = 'arc'
- base_config['hitEffects'] = [{'type': 'explosion', 'priority': 1, 'damage': damage + 20, 'radius': 100, 'delay': 0.1}]
- base_config['lifecycle']['type'] = 'ground_impact'
- base_config['visual']['hitEffect'] = 'Animation/WeaponTx/tx0007/tx0007'
- base_config['visual']['explosionEffect'] = 'Animation/WeaponTx/tx0007/tx0007'
-
- return base_config
-
- def _generate_visual_config(self, weapon_id, weapon_name):
- """生成视觉配置"""
- # 根据武器ID生成图片编号
- weapon_sprite_map = {
- 'pea_shooter': '001-1',
- 'sharp_carrot': '002',
- 'saw_grass': '003',
- 'watermelon_bomb': '007',
- 'boomerang_plant': '004',
- 'hot_pepper': '005',
- 'cactus_shotgun': '008',
- 'okra_missile': '006',
- 'mace_club': '009'
- }
-
- sprite_id = weapon_sprite_map.get(weapon_id, '001')
-
- return {
- 'weaponSprites': f'images/PlantsSprite/{sprite_id}',
- 'fireSound': f'audio/{weapon_id}_shot'
- }
-
- def backup_json_config(self):
- """备份现有JSON配置"""
- try:
- if self.json_file.exists():
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- backup_file = self.json_file.parent / f"{self.json_file.stem}_backup_{timestamp}.json"
-
- with open(self.json_file, 'r', encoding='utf-8') as src:
- with open(backup_file, 'w', encoding='utf-8') as dst:
- dst.write(src.read())
-
- print(f"配置已备份到: {backup_file}")
- return backup_file
- else:
- print("JSON文件不存在,无需备份")
- return None
- except Exception as e:
- print(f"备份配置失败: {e}")
- return None
-
- def save_json_config(self, config):
- """保存配置到JSON文件"""
- try:
- # 确保目录存在
- self.json_file.parent.mkdir(parents=True, exist_ok=True)
-
- with open(self.json_file, 'w', encoding='utf-8') as f:
- json.dump(config, f, ensure_ascii=False, indent=2)
- print(f"配置已保存到: {self.json_file}")
- return True
- except Exception as e:
- print(f"保存JSON文件失败: {e}")
- return False
-
- def import_weapon_config(self):
- """导入武器配置的主方法"""
- try:
- print("开始导入武器配置...")
-
- # 1. 加载现有JSON配置
- existing_config = self.load_existing_json_config()
-
- # 2. 读取Excel配置
- excel_sheets = self.read_excel_config()
-
- # 3. 解析Excel数据
- excel_config = self.parse_weapon_multi_sheet_data(excel_sheets)
-
- # 4. 合并配置
- merged_config = self.merge_weapon_configs(existing_config, excel_config)
-
- # 5. 备份现有配置
- self.backup_json_config()
-
- # 6. 保存新配置
- if self.save_json_config(merged_config):
- print("武器配置导入成功!")
- return True
- else:
- print("武器配置保存失败!")
- return False
-
- except Exception as e:
- print(f"导入武器配置失败: {e}")
- return False
- def main():
- """主函数"""
- print("武器配置管理器")
- print("=" * 50)
-
- # 创建武器配置管理器
- manager = WeaponConfigManager()
-
- # 导入配置
- success = manager.import_weapon_config()
-
- if success:
- print("\n✓ 武器配置导入完成")
- else:
- print("\n✗ 武器配置导入失败")
- if __name__ == "__main__":
- main()
|