From c2f823f11e3058a8f64648548a63d25564b619dd Mon Sep 17 00:00:00 2001 From: oitsjustjose Date: Sat, 28 Aug 2021 23:10:30 -0500 Subject: [PATCH] Initial commit --- .gitignore | 6 + README.md | 13 ++ scripts/batch/slabs.bat | 5 + src/modules/druidcraft_woodcutter.py | 200 +++++++++++++++++++++++++++ src/modules/slab_to_block.py | 65 +++++++++ src/util/file.py | 104 ++++++++++++++ 6 files changed, 393 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 scripts/batch/slabs.bat create mode 100644 src/modules/druidcraft_woodcutter.py create mode 100644 src/modules/slab_to_block.py create mode 100644 src/util/file.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f69b6e8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +__pycache__ +.DS_Store +.vscode +*.txt +*.csv +**/out \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..7f7b5b2 --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# Mod Compat Utilities + +This library is filled with Python packages that are useful in order to get you up and running with inter-mod compatability within a Vanilla datapack. The datapack you produce using the files output (into `./out/**/*.json`) can be loaded into every world you play using the [Global Resource and Datapacks Mod](https://www.curseforge.com/minecraft/mc-mods/drp-global-datapack). + +## Setup + +Setup for this is pretty straight forward. + +1. Install Python for your current OS: https://www.python.org/downloads/ +2. Download this repo by clicking the Green "Clone" button above and choosing `Download Zip` +3. Run the Shell/Batch file (Batch for Windows, Shell for Linux/MacOS/WSL/Other) that corresponds to the data you wish to create (i.e. if I was on Windows wanting to create a set of recipes to turn 2 slabs into their solid-block counterpart, I'd run `./scripts/batch/slabs.bat` by double-clicking it.) + +## Usage diff --git a/scripts/batch/slabs.bat b/scripts/batch/slabs.bat new file mode 100644 index 0000000..56ee3d0 --- /dev/null +++ b/scripts/batch/slabs.bat @@ -0,0 +1,5 @@ +@ECHO OFF + +cd ../.. + +PAUSE \ No newline at end of file diff --git a/src/modules/druidcraft_woodcutter.py b/src/modules/druidcraft_woodcutter.py new file mode 100644 index 0000000..1f85578 --- /dev/null +++ b/src/modules/druidcraft_woodcutter.py @@ -0,0 +1,200 @@ +""" +Author: Jose Stovall | oitsjustjose +A script for iterating over every plank in the game (provided by CraftDumper) + Uses this plank to create compatibility for all Woodcutting recipes from Druidcraft +""" + +import json +import os +from typing import List, Tuple, Union + + +class Block: + """A block constructor that makes my life easier""" + + def __init__(self, resource_location: str): + modid, path = resource_location.replace("\n", "").split(":") + self._modid = modid + self._path = path + + def get_modid(self) -> str: + """Gets the modid of the Block instance""" + return self._modid + + def get_path(self) -> str: + """Gets the path of the Block instance""" + return self._path + + def get_resource_location(self) -> str: + """Gets the resource_location of the Block instance""" + return f"{self._modid}:{self._path}" + + def __eq__(self, o: object) -> bool: + return ( + isinstance(o, Block) + and o.get_modid() == self.get_modid() + and o.get_path() == self.get_path() + ) + + def __str__(self) -> str: + return self.get_resource_location() + + def __unicode__(self): + return self.get_resource_location() + + def __repr__(self): + return self.get_resource_location() + + +def try_get( + all_blocks: List[Block], source: Block, variant: str, tag_name: str +) -> Union[Block, None]: + """ + Tries to get the fence for a given block if it can. + If it cannot then it it will return None + """ + modid = source.get_modid() + path = source.get_path() + base: str = ( + source.get_resource_location() + .replace(f"_{tag_name}", "") + .replace(f"{tag_name}_", "") + ) + + variants: List[Block] = [ + Block(f"{base}_{variant}"), + Block(f"{variant}_{base}"), + Block(f"{base}_{tag_name}_{variant}"), + Block(f"{variant}_{base}_{tag_name}"), + Block(f"{modid}:{variant}_{path}"), + # modid:{a}_log -> modid:{a}_stripped_log + Block(f"{modid}:{path.replace('_log', '')}_{variant}_{tag_name}"), + ] + + for var in variants: + if var in all_blocks: + return var + return None + + +def generate_plank_crafting(all_blocks: List[Block]) -> None: + """ + Generates the plank -> recipes for Woodcutting + """ + variant_map = { + "slab": 2, + "stair": 1, + "stairs": 1, + "fence": 1, + "fence_gate": 1, + "gate": 1, + "button": 4, + "door": 1, + "sign": 1, + "trapdoor": 2, + "pressure_plate": 3, + } + + anti_matchers = [ + "vertical", + "slab", + "stair", + "fence", + "gate", + "chipped:", + "minecraft:", + "quark:", + "druidcraft:", + ] + + # Filter out any things we don't want to see in the anti_matchers list + planks: List[Block] = list( + filter( + lambda x: "planks" in x.get_resource_location() + and not any(y in x.get_resource_location() for y in anti_matchers), + all_blocks, + ) + ) + + created_count = 0 + + for plank in planks: + for_plank: List[Tuple[Block, int]] = [ + (try_get(all_blocks, plank, var, "planks"), cnt) + for var, cnt in variant_map.items() + ] + + for_plank: List[Tuple[Block, int]] = list( + filter(lambda x: x[0] is not None, for_plank) + ) + + for (result, count) in for_plank: + filename = f"{result.get_path()}_from_woodcutting_{plank.get_path()}.json" + data = { + "type": "druidcraft:woodcutting", + "ingredient": {"item": plank.get_resource_location()}, + "result": result.get_resource_location(), + "count": count, + } + + with open(f"./out/woodcutting/{filename}", "w") as file: + file.write(json.dumps(data)) + + created_count += len(for_plank) + print(f"Created {created_count} new plank recipes for woodcutter") + + +def generate_log_stripping(all_blocks: List[Block]) -> None: + """ + Generates Woodcutting recipes to strip logs + """ + logs: List[Block] = list( + filter( + lambda x: x.get_resource_location().endswith("log") + and "minecraft:" not in x.get_resource_location() + and "druidcraft:" not in x.get_resource_location() + and "stripped" not in x.get_resource_location(), + all_blocks, + ) + ) + + created_count = 0 + + for log in logs: + stripped_log = try_get(all_blocks, log, "stripped", "log") + if not stripped_log: + print(f"Could not find stripped variant of {log.get_resource_location()}") + continue + + filename = f"{stripped_log.get_path()}_from_{log.get_path()}_stripping_woodcutting.json" + data = { + "type": "druidcraft:woodcutting", + "ingredient": {"item": log.get_resource_location()}, + "result": stripped_log.get_resource_location(), + "count": 1, + } + + with open(f"./out/woodcutting/{filename}", "w") as file: + file.write(json.dumps(data)) + + created_count += 1 + print(f"Created {created_count} new log -> stripped log recipes") + + +def main() -> None: + """ + The main Python run-function for this file + """ + all_blocks: List[Block] = [] + with open("./all_blocks.txt", "r") as file: + all_blocks = [Block(x) for x in file.readlines()] + + if not os.path.exists("./out/woodcutting"): + os.makedirs("./out/woodcutting") + + generate_plank_crafting(all_blocks) + generate_log_stripping(all_blocks) + + +if __name__ == "__main__": + main() diff --git a/src/modules/slab_to_block.py b/src/modules/slab_to_block.py new file mode 100644 index 0000000..0a6477d --- /dev/null +++ b/src/modules/slab_to_block.py @@ -0,0 +1,65 @@ +""" +Author: Jose Stovall | oitsjustjose +A script for iterating over every slab in the game (provided by CraftDumper) + Turns 2 slabs into 1 source block of slab +""" + +import json +import os +from typing import List +from ..util.file import create_requisite_files + + +JSON_TEMPLATE = { + "type": "minecraft:crafting_shapeless", + "ingredients": [], + "result": {"item": "", "count": 1}, +} + +TRANSMUTATIONS = ["s", "_planks"] + + +def main() -> None: + """ + The main Python run-function for this file + """ + create_requisite_files() + + if not os.path.exists("./out/slab_to_block"): + os.makedirs("./out/slab_to_block") + + slabs: List[str] + all_blocks: List[str] + with open("./all_blocks.txt", "r") as file: + all_blocks = [x.replace("\n", "") for x in file.readlines()] + with open("./slabs.txt", "r") as file: + slabs = [x.replace("\n", "") for x in file.readlines()] + + for slab in slabs: + block = slab.replace("_slab", "").replace("slab_", "") + + if block not in all_blocks: + found = False + for trns in TRANSMUTATIONS: + block_alt = f"{block}{trns}" + if block_alt in all_blocks: + block = block_alt + found = True + break + if not found: + print(f"Neither {block} nor {block_alt} exist in block list") + continue + + recipe = JSON_TEMPLATE.copy() + recipe["ingredients"] = [{"item": slab}, {"item": slab}] + recipe["result"]["item"] = block + + block_cln = block[block.index(":") + 1 :] + slab_cln = slab[slab.index(":") + 1 :] + file_name = f"{block_cln}_from_two_{slab_cln}.json" + with open(f"./out/slab_to_block/{file_name}", "w") as file: + file.write(json.dumps(recipe, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/src/util/file.py b/src/util/file.py new file mode 100644 index 0000000..3265963 --- /dev/null +++ b/src/util/file.py @@ -0,0 +1,104 @@ +""" +Author: Jose Stovall | github.com/oitsjustjose | oitsjustjose.com + +A script for extracting slabs (via BlockTag) from a CSV table of all blocks. + @link{https://www.curseforge.com/minecraft/mc-mods/craftdumper} + Table to be generated by CraftDumper + +Script Arguments: + [python.exe] extract_slabs.py +""" +import os +import sys +from typing import List, Tuple + +import pandas as pd + + +class FORE: + """A base colors class for printing colors to the shell""" + + HEADER = "\033[95m" + BLUE = "\033[94m" + CYAN = "\033[96m" + GREEN = "\033[92m" + WARNING = "\033[93m" + FAIL = "\033[91m" + ENDC = "\033[0m" + BOLD = "\033[1m" + UNDERLINE = "\033[4m" + + +def __try_find_path() -> Tuple[List[str], str]: + """ + Makes an attempt at automagically finding the blocks csv + in the local directory if you just dropped it in and ran + this without reading up on these docstrings or anything 😠 + """ + if len(sys.argv) == 2: + return sys.argv[1] + candidates: List[str] = [] + for dirpath, _, filenames in os.walk("./"): + for f_name in filenames: + if f_name.endswith(".csv"): + candidates.append(f"{dirpath}/{f_name}") + + for f_name in candidates: + str_data: str + with open(f_name, "r") as file: + str_data = file.readline() + if "ID" in str_data and "Tags" in str_data: + return candidates, f_name + return candidates, "" + + +def __try_get_blocks() -> Tuple[List[str], List[str]]: + """ + Attempts to fetch the blocks CSV as a Pandas Df object + If it cannot find or parse the file at the path given + (or the path is not given), None is returned to throw + an error later down the call stack :) + """ + print(f"{FORE.HEADER}Beginning Extract...{FORE.ENDC}") + + attempts, f_name = __try_find_path() + if f_name: + print(f"Detected CSV file {f_name}") + else: + print(f"{FORE.FAIL}Error in program execution:{FORE.ENDC}") + print(f"\tpython3 {' '.join(sys.argv)} {FORE.FAIL}does not match{FORE.ENDC}") + print("\tpython3 extract_slabs.py ") + if attempts: + print("") + print( + f"{FORE.BOLD}Also tried the following CSVs but were missing attributes:" + ) + print("\n ".join(attempts)) + sys.exit(0) + d_blocks: pd.DataFrame = pd.read_csv(f_name) + d_slabs: pd.DataFrame = d_blocks.copy() + + d_slabs: pd.DataFrame = d_slabs[d_slabs["Tags"].notna()] + d_slabs: pd.DataFrame = d_slabs[d_slabs["Tags"].str.contains("slab")] + d_slabs: pd.DataFrame = d_slabs[~d_slabs["Tags"].str.contains("vertical")] + + # WARN: Instance of 'TextFileReader' has no 'ID' member + # IGNORE this warning - I think Pandas.DataFrame.Id is confusing it. + return d_blocks.ID.unique(), d_slabs.ID.unique() + + +def create_requisite_files() -> None: + """The main runfunc for the program 😀""" + all_blocks, slabs = __try_get_blocks() + + print(f"{FORE.CYAN}Writing {len(all_blocks)} blocks to ./all_blocks.txt{FORE.ENDC}") + print(f"{FORE.CYAN}Writing {len(slabs)} slabs to ./slabs.txt{FORE.ENDC}") + + with open("./all_blocks.txt", "w") as file: + file.write("\n".join(all_blocks)) + with open("./slabs.txt", "w") as file: + file.write("\n".join(slabs)) + + +if __name__ == "__main__": + create_requisite_files()