OpenTTD-China-Set / China-Set-Trains

The Train sector of the China Set of OpenTTD.
GNU General Public License v2.0
12 stars 6 forks source link

Codechange: switch from number ids to text ids #57

Open WenSimEHRP opened 3 months ago

WenSimEHRP commented 3 months ago

NMLC is able to handle vehicle ids as text, so to make them more understandable it is a good idea to switch from number ids to text ids. md5hashes

df5e53166e2b0bb126ddc36d30a37faa *chinasettrains.grf (changed)
df5e53166e2b0bb126ddc36d30a37faa *chinasettrains.grf (unchanged)

script used:

import glob
import re

vehid_dict = {}

with open("src/vehicleid.pnml", "r", encoding="utf-8-sig") as file:
    for line in file:
        pattern = re.compile(r"\s*item\s*\(\s*\w+\s*,\s*(\w+?)\s*,\s*(\d+)\s*\)")
        match = pattern.match(line)
        if match is None:
            continue
        # for ind, thing in enumerate(match.groups()):
        #     print(ind, thing)
        vehid_dict[match.groups()[1]] = match.groups()[0]

# print(vehid_dict)

files = glob.glob('**/*.pnml', recursive=True)

class PNMLFile:
    def __init__(self, path: str):
        self.path = path

    def replace(self):
        with open(self.path, "r", encoding="utf-8-sig") as file:
            newfile = []
            replaced = set()
            for i, line in enumerate(file):
                # use re to match all numbers in the line
                numbers = re.findall(r"\d+", line)
                for number in numbers:
                    # print(number)
                    if number in vehid_dict.keys():
                        replaced |= {number}
                        line = line.replace(number, vehid_dict[number])
                newfile.append(line)
            if replaced:
                replaced = sorted(replaced)
                replaced_str = ", ".join([f"{vehid} ({vehid_dict[vehid]})" for vehid in replaced])
                print(f"{self.path:<48}:{replaced_str}")
        with open(self.path, "w", encoding="utf-8") as file:
            file.writelines(newfile)

files = glob.glob('**/*.pnml', recursive=True)
# remove specific files in the files variable
files = [file for file in files if "vehicleid.pnml" not in file]

for file in files:
    pnml = PNMLFile(file)
    pnml.replace()
    # print(f"Replaced vehicle IDs in {file}")