WeaponScriptToWiki.py

Jump to navigation Jump to search

import os import re

  1. Utility functions for conversions

def kg_to_g(kg):

   return round(kg * 1000, 2)

def kg_to_grains(kg):

   return round(kg * 15432.36, 2)

def kg_to_lbs(kg):

   return round(kg * 2.20462, 2)
  1. Load the template file

def load_template(template_path):

   with open(template_path, "r", encoding="utf-8") as f:
       return f.read()
  1. Parse key-value pairs from script file

def parse_file(file_path):

   variables = {}
   with open(file_path, "r", encoding="utf-8") as f:
       for line in f:
           match = re.match(r'\s*"(.+?)"\s+"(.+?)"', line)
           if match:
               key, value = match.groups()
               variables[key.lower()] = value
   return variables
  1. Retrieve the printnameenglish value from the vietnam_english.txt file

def get_printname_english(printname):

   file_path = r"C:\Program Files (x86)\Steam\steamapps\common\Military Conflict - Vietnam\vietnam\resource\vietnam_english.txt"
   
   # Remove the leading "#" from printname
   printname = printname.lstrip('#')
   # Try opening the file with different encodings
   encodings = ["utf-8", "utf-16", "latin-1"]
   for enc in encodings:
       try:
           with open(file_path, "r", encoding=enc) as f:
               for line in f:
                   line = line.strip()
                   # Ensure the line is in the format we expect (e.g. "weapon_ammobox" "Ammunition Box")
                   match = re.match(r'^\s*"(.+?)"\s+"(.+?)"\s*$', line)
                   if match:
                       key, value = match.groups()
                       # If the key matches the printname, return the corresponding value
                       if key.lower() == printname.lower():
                           return value
       except UnicodeDecodeError:
           continue  # Try the next encoding if decoding fails
   print(f"Error: Unable to decode the file or find the key '{printname}'")
   return None
  1. Get the origin value and process it

def get_origin(origin):

   # Remove leading "#" and any other unwanted characters
   origin = origin.lstrip('#').replace("_", " ").title()
   return origin
  1. Preprocess calculations for the template

def preprocess_calculations(variables, file_name, folder_path):

   calculations = {}
   # Retrieve damage-related values (set default to 0 if not found)
   damage_generic = float(variables.get("damagegeneric", "0"))
   damage_head_multiplier = float(variables.get("damageheadmultiplier", "1"))
   damage_chest_multiplier = float(variables.get("damagechestmultiplier", "1"))
   damage_stomach_multiplier = float(variables.get("damagestomachmultiplier", "1"))
   damage_leg_multiplier = float(variables.get("damagelegmultiplier", "1"))
   damage_arm_multiplier = float(variables.get("damagearmmultiplier", "1"))
   # Calculate damage multipliers (only if damage_generic is greater than 0)
   if damage_generic > 0:
       calculations["damagegenericxdamageheadmultiplier"] = round(damage_generic * damage_head_multiplier, 2)
       calculations["damagegenericxdamagechestmultiplier"] = round(damage_generic * damage_chest_multiplier, 2)
       calculations["damagegenericxdamagestomachmultiplier"] = round(damage_generic * damage_stomach_multiplier, 2)
       calculations["damagegenericxdamagelegmultiplier"] = round(damage_generic * damage_leg_multiplier, 2)
       calculations["damagegenericxdamagearmmultiplier"] = round(damage_generic * damage_arm_multiplier, 2)
   else:
       calculations["damagegenericxdamageheadmultiplier"] = "N/A"
       calculations["damagegenericxdamagechestmultiplier"] = "N/A"
       calculations["damagegenericxdamagestomachmultiplier"] = "N/A"
       calculations["damagegenericxdamagelegmultiplier"] = "N/A"
       calculations["damagegenericxdamagearmmultiplier"] = "N/A"
   # Bayonet check
   has_bayonet = variables.get("hasbayonet", "0") == "1"
   calculations["hasbayonet"] = "YES" if has_bayonet else "NO"
   # Rifle grenade file check
   file_base_name = os.path.splitext(file_name)[0]
   rifle_grenade_file = os.path.join(folder_path, f"{file_base_name}_riflegrenade.txt")
   has_rifle_grenade = os.path.exists(rifle_grenade_file)
   calculations["hasriflegrenade"] = "YES" if has_rifle_grenade else "NO"
   # Weight conversions
   bullet_weight = float(variables.get("bullet_weight", "0"))
   weight = float(variables.get("weight", "0"))
   print(f"DEBUG: Bullet weight in kg: {bullet_weight}")  # Debug print
   calculations["bullet_weight"] = kg_to_g(bullet_weight)
   calculations["bullet_weightingr"] = kg_to_grains(bullet_weight)  # Ensure conversion to grains
   calculations["weightinlbs"] = kg_to_lbs(weight)
   # ExtraBulletChamber check
   calculations["extrabulletchamber"] = variables.get("extrabulletchamber", "0")
   # File name replacement (ensure base name without extension)
   calculations["filename"] = file_base_name
   # Get the printname and replace with the appropriate english translation if found
   printname = variables.get("printname", "").lstrip("#")  # Strip the leading "#" here as well
   printname_english = get_printname_english(printname)
   if printname_english:
       calculations["printnameenglish"] = printname_english
   else:
       calculations["printnameenglish"] = printname
   # Get the origin and process it
   origin = variables.get("origin", "")
   calculations["origin"] = get_origin(origin)
   return calculations
  1. Replace placeholders in the template

def replace_placeholders(template, variables, calculations):

   result = template
   # Replace placeholders with variables or calculations
   for placeholder in re.findall(r'""([^"]+)""', result):
       # Check if placeholder is "FILENAME" and replace it with the file base name
       if placeholder.lower() == "filename":
           value = calculations["filename"]
       elif placeholder.lower() == "bullet_weightingr":  # Ensure correct grains conversion handling
           value = str(calculations["bullet_weightingr"])  # Correct grains replacement
       elif placeholder.lower() == "extrabulletchamber":
           # Only add [[]] if extra_bullet_chamber is not "0"
           extra_bullet_chamber = calculations.get("extrabulletchamber", "0")
           if extra_bullet_chamber == "0":
               value = ""  # Remove the [[]] if the chamber is not present
           else:
               value = "[[]]"  # Keep the [[]] if ExtraBulletChamber is set
       else:
           value = calculations.get(placeholder.lower(), variables.get(placeholder.lower(), "N/A"))
       # Replace the placeholder correctly (ensuring the exact match with quotes)
       result = result.replace(f'""{placeholder}""', str(value))
   # Handle ammo column, ensuring the proper format (no extra [[]] and correct ammo count)
   result = re.sub(r"(\d+)/(\d+)(\[\[\]\])?", lambda m: m.group(1) + (
       f"[[+{calculations['extrabulletchamber']}]]" if calculations["extrabulletchamber"] == "2" else
       f"+1" if calculations["extrabulletchamber"] == "1" else "") 
       + "/" + m.group(2), result)
   return result
  1. Process all script files

def process_files(template, scripts_path, output_path):

   for root, _, files in os.walk(scripts_path):
       for file in files:
           if not file.endswith(".txt"):
               continue
           input_file = os.path.join(root, file)
           file_name = os.path.basename(file)
           variables = parse_file(input_file)
           calculations = preprocess_calculations(variables, file_name, root)
           processed_template = replace_placeholders(template, variables, calculations)
           # Save processed template to output
           output_file = os.path.join(output_path, file_name)
           with open(output_file, "w", encoding="utf-8") as f:
               f.write(processed_template)
  1. Paths

template_path = r"C:\MCV\wiki\WikiTemplate.txt" scripts_path = r"C:\Program Files (x86)\Steam\steamapps\common\Military Conflict - Vietnam\vietnam\scripts" output_path = r"C:\MCV\wiki\output" os.makedirs(output_path, exist_ok=True)

  1. Main execution

template = load_template(template_path) process_files(template, scripts_path, output_path)

def remove_hash_from_files(directory):

   # Check if the directory exists
   if not os.path.exists(directory):
       print(f"The directory '{directory}' does not exist.")
       return
   
   # Iterate through all files in the directory
   for filename in os.listdir(directory):
       # Full path of the file
       file_path = os.path.join(directory, filename)
       
       # Process only text files
       if os.path.isfile(file_path) and filename.endswith('.txt'):
           try:
               # Read the file contents
               with open(file_path, 'r', encoding='utf-8') as file:
                   content = file.read()
               
               # Remove '#' characters
               updated_content = content.replace('#', )
               
               # Write the updated content back to the file
               with open(file_path, 'w', encoding='utf-8') as file:
                   file.write(updated_content)
               
               print(f"Processed file: {filename}")
           except Exception as e:
               print(f"Error processing file {filename}: {e}")
  1. Define the directory

directory = r"C:\MCV\wiki\output"

  1. Call the function

remove_hash_from_files(directory)


print("Processing complete.")