### Quick Example: Apply Effects, Play Sound, Give XP using fabricpy Source: https://fabricpy.readthedocs.io/stable/guides/block-actions Demonstrates combining multiple actions: applying a regeneration effect, playing a sound, and giving experience points. This example showcases how to return a list of actions from a block's on_right_click event handler. ```python import fabricpy from fabricpy.actions import apply_effect, play_sound, give_xp class MagicBlock(fabricpy.Block): def __init__(self): super().__init__( id="mymod:magic_block", name="Magic Block", item_group=fabricpy.item_group.BUILDING_BLOCKS, loot_table=fabricpy.LootTable.drops_self("mymod:magic_block"), ) def on_right_click(self): return [ apply_effect("REGENERATION", 400, 1), play_sound("PLAYER_LEVELUP"), give_xp(50), ] ``` -------------------------------- ### Complete Mining Block Example Source: https://fabricpy.readthedocs.io/stable/guides/creating-blocks A comprehensive example demonstrating custom hardness, resistance, tool type, mining level, per-tool mining speeds, and a fortune-based loot table. ```python ruby_ore = fabricpy.Block( id="mymod:ruby_ore", name="Ruby Ore", hardness=3.0, resistance=3.0, tool_type="pickaxe", mining_level="iron", mining_speeds={ "pickaxe": 8.0, "axe": 2.0, }, loot_table=fabricpy.LootTable.drops_with_fortune( "mymod:ruby_ore", "mymod:ruby", min_count=1, max_count=3, ), ) ``` -------------------------------- ### Complete FabricPy Mod Integration Example Source: https://fabricpy.readthedocs.io/stable/guides/vanilla-item-groups This comprehensive example demonstrates setting up a FabricPy mod with a `ModConfig` and registering various item types, including building blocks, natural resources, ingredients, tools, combat items, food, functional blocks, and decorations. It iterates through a list of items and registers them based on their type before compiling and running the mod. ```python import fabricpy # Create mod mod = fabricpy.ModConfig( mod_id="integrated_mod", name="Integrated Mod", version="1.0.0", description="Seamlessly integrates with vanilla Minecraft", authors=["Integration Expert"] ) # Items organized by vanilla tabs all_items = [ # Building materials fabricpy.Block( id="integrated_mod:marble_block", name="Marble Block", item_group=fabricpy.item_group.BUILDING_BLOCKS, ), fabricpy.Block( id="integrated_mod:granite_bricks", name="Granite Bricks", item_group=fabricpy.item_group.BUILDING_BLOCKS, ), # Natural resources fabricpy.Block( id="integrated_mod:tin_ore", name="Tin Ore", item_group=fabricpy.item_group.NATURAL, ), # Crafting ingredients fabricpy.Item( id="integrated_mod:tin_ingot", name="Tin Ingot", item_group=fabricpy.item_group.INGREDIENTS ), fabricpy.Item( id="integrated_mod:bronze_ingot", name="Bronze Ingot", item_group=fabricpy.item_group.INGREDIENTS ), # Tools fabricpy.Item( id="integrated_mod:bronze_pickaxe", name="Bronze Pickaxe", item_group=fabricpy.item_group.TOOLS, max_stack_size=1 ), fabricpy.Item( id="integrated_mod:tin_shovel", name="Tin Shovel", item_group=fabricpy.item_group.TOOLS, max_stack_size=1 ), # Combat items fabricpy.Item( id="integrated_mod:bronze_sword", name="Bronze Sword", item_group=fabricpy.item_group.COMBAT, max_stack_size=1 ), # Food items fabricpy.FoodItem( id="integrated_mod:tin_can_food", name="Canned Food", nutrition=6, saturation=7.2, item_group=fabricpy.item_group.FOOD_AND_DRINK ), # Functional blocks fabricpy.Block( id="integrated_mod:bronze_furnace", name="Bronze Furnace", item_group=fabricpy.item_group.FUNCTIONAL, ), # Decorative items fabricpy.Block( id="integrated_mod:tin_lantern", name="Tin Lantern", item_group=fabricpy.item_group.DECORATIONS, ) ] # Register all items for item in all_items: if hasattr(item, 'nutrition'): # FoodItem mod.registerFoodItem(item) elif hasattr(item, 'block_texture_path'): # Block mod.registerBlock(item) else: # Item mod.registerItem(item) # Compile and run mod.compile() mod.run() ``` -------------------------------- ### Block Creation and Configuration Source: https://fabricpy.readthedocs.io/stable/api Examples of creating Block instances with various configurations, including basic properties, mining settings, and per-tool mining speeds. ```APIDOC ## Block Creation Examples ### Description Demonstrates how to create `Block` instances with different configurations. ### Request Example ```python # Creating a basic block block_basic = Block( id="mymod:basic_block", name="Basic Block" ) # Creating a block with mining configuration block_mining = Block( id="mymod:ruby_ore", name="Ruby Ore", hardness=3.0, resistance=3.0, tool_type="pickaxe", mining_level="iron", requires_tool=True, ) # Creating a block with per-tool mining speeds block_per_tool_speed = Block( id="mymod:mixed_ore", name="Mixed Ore", hardness=4.0, resistance=4.0, mining_speeds={ "pickaxe": 8.0, "shovel": 3.0, }, requires_tool=True, mining_level="stone", ) ``` ``` -------------------------------- ### Initialize FabricPy Mod Configuration (Python) Source: https://fabricpy.readthedocs.io/stable/quickstart Sets up the basic configuration for a FabricPy mod, including its ID, name, version, description, authors, and the output project directory. This is the starting point for any FabricPy mod. ```python mod = fabricpy.ModConfig( mod_id="ruby_mod", name="Ruby Mod", version="1.0.0", description="A complete content mod adding ruby items, tools, and blocks", authors=["Example Dev"], project_dir="ruby-mod-output", ) ``` -------------------------------- ### Install fabricpy using pip Source: https://fabricpy.readthedocs.io/stable/quickstart Installs the fabricpy library using pip. Ensure you have Python 3.10+ installed before running this command. ```bash pip install fabricpy ``` -------------------------------- ### Create a Basic Fabric Mod with fabricpy Source: https://fabricpy.readthedocs.io/index This example demonstrates how to create a simple Minecraft Fabric mod using the fabricpy library. It covers initializing mod configuration, registering a custom item, and compiling/running the mod. No external dependencies are required beyond the fabricpy library itself. ```python import fabricpy # Create mod configuration mod = fabricpy.ModConfig( mod_id="mymod", name="My Awesome Mod", version="1.0.0", description="Adds cool items to Minecraft", authors=["Your Name"] ) # Create and register an item item = fabricpy.Item( id="mymod:cool_sword", name="Cool Sword", item_group=fabricpy.item_group.COMBAT ) mod.registerItem(item) # Compile and run mod.compile() mod.run() ``` -------------------------------- ### Create Basic Fabric Mod with fabricpy Source: https://fabricpy.readthedocs.io/stable/api Demonstrates the fundamental steps of creating a Fabric mod using fabricpy. It initializes the ModConfig, registers a custom item, and then compiles and runs the mod. This requires the fabricpy library to be installed. ```python import fabricpy # Create mod configuration mymod = fabricpy.ModConfig( mod_id="mymod", name="My Mod", version="1.0.0", description="A simple example mod", authors=["Your Name"] ) # Create and register an item item = fabricpy.Item( id="mymod:example_item", name="Example Item" ) mymod.registerItem(item) # Compile and run mymod.compile() mymod.run() ``` -------------------------------- ### Complete FabricPy Mod with Various Recipes Source: https://fabricpy.readthedocs.io/stable/guides/custom-recipes A comprehensive example of a FabricPy mod demonstrating the creation of a ModConfig, multiple recipe types (shaped, smelting, shapeless), and item registration. ```python import fabricpy # Create mod mod = fabricpy.ModConfig( mod_id="recipes_mod", name="Recipes Mod", version="1.0.0", description="Demonstrates various recipe types", authors=["Recipe Master"] ) # Create recipes recipes = { # Shaped crafting recipe "magic_wand": fabricpy.RecipeJson({ "type": "minecraft:crafting_shaped", "pattern": [" D ", " S ", " S "], "key": { "D": "minecraft:diamond", "S": "minecraft:stick" }, "result": {"id": "recipes_mod:magic_wand", "count": 1} }), # Smelting recipe "magic_ingot": fabricpy.RecipeJson({ "type": "minecraft:smelting", "ingredient": {"item": "recipes_mod:magic_ore"}, "result": {"id": "recipes_mod:magic_ingot", "count": 1}, "experience": 1.5, "cookingtime": 300 }), # Shapeless recipe "magic_dust": fabricpy.RecipeJson({ "type": "minecraft:crafting_shapeless", "ingredients": [ {"item": "recipes_mod:magic_crystal"}, {"item": "minecraft:redstone"} ], "result": {"id": "recipes_mod:magic_dust", "count": 4} }) } # Create items with recipes items = [ fabricpy.Item( id="recipes_mod:magic_wand", name="Magic Wand", recipe=recipes["magic_wand"], max_stack_size=1, ), fabricpy.Item( id="recipes_mod:magic_ingot", name="Magic Ingot", recipe=recipes["magic_ingot"] ), fabricpy.Item( id="recipes_mod:magic_dust", name="Magic Dust", recipe=recipes["magic_dust"] ) ] # Register items for item in items: mod.registerItem(item) # Compile and run mod.compile() mod.run() ``` -------------------------------- ### Create Basic Food Item with fabricpy Source: https://fabricpy.readthedocs.io/stable/fabricpy Demonstrates how to create a basic FoodItem instance using the fabricpy library. This example initializes a 'Golden Apple' with specified nutrition, saturation, and edible properties, assigning it to the food item group. ```python apple = FoodItem( id="mymod:golden_apple", name="Golden Apple", nutrition=4, saturation=9.6, always_edible=True, item_group=fabricpy.item_group.FOOD_AND_DRINK ) ``` -------------------------------- ### Basic Block Creation in FabricPy Source: https://fabricpy.readthedocs.io/stable/api Demonstrates the creation of a basic block with essential properties like ID, name, and texture path. This serves as a foundational example for defining new blocks within a FabricPy mod. ```python block = Block( id="mymod:copper_block", name="Copper Block", block_texture_path="textures/blocks/copper_block.png" ) ``` -------------------------------- ### Create and Register Multiple Items in fabricpy Source: https://fabricpy.readthedocs.io/stable/guides/creating-items Provides a comprehensive example of creating a ModConfig, defining multiple items with various properties (including textures and stack sizes), and then registering them with the mod. Finally, it shows how to compile and run the mod. ```python import fabricpy # Create mod configuration mod = fabricpy.ModConfig( mod_id="gems_mod", name="Gems Mod", version="1.0.0", description="Adds various gems to Minecraft", authors=["Your Name"] ) # Create various items items = [ fabricpy.Item( id="gems_mod:ruby", name="Ruby", item_group=fabricpy.item_group.INGREDIENTS, texture_path="textures/items/ruby.png" ), fabricpy.Item( id="gems_mod:sapphire", name="Sapphire", item_group=fabricpy.item_group.INGREDIENTS, texture_path="textures/items/sapphire.png" ), fabricpy.Item( id="gems_mod:emerald_shard", name="Emerald Shard", item_group=fabricpy.item_group.INGREDIENTS, max_stack_size=32 ) ] # Register all items for item in items: mod.registerItem(item) # Compile and run mod.compile() mod.run() ``` -------------------------------- ### Create Mid Game Food Items with fabricpy Source: https://fabricpy.readthedocs.io/stable/guides/creating-food-items Illustrates the creation of a list of mid-game food items using fabricpy.FoodItem. Examples include 'Honey Cake' and 'Roasted Nuts', highlighting the use of nutrition and saturation parameters for balanced gameplay progression. ```python mid_foods = [ fabricpy.FoodItem( id="mymod:honey_cake", name="Honey Cake", nutrition=7, saturation=8.4 ), fabricpy.FoodItem( id="mymod:roasted_nuts", name="Roasted Nuts", nutrition=5, saturation=6.0 ) ] ``` -------------------------------- ### Create a Ruby Pickaxe ToolItem Source: https://fabricpy.readthedocs.io/stable/api This Python example demonstrates the creation of a `ToolItem` representing a 'Ruby Pickaxe'. It configures properties like durability, mining speed, attack damage, mining level, enchantability, and the repair ingredient. ```python pickaxe = ToolItem( id="mymod:ruby_pickaxe", name="Ruby Pickaxe", durability=500, mining_speed_multiplier=8.0, attack_damage=3.0, mining_level=2, enchantability=22, repair_ingredient="minecraft:ruby", ) ``` -------------------------------- ### Set up Fabric Testing Framework in Gradle Build File Source: https://fabricpy.readthedocs.io/stable/_modules/fabricpy/modconfig Configures the mod project to support Fabric's testing capabilities by modifying the `build.gradle` file. It adds necessary testing dependencies and configurations, including options for game tests if enabled or detected. This setup is a prerequisite for running unit and game tests. ```python def setup_fabric_testing(self, project_dir: str): """Set up Fabric testing framework in the project. Configures the mod project to support Fabric's testing capabilities by enhancing build.gradle with testing dependencies and configuration, and ensuring gradle.properties has the necessary testing properties. Args: project_dir (str): The root directory of the mod project. Note: This method is called automatically during compile() when enable_testing is True. It sets up the foundation for both unit tests and game tests but doesn't generate the test files themselves (see generate_fabric_unit_tests and generate_fabric_game_tests). """ print("Setting up Fabric testing framework...") # Enhance build.gradle with testing dependencies and configuration self._enhance_build_gradle_for_testing(project_dir) # Create gradle.properties if needed self._ensure_gradle_properties(project_dir) print("Fabric testing framework setup complete.") ``` -------------------------------- ### Create Food Item with Recipe using fabricpy Source: https://fabricpy.readthedocs.io/stable/fabricpy Illustrates the creation of a FoodItem with a defined crafting recipe using fabricpy. This example first defines a shaped crafting recipe using RecipeJson and then instantiates FoodItem, linking it to the defined recipe. ```python recipe = RecipeJson({ "type": "minecraft:crafting_shaped", "pattern": ["###", "#A#", "###"], "key": { "#": "minecraft:gold_ingot", "A": "minecraft:apple" }, "result": {"id": "mymod:golden_apple", "count": 1} }) apple = FoodItem( id="mymod:golden_apple", name="Golden Apple", nutrition=4, saturation=9.6, recipe=recipe ) ``` -------------------------------- ### Initialize Mod Configuration with FabricPy Source: https://fabricpy.readthedocs.io/stable/api Initializes a new Fabric mod configuration. This involves providing essential metadata such as mod ID, name, description, version, and authors. Optional parameters allow customization of the project directory, template repository, and testing framework setup. ```python config = ModConfig( mod_id="awesome_mod", name="Awesome Mod", description="Makes Minecraft more awesome", version="1.2.3", authors=["Alice", "Bob"], project_dir="my-awesome-mod" ) ``` -------------------------------- ### Initialize Block Instance with All Parameters Source: https://fabricpy.readthedocs.io/stable/fabricpy Demonstrates the initialization of a Block instance, showcasing all available parameters including ID, name, stack size, texture paths, recipe, item group, click and break events, loot table, and various mining-related configurations. ```python __init__(_id =None_, _name =None_, _max_stack_size =64_, _block_texture_path =None_, _inventory_texture_path =None_, _recipe =None_, _item_group =None_, _left_click_event =None_, _right_click_event =None_, _break_event =None_, _loot_table =None_, _tool_type =None_, _hardness =None_, _resistance =None_, _mining_level =None_, _requires_tool =None_, _mining_speeds =None_) ``` -------------------------------- ### ItemGroup Icon Handling Source: https://fabricpy.readthedocs.io/stable/_modules/fabricpy/itemgroup Documentation for methods related to setting and getting the icon for an ItemGroup. ```APIDOC ## GET /itemgroup/icon_item_id ### Description Retrieves the item ID of the icon associated with the ItemGroup. Returns None if no icon is set or if the icon lacks an ID attribute. ### Method GET ### Endpoint /itemgroup/icon_item_id ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **icon_item_id** (str | None) - The item ID of the icon, or None. #### Response Example ```json { "icon_item_id": "mymod:sword" } ``` ``` ```APIDOC ## POST /itemgroup/set_icon ### Description Sets the icon item for this ItemGroup. This icon is displayed on the creative inventory tab and should represent the category of items within the group. The icon item should be registered before the ItemGroup is used in mod compilation. ### Method POST ### Endpoint /itemgroup/set_icon ### Parameters #### Request Body - **icon** (Type) - Required - The item class whose ItemStack will be displayed as the tab icon. This should be a class that extends Item, FoodItem, or Block. ### Request Example ```json { "icon": "MagicWandItem" } ``` ### Response #### Success Response (200) - **message** (str) - Indicates successful setting of the icon. #### Response Example ```json { "message": "Icon set successfully." } ``` ``` -------------------------------- ### Patch ExampleMod.java Initializer Source: https://fabricpy.readthedocs.io/stable/_modules/fabricpy/modconfig A helper method to patch the ExampleMod.java file by inserting a given line into the onInitialize method. It handles finding the file, checking for existing lines, and writing the patched content back. It prints a warning if the file is not found. ```python def _patch_initializer(self, project_dir, line: str): paths = [ os.path.join( project_dir, "src", "main", "java", "com", "example", "ExampleMod.java" ), os.path.join( project_dir, "src", "main", "resources", "java", "com", "example", "ExampleMod.java", ), ] init = next((p for p in paths if os.path.exists(p)), None) if not init: print("WARNING: ExampleMod.java not found – cannot patch initializer.") return with open(init, "r", encoding="utf-8") as fh: txt = fh.read() if line in txt: return patched, n = re.subn( r"(public\s+void\s+onInitialize\s*\(\s*\)\s*{")", r"\1\n " + line, txt, 1, ) if n: with open(init, "w", encoding="utf-8") as fh: fh.write(patched) print(f"Patched ExampleMod.java – added `{line.strip()}`.") ``` -------------------------------- ### Get ItemGroup ID (Python) Source: https://fabricpy.readthedocs.io/stable/api Retrieves the registry identifier for an ItemGroup. This property is an alias for 'item_id' for compatibility with existing code. ```python group.id ``` -------------------------------- ### RecipeJson Class Source: https://fabricpy.readthedocs.io/stable/api Represents a JSON recipe. It stores the recipe text and data, and provides methods to get the result item ID. ```APIDOC ## RecipeJson Class ### Description Represents a JSON recipe. It stores the recipe text and data, and provides methods to get the result item ID. ### Attributes - **text** (str) - The raw JSON string of the recipe. - **data** (dict) - The parsed JSON data of the recipe. ### Methods - **`__init__(...)`**: Initializes a new RecipeJson instance. - **`result_id`**: Property to get the ID of the result item. - **`get_result_id()`**: Returns the ID of the result item. ``` -------------------------------- ### Initialize Fabric Mod Configuration Source: https://fabricpy.readthedocs.io/stable/guides/creating-blocks Sets up the basic configuration for a fabric mod, including its ID, name, version, description, and authors. ```python import fabricpy # Create mod mod = fabricpy.ModConfig( mod_id="blocks_mod", name="Blocks Mod", version="1.0.0", description="Adds various blocks to Minecraft", authors=["Block Builder"] ) ``` -------------------------------- ### Get ItemGroup ID - Python Source: https://fabricpy.readthedocs.io/stable/fabricpy Shows how to retrieve the unique registry identifier for an ItemGroup. This property, aliased as 'id', is crucial for internal referencing and compatibility. ```python # Assuming 'group' is an initialized ItemGroup object print(group.id) ``` -------------------------------- ### Get Result ID from Recipe (Python) Source: https://fabricpy.readthedocs.io/stable/api Retrieves the item identifier for the result of a crafting or smelting recipe. This method is an alias for the `result_id` property and is provided for backward compatibility. ```python recipe = RecipeJson({"type": "minecraft:smelting", "result": "minecraft:iron_ingot"}) result = recipe.get_result_id() # "minecraft:iron_ingot" ``` -------------------------------- ### Patch Mod Initializer with Item Initialization Source: https://fabricpy.readthedocs.io/stable/_modules/fabricpy/modconfig Adds a call to initialize tutorial items in the mod's main initializer file (ExampleMod.java). It locates the ExampleMod.java file and inserts the provided initialization line into the onInitialize method if it's not already present. This is useful for ensuring all custom items are properly registered. ```python def update_mod_initializer(self, project_dir, pkg): """Add item initialization code to the mod's main initializer. Args: project_dir (str): The root directory of the mod project. pkg (str): The Java package name containing the TutorialItems class. """ self._patch_initializer(project_dir, f"{pkg}.TutorialItems.initialize();") ``` -------------------------------- ### setup_fabric_testing Source: https://fabricpy.readthedocs.io/stable/api Sets up the Fabric testing framework in the project. This function configures the mod project to support Fabric’s testing capabilities by enhancing build.gradle with testing dependencies and configuration, and ensuring gradle.properties has the necessary testing properties. ```APIDOC ## setup_fabric_testing ### Description Set up Fabric testing framework in the project. Configures the mod project to support Fabric’s testing capabilities by enhancing build.gradle with testing dependencies and configuration, and ensuring gradle.properties has the necessary testing properties. ### Method POST ### Endpoint /setup_fabric_testing ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **project_dir** (str) - Required - The root directory of the mod project. ### Note This method is called automatically during compile() when enable_testing is True. It sets up the foundation for both unit tests and game tests but doesn’t generate the test files themselves (see generate_fabric_unit_tests and generate_fabric_game_tests). ``` -------------------------------- ### Create Advanced Shaped Crafting Recipe with fabricpy Source: https://fabricpy.readthedocs.io/stable/guides/custom-recipes An example of a more complex shaped crafting recipe involving multiple different ingredients arranged in a specific pattern. ```python # Advanced crafting table recipe advanced_table_recipe = fabricpy.RecipeJson({ "type": "minecraft:crafting_shaped", "pattern": [ "DGD", "WTW", "WOW" ], "key": { "D": "minecraft:diamond", "G": "minecraft:gold_ingot", "W": "minecraft:oak_planks", "T": "minecraft:crafting_table", "O": "minecraft:obsidian" }, "result": {"id": "mymod:advanced_crafting_table", "count": 1} }) ``` -------------------------------- ### Block Class Initialization Source: https://fabricpy.readthedocs.io/stable/api Detailed documentation for the `Block` class constructor, explaining each parameter. ```APIDOC ## Block Class Constructor ### Description Initializes a new `Block` instance with various properties and event handlers. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **id** (str | None) - The registry identifier for the block. - **name** (str | None) - The display name for the block. - **max_stack_size** (int) - Maximum number of block items that can be stacked. Defaults to 64. - **block_texture_path** (str | None) - Path to the block’s world texture file. - **inventory_texture_path** (str | None) - Path to the block’s inventory texture file. Falls back to `block_texture_path` if not provided. - **recipe** (object | None) - Recipe definition for crafting this block. - **item_group** (object | str | None) - Creative tab to place this block’s item in. - **left_click_event** (str | Sequence[str] | None) - Java code to execute when the block is left clicked. Prefer overriding `on_left_click()` in a subclass. - **right_click_event** (str | Sequence[str] | None) - Java code to execute when the block is right clicked. Prefer overriding `on_right_click()` in a subclass. - **break_event** (str | Sequence[str] | None) - Java code to execute after the block is broken. Prefer overriding `on_break()` in a subclass. - **loot_table** (object | None) - Loot table for block drops. - **tool_type** (str | None) - Primary tool type for efficient mining (e.g., "pickaxe", "axe"). - **hardness** (float | None) - Block hardness (mining time base). - **resistance** (float | None) - Blast resistance. - **mining_level** (str | None) - Minimum tool tier (e.g., "stone", "iron", "diamond"). - **requires_tool** (bool | None) - Whether the correct tool is required for drops. Inferred from `tool_type` when `None`. - **mining_speeds** (dict[str, float] | None) - Per-tool speed overrides as `{tool: speed}` mapping. ### Raises **ValueError** - If `tool_type`, `mining_level`, or any key in `mining_speeds` is not a recognized value. ### Request Example ```python # Example of initializing a Block with various parameters block = Block( id="mymod:custom_block", name="Custom Block", hardness=5.0, resistance=10.0, tool_type="pickaxe", mining_level="diamond", mining_speeds={ "pickaxe": 1.0, "diamond_pickaxe": 0.5 }, left_click_event="player.sendMessage('You clicked the block!');", break_event="world.createExplosion(pos, 1.0);" ) ``` ``` -------------------------------- ### Handle Block Left Click Event (Python) Source: https://fabricpy.readthedocs.io/stable/api Provides an example of overriding the `on_left_click` method to execute custom Java code when a block is left-clicked. This allows for interactive block behavior. ```python def on_left_click(self): return [ drop_item("DIAMOND", count=3), play_sound("EXPERIENCE_ORB_PICKUP"), give_xp(25), ] ``` -------------------------------- ### Define an Item with a Crafting Recipe in Fabricpy Source: https://fabricpy.readthedocs.io/stable/api This example shows how to define a custom item that can be crafted using a shaped recipe. It involves creating a RecipeJson object and passing it to the Item constructor. ```python recipe = RecipeJson({ "type": "minecraft:crafting_shaped", "pattern": ["#", "#", "/"], "key": { "#": "minecraft:copper_ingot", "/": "minecraft:stick" }, "result": {"id": "mymod:copper_sword", "count": 1} }) item = Item( id="mymod:copper_sword", name="Copper Sword", recipe=recipe ) ``` -------------------------------- ### Generate TutorialItems.java Source Code Source: https://fabricpy.readthedocs.io/stable/_modules/fabricpy/modconfig This Python function generates the complete Java source code for the TutorialItems class. It dynamically includes imports for FoodProperties, CustomToolItem, and CreativeModeTab based on the types of registered items. The generated code defines constants for each item and a helper method for registration. ```python def _tutorial_items_src(self, pkg: str) -> str: """Generate Java source code for the TutorialItems class. Creates a complete Java class that registers all mod items, including proper imports, constant declarations, registration logic, and vanilla item group integration. Args: pkg (str): The Java package name for the generated class. Returns: str: Complete Java source code for the TutorialItems class. Example: Creating item files:: mod.create_item_files( "/path/to/mod", "com.example.mymod.items" ) """ has_food = any(isinstance(i, FoodItem) for i in self.registered_items) has_tool = any(isinstance(i, ToolItem) for i in self.registered_items) has_vanila = any( isinstance(getattr(i, "item_group", None), str) for i in self.registered_items ) L: List[str] = [] L.append(f"package {pkg}\n") L.append("import net.minecraft.world.item.Item;") if has_food: L.append("import net.minecraft.world.food.FoodProperties;") L.append("import net.minecraft.resources.Identifier;") L.append("import net.minecraft.core.Registry;") L.append("import net.minecraft.resources.ResourceKey;") L.append("import net.minecraft.core.registries.Registries;") L.append("import net.minecraft.core.registries.BuiltInRegistries;") if has_tool: L.append(f"import {pkg}.CustomToolItem;") if has_vanila: L.append("import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents;") L.append("import net.minecraft.world.item.CreativeModeTab;") L.append("import java.util.function.Function\n") L.append("public final class TutorialItems {") L.append(" private TutorialItems() {} ") for itm in self.registered_items: const = self._to_java_constant(itm.id) if isinstance(itm, FoodItem): b = [ f".nutrition({itm.nutrition})", f".saturationModifier({itm.saturation}f)", ] if itm.always_edible: b.append(".alwaysEdible()") settings = ( "new Item.Properties()" f".food(new FoodProperties.Builder(){''.join(b)}.build())" f".stacksTo({itm.max_stack_size})" ) factory = "Item::new" elif isinstance(itm, ToolItem): settings = "new Item.Properties()" repair = ( "null" if itm.repair_ingredient is None else f'\"{itm.repair_ingredient}\"' ) factory = ( "s -> new CustomToolItem(" f"{itm.durability}, {itm.mining_speed_multiplier}f, " f"{itm.attack_damage}f, {itm.mining_level}, {itm.enchantability}, " f"{repair}, {itm.max_stack_size}, s)" ) else: settings = f"new Item.Properties().stacksTo({itm.max_stack_size})" factory = "CustomItem::new" # Extract just the path part if the ID is namespaced item_path = itm.id.split(":", 1)[-1] L.append( f' public static final Item {const} = register("", "{item_path}", ' f"{factory}, {settings});" ) L.append("") L.append( " private static Item register(String path, " "Function factory, Item.Properties settings) {" ) L.append( f' ResourceKey key = ResourceKey.create(Registries.ITEM, Identifier.fromNamespaceAndPath("{self.mod_id}", path));' ) L.append(" settings = settings.setId(key);") L.append( f" return Registry.register(BuiltInRegistries.ITEM, key, factory.apply(settings));" ) L.append(" }\n") L.append(" public static void initialize() {") if has_vanila: groups: Dict[str, List[str]] = defaultdict(list) ``` -------------------------------- ### Define a Custom ToolItem Source: https://fabricpy.readthedocs.io/stable/quickstart Provides a minimal example of defining a custom ToolItem in FabricPy. This includes setting properties like durability, mining speed, attack damage, and repair ingredients. ```python import fabricpy # Configure the mod mod = fabricpy.ModConfig( mod_id="example_tools", name="Example Tools", version="1.0.0", description="Demonstrates ToolItem usage", authors=["Example Dev"] ) # Define a ruby pickaxe tool ruby_pickaxe = fabricpy.ToolItem( id="example_tools:ruby_pickaxe", name="Ruby Pickaxe", durability=500, mining_speed_multiplier=8.0, attack_damage=3.0, mining_level=2, enchantability=22, repair_ingredient="minecraft:ruby", item_group=fabricpy.item_group.TOOLS, ) # Register the tool with the mod mod.registerItem(ruby_pickaxe) ``` -------------------------------- ### Patch Mod Initializer with Block Initialization Source: https://fabricpy.readthedocs.io/stable/_modules/fabricpy/modconfig Adds a call to initialize tutorial blocks in the mod's main initializer file (ExampleMod.java). It locates the ExampleMod.java file and inserts the provided initialization line into the onInitialize method if it's not already present. This ensures that all custom blocks are registered. ```python def update_mod_initializer_blocks(self, project_dir, pkg): """Add block initialization code to the mod's main initializer. Args: project_dir (str): The root directory of the mod project. pkg (str): The Java package name containing the TutorialBlocks class. """ self._patch_initializer(project_dir, f"{pkg}.TutorialBlocks.initialize();") ``` -------------------------------- ### Create Blocks for Building Tab Source: https://fabricpy.readthedocs.io/stable/guides/vanilla-item-groups Provides an example of creating block items and assigning them to the BUILDING_BLOCKS vanilla item group. These blocks are intended for construction purposes in Minecraft. ```python # Blocks for construction building_items = [ fabricpy.Block( id="mymod:marble_block", name="Marble Block", item_group=fabricpy.item_group.BUILDING_BLOCKS ), fabricpy.Block( id="mymod:steel_block", name="Steel Block", item_group=fabricpy.item_group.BUILDING_BLOCKS ), fabricpy.Block( id="mymod:reinforced_concrete", name="Reinforced Concrete", item_group=fabricpy.item_group.BUILDING_BLOCKS ) ] ``` -------------------------------- ### LootPool Builder Initialization and Configuration Source: https://fabricpy.readthedocs.io/stable/_modules/fabricpy/loottable Demonstrates how to initialize and configure a LootPool object using its fluent interface. This includes setting the number of rolls, bonus rolls, and adding item entries with optional weights, quality modifiers, conditions, and functions. ```python pool = ( LootPool() .rolls(1) .entry("mymod:ruby", weight=3) .entry("mymod:sapphire", weight=1) .condition({"condition": "minecraft:survives_explosion"}) .build() ) ``` -------------------------------- ### Create Item Registration Java Files (Java) Source: https://fabricpy.readthedocs.io/stable/_modules/fabricpy/modconfig Generates Java source files for item registration and custom item behavior. It creates 'TutorialItems.java' for registering all mod items and 'CustomItem.java' as a base class for items with custom functionality, placing them in the specified package directory. ```java java_src = os.path.join(project_dir, "src", "main", "java") pkg_dir = os.path.join(java_src, *package_path.split(".")) os.makedirs(pkg_dir, exist_ok=True) with open( ``` -------------------------------- ### Create Block with Loot Table in fabricpy Source: https://fabricpy.readthedocs.io/stable/guides/creating-blocks Illustrates how to attach loot tables to blocks to control their drops when broken. Examples include a self-dropping block and an ore block with fortune scaling. ```python # Self-dropping block (most common) simple_block = fabricpy.Block( id="mymod:marble", name="Marble", loot_table=fabricpy.LootTable.drops_self("mymod:marble"), ) # Ore with fortune scaling ore = fabricpy.Block( id="mymod:ruby_ore", name="Ruby Ore", loot_table=fabricpy.LootTable.drops_with_fortune( "mymod:ruby_ore", "mymod:ruby", min_count=1, max_count=2, ), ) ``` -------------------------------- ### Generate TutorialBlocks.java Source Code (Python) Source: https://fabricpy.readthedocs.io/stable/_modules/fabricpy/modconfig Generates the complete Java source code for the TutorialBlocks class, responsible for registering all mod blocks. It includes necessary imports, constant declarations, registration logic, and vanilla item group integration. ```python def _tutorial_blocks_src(self, pkg: str) -> str: """Generate Java source code for the TutorialBlocks class. Creates a complete Java class that registers all mod blocks, including proper imports, constant declarations, registration logic, and vanilla item group integration. Args: pkg (str): The Java package name for the generated class. Returns: str: Complete Java source code for the TutorialBlocks class. Example: Creating block files:: mod.create_block_files( "/path/to/mod", "com.example.mymod.blocks" ) """ has_vanila = any( isinstance(getattr(b, "item_group", None), str) for b in self.registered_blocks ) left_handlers = { blk: _normalize_hook(blk.on_left_click()) for blk in self.registered_blocks } right_handlers = { blk: _normalize_hook(blk.on_right_click()) for blk in self.registered_blocks } break_handlers = { blk: _normalize_hook(blk.on_break()) for blk in self.registered_blocks } has_left_click = any(left_handlers.values()) has_right_click = any(right_handlers.values()) has_break = any(break_handlers.values()) # Collect all event handler code for import detection _all_event_code = "\n".join( ev for ev in list(left_handlers.values()) + list(right_handlers.values()) + list(break_handlers.values()) if ev ) needs_text = "Component.literal" in _all_event_code L: List[str] = [] L.append(f"package {pkg}\n") L.append("import net.minecraft.world.level.block.Block;") L.append("import net.minecraft.world.level.block.state.BlockBehaviour;") L.append("import net.minecraft.world.level.block.Blocks;") L.append("import net.minecraft.world.item.BlockItem;") L.append("import net.minecraft.world.item.Item;") L.append("import net.minecraft.resources.Identifier;") L.append("import net.minecraft.core.Registry;") L.append("import net.minecraft.resources.ResourceKey;") L.append("import net.minecraft.core.registries.Registries;") L.append("import net.minecraft.core.registries.BuiltInRegistries;") if needs_text: L.append("import net.minecraft.network.chat.Component;") if has_vanila: L.append("import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents;") L.append("import net.minecraft.world.item.CreativeModeTab;") if has_left_click: L.append("import net.fabricmc.fabric.api.event.player.AttackBlockCallback;") if has_right_click: ``` -------------------------------- ### Create Early Game Food Items with fabricpy Source: https://fabricpy.readthedocs.io/stable/guides/creating-food-items Demonstrates the creation of a list of early-game food items using fabricpy.FoodItem. This includes items like 'Wild Berry' and 'Mushroom Stew', showcasing basic food item creation with varying nutrition, saturation, and stack sizes. ```python early_foods = [ fabricpy.FoodItem( id="mymod:berry", name="Wild Berry", nutrition=2, saturation=1.2 ), fabricpy.FoodItem( id="mymod:mushroom_stew", name="Mushroom Stew", nutrition=6, saturation=7.2, max_stack_size=1 # Bowl items don't stack ) ] ``` -------------------------------- ### Schedule Delayed Action using FabricPy Source: https://fabricpy.readthedocs.io/stable/guides/block-actions This section introduces the `delayed_action` function from FabricPy, which allows scheduling a block of Java code to execute after a specified delay in ticks. The example shows importing `delayed_action` and `give_xp`. ```python from fabricpy.actions import delayed_action, give_xp ``` -------------------------------- ### Get Recipe Result ID (Python) Source: https://fabricpy.readthedocs.io/stable/api Retrieves the item identifier for the result of a recipe. This ID is used for naming the generated recipe JSON file and is extracted from the 'result' field, supporting both string and dictionary formats. ```python result_id = recipe.result_id # "mymod:stone_block" ``` -------------------------------- ### Create Item Registration Files Source: https://fabricpy.readthedocs.io/stable/api Generates Java source files for item registration and management. It creates 'TutorialItems.java' for registration and 'CustomItem.java' as a base class for custom item behavior within the specified package. ```java mod.create_item_files( "/path/to/mod", "com.example.mymod.items" ) ``` -------------------------------- ### Create Magic-Themed Tab - Python Source: https://fabricpy.readthedocs.io/stable/guides/custom-item-groups Shows how to create a custom item group for magic-related items. This example includes creating a generic 'Item' and assigning it to the tab, then setting it as the tab's icon. ```python # Create a magic items tab magic_items = fabricpy.ItemGroup( id="magic_items", name="Magic Items" ) # Create magical items for this tab magic_wand = fabricpy.Item( id="mymod:magic_wand" name="Magic Wand" item_group=magic_items max_stack_size=1 ) # Use the wand as the tab icon magic_items.set_icon(magic_wand) ``` -------------------------------- ### Create Basic Block in Python Source: https://fabricpy.readthedocs.io/stable/_modules/fabricpy/block Demonstrates how to create a basic block instance with its ID, name, and texture path, assigning it to an item group. This is the foundational step for defining custom blocks in FabricPy. ```python block = Block( id="mymod:copper_block", name="Copper Block", block_texture_path="textures/blocks/copper_block.png", item_group=fabricpy.item_group.BUILDING_BLOCKS ) ``` -------------------------------- ### Get ItemGroup Icon Item ID (Python) Source: https://fabricpy.readthedocs.io/stable/_modules/fabricpy/itemgroup Retrieves the item ID of the icon set for an ItemGroup. Returns None if no icon is set or if the icon lacks an ID attribute. This is useful for verifying or displaying the icon's identifier. ```python def icon_item_id(self) -> str | None: """Returns: str | None: The item ID of the icon, or None if no icon is set or the icon has no ID attribute. Example: Getting the icon item ID:: group = ItemGroup(id="weapons", name="Weapons") group.set_icon(MySwordItem) # MySwordItem.id = "mymod:sword" print(group.icon_item_id) # "mymod:sword" """ if self._icon_cls is None: return None # Try to get ID from class or instance if hasattr(self._icon_cls, "id"): return getattr(self._icon_cls, "id") return None ``` -------------------------------- ### Get ItemGroup ID Alias Source: https://fabricpy.readthedocs.io/stable/_modules/fabricpy/itemgroup Provides an alias 'id' for the 'item_id' attribute of the ItemGroup class. This allows accessing the registry identifier using either property name, maintaining compatibility with different code styles or existing implementations. ```python @property def id(self) -> str: """Get the ItemGroup's ID. Returns: str: The registry identifier for this ItemGroup. Note: This is an alias for item_id to maintain compatibility with tests and existing code that expects an 'id' property. """ return self.item_id ``` -------------------------------- ### Create Basic Item in Python Source: https://fabricpy.readthedocs.io/stable/fabricpy Demonstrates how to create a basic custom item using the Item class. This includes setting the item's ID, display name, stack size, texture path, and assigning it to a creative tab. ```python from fabricpy.item import Item from fabricpy.item_group import COMBAT item = Item( id="mymod:copper_sword", name="Copper Sword", max_stack_size=1, texture_path="textures/items/copper_sword.png", item_group=COMBAT ) ``` -------------------------------- ### Get ItemGroup Icon Item ID Source: https://fabricpy.readthedocs.io/stable/_modules/fabricpy/itemgroup Retrieves the item ID of the icon used for an ItemGroup. This method is useful for identifying which item is designated as the visual representation for the creative tab, handling cases where the icon might be set as a class or instance. ```python @property def icon_item_id(self) -> str | None: """Get the item ID of the icon used for this ItemGroup. Extracts the item ID from the icon object, handling both class attributes and instance attributes. """ # This is a placeholder for the actual implementation which would # inspect self.icon and return its item ID. ```