fabricpy package modules¶
This section contains detailed documentation for each module in the fabricpy package.
Submodules¶
fabricpy.modconfig module¶
Generates a ready-to-build Fabric mod project on disk.
clones (or re-uses) the Fabric example-mod template repository
rewrites fabric.mod.json with your metadata
- generates Java for:
– items & food items – custom ItemGroups (creative-inventory tabs) – blocks (with BlockItems)
patches ExampleMod.java so those registries run at game-init
copies textures & writes model / blockstate JSON files
writes / merges language (en_us.json) entries for items, blocks & tabs
NEW: writes any Recipe JSON attached to an Item, FoodItem or Block
- NEW: supports build() to produce the mod JAR, and run() to launch
a development client via Gradle.
Tested against Minecraft 1.21.11 + Fabric-API 0.141.3.
- class ModConfig(mod_id, name, description, version, authors, project_dir='my-fabric-mod', template_repo='https://github.com/FabricMC/fabric-example-mod.git', enable_testing=True, generate_unit_tests=True, generate_game_tests=False)[source]¶
Bases:
objectMain configuration class for generating Fabric mod projects.
This class handles the entire process of creating a Minecraft Fabric mod from Python definitions. It manages mod metadata, item/block registration, Java code generation, texture processing, and project compilation.
The class supports: - Cloning and configuring the Fabric example-mod template - Registering items, food items, and blocks with custom properties - Generating Java source files for all registered components - Processing textures and generating model/blockstate JSON files - Creating recipe JSON files from RecipeJson objects - Setting up Fabric testing framework with unit and game tests - Building and running the mod in development mode
- authors¶
List of mod authors.
- Type:
List[str]
- registered_items¶
List of registered Item and FoodItem objects.
- Type:
List
- registered_blocks¶
List of registered Block objects.
- Type:
List
Example
Basic mod setup:
mod = ModConfig( mod_id="mymod", name="My Awesome Mod", version="1.0.0", description="Adds cool items to Minecraft", authors=["Your Name"] ) # Register an item item = Item(id="mymod:cool_item", name="Cool Item") mod.registerItem(item) # Compile and run mod.compile() mod.run()
- __init__(mod_id, name, description, version, authors, project_dir='my-fabric-mod', template_repo='https://github.com/FabricMC/fabric-example-mod.git', enable_testing=True, generate_unit_tests=True, generate_game_tests=False)[source]¶
Initialize a new ModConfig instance.
- Parameters:
mod_id (
str) – Unique identifier for the mod. Must be valid for Minecraft namespaces (lowercase, no spaces, alphanumeric + underscore/hyphen).name (
str) – Human-readable display name for the mod.description (
str) – Brief description of what the mod does.version (
str) – Version string for the mod (e.g., “1.0.0”).authors (
List[str] | tuple[str,]) – List or tuple of author names.project_dir (
str, optional) – Directory name for the generated mod project. Defaults to “my-fabric-mod”.template_repo (
str, optional) – Git repository URL for the Fabric template. Defaults to the official Fabric example-mod repository.enable_testing (
bool, optional) – Whether to set up Fabric testing framework. Defaults to True.generate_unit_tests (
bool, optional) – Whether to generate unit tests for registered items and blocks. Defaults to True.generate_game_tests (
bool, optional) – Whether to generate Fabric game tests that run in a Minecraft environment. Defaults to False to prevent build compilation issues.
Example
Creating a mod configuration:
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" )
- registerItem(item)[source]¶
Register an Item instance with this mod.
- Parameters:
item (
Item) – The Item instance to register. This can be a basic Item or any subclass such as FoodItem.
Example
Registering a basic item:
item = Item(id="mymod:stone_sword", name="Stone Sword") mod.registerItem(item)
- registerFoodItem(food_item)[source]¶
Register a FoodItem instance with this mod.
- Parameters:
food_item (
FoodItem) – The FoodItem instance to register. This is a convenience method that’s equivalent to registerItem() for food items.
Example
Registering a food item:
apple = FoodItem( id="mymod:golden_apple", name="Golden Apple", nutrition=6, saturation=0.8 ) mod.registerFoodItem(apple)
- registerBlock(block)[source]¶
Register a Block instance with this mod.
- Parameters:
block (
Block) – The Block instance to register. This will generate both the block itself and its corresponding BlockItem.
Example
Registering a block:
block = Block( id="mymod:diamond_block", name="Diamond Block", block_texture_path="textures/diamond_block.png" ) mod.registerBlock(block)
- registerLootTable(name, loot_table)[source]¶
Register a standalone loot table (entity / chest / custom).
Block loot tables should be attached directly to the Block via its
loot_tableattribute. Use this method for loot tables that are not tied to a specific block, such as entity drops, chest loot, or gameplay loot tables.- Parameters:
Example
Registering an entity loot table:
from fabricpy import LootTable, LootPool lt = LootTable.entity([ LootPool().rolls(1).entry("mymod:fang") ]) mod.registerLootTable("custom_zombie", lt)
- compile()[source]¶
Compile the mod project from registered components.
This is the main method that orchestrates the entire mod generation process: 1. Clones the Fabric example-mod template repository 2. Updates fabric.mod.json with mod metadata 3. Generates Java source files for items and item groups 4. Generates Java source files for blocks (if any) 5. Copies textures and generates model/blockstate JSON files 6. Writes recipe JSON files for items/blocks with recipes 7. Updates language files with item/block/group translations 8. Sets up Fabric testing framework (if enabled) 9. Generates unit and game tests (if enabled)
The generated project will be a complete, buildable Fabric mod.
- Raises:
subprocess.CalledProcessError – If git clone fails.
FileNotFoundError – If the fabric.mod.json template file is missing.
OSError – If there are issues with file I/O operations.
Example
Compiling a mod:
mod.registerItem(Item(id="mymod:test", name="Test")) mod.compile() # Creates complete mod project
Note
This method must be called before build() or run().
- clone_repository(repo_url, dst)[source]¶
Clone a Git repository to the specified destination.
- Parameters:
- Raises:
subprocess.CalledProcessError – If the git clone command fails.
Example
Cloning the Fabric example mod template:
mod.clone_repository( "https://github.com/FabricMC/fabric-example-mod.git", "/path/to/my-mod" )
- update_mod_metadata(path, data)[source]¶
Update the fabric.mod.json file with mod metadata.
- Parameters:
- Raises:
FileNotFoundError – If the fabric.mod.json file doesn’t exist.
json.JSONDecodeError – If the existing file contains invalid JSON.
Example
Updating mod metadata:
mod.update_mod_metadata( "src/main/resources/fabric.mod.json", { "id": "mymod", "name": "My Awesome Mod", "version": "1.0.0", "description": "An awesome Minecraft mod", "authors": ["Author Name"] } )
- write_recipe_files(project_dir, mod_id)[source]¶
Write recipe JSON files for items and blocks that have recipes.
Scans all registered items and blocks for attached RecipeJson objects and writes them as JSON files in the mod’s data/recipes directory. Each recipe file is named based on the result item ID.
- Parameters:
Note
Only items and blocks with non-None recipe attributes are processed
Recipe files are written to data/{mod_id}/recipe/
File names are derived from the recipe’s result_id or the item/block ID
Existing recipe files will be overwritten
Example
Writing recipes after registering items with recipes:
# Item with recipe item = Item( id="mymod:diamond_sword", name="Diamond Sword", recipe=RecipeJson({...}) ) mod.registerItem(item) # This will create the recipe file mod.write_recipe_files(project_dir, "mymod")
- write_loot_table_files(project_dir, mod_id)[source]¶
Write loot-table JSON files for blocks and standalone registrations.
Scans all registered blocks for attached
loot_tableattributes and all entries added viaregisterLootTable(), then writes them as JSON files underdata/<mod_id>/loot_table/<category>/.For blocks the filename is derived from the block ID. For standalone tables the filename is the name passed to
registerLootTable().- Parameters:
Note
This method is called automatically during
compile().Example
Writing loot tables manually (usually not needed):
mod.write_loot_table_files("my-mod-project", "mymod")
- write_block_tags(project_dir, mod_id)[source]¶
Write mineable and mining-level block-tag JSON files.
For every registered block that specifies a
tool_type(and/or keys inmining_speeds), the block is added to the correspondingdata/minecraft/tags/block/mineable/<tool>.jsontags.Blocks that specify a
mining_level("stone","iron", or"diamond") are also added todata/minecraft/tags/block/needs_<level>_tool.json.
- create_item_files(project_dir, package_path)[source]¶
Generate Java source files for item registration and management.
Creates TutorialItems.java and CustomItem.java files in the specified package. TutorialItems contains registration code for all items, while CustomItem provides a base class for custom item behavior.
- Parameters:
Note
Generated files include: - TutorialItems.java: Static registration for all mod items - CustomItem.java: Base class for items with custom behavior
Example
Creating item files:
mod.create_item_files( "/path/to/mod", "com.example.mymod.items" )
- create_item_group_files(project_dir, package_path)[source]¶
Generate Java source files for custom item groups (creative tabs).
Creates the TutorialItemGroups.java file containing Java code for all custom ItemGroup objects. This handles creative tab registration, icon assignment, and adding items/blocks to the custom tabs.
- Parameters:
Note
This method is called automatically during compile() when custom ItemGroup objects are detected. If no custom groups exist, no files are generated.
- update_mod_initializer(project_dir, pkg)[source]¶
Add item initialization code to the mod’s main initializer.
- update_mod_initializer_itemgroups(project_dir, pkg)[source]¶
Add item group initialization code to the mod’s main initializer.
- update_mod_initializer_blocks(project_dir, pkg)[source]¶
Add block initialization code to the mod’s main initializer.
- copy_texture_and_generate_models(project_dir, mod_id)[source]¶
Copy item textures and generate model/item definition JSON files.
Processes all registered items by copying their texture files to the mod’s assets directory and generating the corresponding model and item definition JSON files required by Minecraft’s resource pack system.
- Parameters:
Note
For each item, this method: - Copies the texture PNG file to assets/<mod_id>/textures/item/ - Generates a model JSON file in assets/<mod_id>/models/item/ - Generates an item definition JSON file in assets/<mod_id>/items/ Items without valid texture paths are skipped with a warning.
- update_item_lang_file(project_dir, mod_id)[source]¶
Update the English language file with item translations.
Adds or updates translation entries for all registered items in the mod’s en_us.json language file.
- update_item_group_lang_entries(project_dir, mod_id)[source]¶
Update the English language file with item group translations.
Adds translation entries for all custom item groups defined in the mod.
- create_block_files(project_dir, package_path)[source]¶
Generate Java source files for all registered blocks.
Creates the TutorialBlocks.java and CustomBlock.java files containing block registration and implementation logic.
- copy_block_textures_and_generate_models(project_dir, mod_id)[source]¶
Copy block textures and generate model/blockstate JSON files.
Processes all registered blocks by copying their texture files and generating the corresponding model, blockstate, and item definition JSON files required by Minecraft’s resource pack system.
- update_block_lang_file(project_dir, mod_id)[source]¶
Update the English language file with block translations.
Adds or updates translation entries for all registered blocks in the mod’s en_us.json language file. Creates entries for both the block and its corresponding item form.
- build()[source]¶
Build the mod JAR file using Gradle.
Requires compile() to have been called first. Enters the mod project directory and runs ./gradlew build to produce the distributable JAR file.
The built JAR will be located in the build/libs/ directory of the project.
- Raises:
RuntimeError – If the project directory doesn’t exist (compile() not called).
subprocess.CalledProcessError – If the Gradle build fails.
Example
Building the mod:
mod.compile() # Must be called first mod.build() # Creates JAR in build/libs/
- run()[source]¶
Run the mod in development mode using Fabric Loader.
Launches a Minecraft client with the mod loaded for testing and development. This uses Gradle’s runClient task which sets up a development environment.
- Raises:
FileNotFoundError – If the project directory doesn’t exist (compile() not called).
subprocess.CalledProcessError – If the Gradle runClient task fails.
Example
Running the mod for testing:
mod.compile() # Must be called first mod.run() # Launches Minecraft with the mod
- setup_fabric_testing(project_dir)[source]¶
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.
- Parameters:
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).
- generate_fabric_unit_tests(project_dir)[source]¶
Generate Fabric unit tests for the mod.
Creates comprehensive unit tests that validate item registration, recipe functionality, and mod integration. Tests are generated based on the registered items, blocks, and their properties.
- Parameters:
project_dir (
str) – The root directory of the mod project.
Note
Generated tests include: - Item registration verification - Food item property validation - Recipe validation and result ID checking - Complete mod integration testing Test files are placed in src/test/java/ following standard conventions.
- generate_fabric_game_tests(project_dir)[source]¶
Generate Fabric game tests for the mod.
Creates game tests that run within a Minecraft environment to validate mod functionality in actual gameplay conditions. These tests can interact with the world, place blocks, and test item behavior.
- Parameters:
project_dir (
str) – The root directory of the mod project.
Note
Generated game tests include: - Server-side item and block functionality testing - Client-side interaction and rendering validation - Block placement and world interaction tests Game test files are placed in src/gametest/java/ and require a separate fabric.mod.json for the test environment.
fabricpy.item module¶
Item registration and definition for Fabric mods.
This module provides the Item class for defining custom items in Minecraft Fabric mods. Items can have custom textures, recipes, stack sizes, and be assigned to creative tabs.
- class Item(id=None, name=None, max_stack_size=64, texture_path=None, recipe=None, item_group=None)[source]¶
Bases:
objectRepresents a custom item in a Fabric mod.
The Item class handles the definition of custom items including their properties, textures, recipes, and creative tab assignment. Items are registered with a ModConfig instance and compiled into the final mod.
- Parameters:
id (str | None) – The registry identifier for the item (e.g., “mymod:example_item”). If None, must be set before compilation.
name (str | None) – The display name for the item shown in-game. If None, must be set before compilation.
max_stack_size (int) – Maximum number of items that can be stacked together. Defaults to 64.
texture_path (str | None) – Path to the item’s texture file relative to mod resources. If None, a default texture will be used.
recipe (object | None) – Recipe definition for crafting this item. Can be a RecipeJson instance or None for no recipe.
item_group (object | str | None) – Creative tab to place this item in. Can be an ItemGroup instance, a string constant from item_group module, or None.
- recipe¶
Recipe definition for crafting this item.
- Type:
RecipeJson
- item_group¶
Creative tab assignment for the item.
- Type:
ItemGroup | str
Example
Creating a basic item:
item = Item( id="mymod:copper_sword", name="Copper Sword", max_stack_size=1, texture_path="textures/items/copper_sword.png", item_group=fabricpy.item_group.COMBAT )
Creating an item with a recipe:
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 )
- __init__(id=None, name=None, max_stack_size=64, texture_path=None, recipe=None, item_group=None)[source]¶
Initialize a new Item instance.
- Parameters:
id (str | None) – The registry identifier for the item.
name (str | None) – The display name for the item.
max_stack_size (int) – Maximum number of items that can be stacked.
texture_path (str | None) – Path to the item’s texture file.
recipe (object | None) – Recipe definition for crafting this item.
item_group (object | str | None) – Creative tab to place this item in.
fabricpy.fooditem module¶
Food item registration and definition for Fabric mods.
This module provides the FoodItem class, which extends the base Item class to support food-specific properties like nutrition, saturation, and eating behavior.
- class FoodItem(id=None, name=None, max_stack_size=64, texture_path=None, nutrition=0, saturation=0.0, always_edible=False, recipe=None, item_group=None)[source]¶
Bases:
ItemRepresents a custom food item in a Fabric mod.
FoodItem extends the base Item class to add food-specific properties including nutrition value, saturation, and whether the item can always be eaten regardless of hunger level.
- Parameters:
id (str | None) – The registry identifier for the food item (e.g., “mymod:golden_apple”). If None, must be set before compilation.
name (str | None) – The display name for the food item shown in-game. If None, must be set before compilation.
max_stack_size (int) – Maximum number of items that can be stacked together. Defaults to 64.
texture_path (str | None) – Path to the item’s texture file relative to mod resources. If None, a default texture will be used.
nutrition (int) – Number of hunger points restored when eaten (half-hearts on hunger bar). Defaults to 0.
saturation (float) – Saturation value provided when eaten. Higher values prevent hunger from decreasing quickly. Defaults to 0.0.
always_edible (bool) – Whether the food can be eaten even when the player’s hunger bar is full. Defaults to False.
recipe (object | None) – Recipe definition for crafting this food item. Can be a RecipeJson instance or None for no recipe.
item_group (object | str | None) – Creative tab to place this item in. Can be an ItemGroup instance, a string constant from item_group module, or None. Typically FOOD_AND_DRINK for food items.
Example
Creating a basic food item:
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 )
Creating a food item with a recipe:
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 )
- __init__(id=None, name=None, max_stack_size=64, texture_path=None, nutrition=0, saturation=0.0, always_edible=False, recipe=None, item_group=None)[source]¶
Initialize a new FoodItem instance.
- Parameters:
id (str | None) – The registry identifier for the food item.
name (str | None) – The display name for the food item.
max_stack_size (int) – Maximum number of items that can be stacked.
texture_path (str | None) – Path to the item’s texture file.
nutrition (int) – Number of hunger points restored when eaten.
saturation (float) – Saturation value provided when eaten.
always_edible (bool) – Whether the food can be eaten when hunger is full.
recipe (object | None) – Recipe definition for crafting this food item.
item_group (object | str | None) – Creative tab to place this item in.
fabricpy.block module¶
Block registration and definition for Fabric mods.
This module provides the Block class for defining custom blocks in Minecraft Fabric mods. Blocks can have custom textures for both the block itself and its inventory item representation, recipes for crafting, creative tab assignment, and full mining configuration including hardness, blast resistance, required tools, mining levels, and per-tool speed overrides.
Block event hooks supported:
- Left click (attack): AttackBlockCallback via Block.on_left_click()
- Right click (interact): UseBlockCallback via Block.on_right_click()
- After block break: PlayerBlockBreakEvents.AFTER via Block.on_break()
Hook methods can return a single action string, a list of action strings, or
None. Lists are automatically joined with newlines during code generation,
so there is no need to manually call "\n".join([...]).
- HookResult¶
Type alias for values returned by event hooks and accepted by constructor event parameters. Hooks may return a single Java code string, a list/tuple of strings (joined automatically), or
None.
- VALID_TOOL_TYPES = {'axe', 'hoe', 'pickaxe', 'shovel', 'sword'}¶
Valid tool types that can be used for
tool_typeandmining_speedskeys.
- VALID_MINING_LEVELS = {'diamond', 'iron', 'stone'}¶
Valid mining-level strings for
mining_level.
- class Block(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)[source]¶
Bases:
objectRepresents a custom block in a Fabric mod.
The Block class handles the definition of custom blocks including their properties, textures, recipes, and creative tab assignment. Blocks automatically generate corresponding BlockItems for inventory representation.
Mining behaviour is fully configurable through
hardness,resistance,tool_type,mining_level,requires_tool, andmining_speeds.- Parameters:
id (str | None) – The registry identifier for the block (e.g., “mymod:copper_block”). If None, must be set before compilation.
name (str | None) – The display name for the block shown in-game. If None, must be set before compilation.
max_stack_size (int) – Maximum number of block items that can be stacked together. Defaults to 64.
block_texture_path (str | None) – Path to the block’s texture file for world rendering relative to mod resources. If None, a default texture will be used.
inventory_texture_path (str | None) – Path to the texture used for the block’s item form in inventories. If None, falls back to block_texture_path.
recipe (object | None) – Recipe definition for crafting this block. Can be a RecipeJson instance or None for no recipe.
item_group (object | str | None) – Creative tab to place this block’s item in. Can be an ItemGroup instance, a string constant from item_group module, or None. Typically BUILDING_BLOCKS for most blocks.
left_click_event (HookResult) – Java code to execute when the block is left clicked. Can be a string, a list of strings (joined automatically), or None.
right_click_event (HookResult) – Java code to execute when the block is right clicked. Can be a string, a list of strings (joined automatically), or None.
break_event (HookResult) – Java code to execute after the block is broken/destroyed. The code runs server-side via
PlayerBlockBreakEvents.AFTER. Can be a string, a list of strings (joined automatically), or None.loot_table (object | None) – Loot table definition controlling what the block drops when broken. Can be a LootTable instance or None (defaults to dropping itself).
tool_type (str | None) – The primary tool required to mine this block efficiently. One of
"pickaxe","axe","shovel","hoe","sword", orNone(no specific tool required). Defaults toNone.hardness (float | None) – How long the block takes to mine. Lower values break faster. Vanilla reference values: dirt = 0.5, stone = 1.5, obsidian = 50. Defaults to
None(uses stone-equivalent 1.5).resistance (float | None) – Blast resistance against explosions. Vanilla reference values: stone = 6.0, obsidian = 1200. Defaults to
None(uses stone-equivalent 6.0).mining_level (str | None) – Minimum tool tier needed to mine the block and obtain drops. One of
"stone","iron","diamond", orNone(any tier works). Requiresrequires_tool=True(ortool_typeset) to be effective. Defaults toNone.requires_tool (bool | None) – Whether the correct tool must be used for the block to drop items. When
Nonethe value is inferred:Trueiftool_typeis set,Falseotherwise.mining_speeds (dict[str, float] | None) – A mapping of tool type strings (e.g.
"pickaxe","shovel") to custom mining-speed multipliers for this block. When provided, a custom block class is generated that overrides the per-tool break speed, enabling fine-grained control over how fast each tool type mines the block. The block is also automatically added to themineable/<tool>tags for every key in the dict. Defaults toNone.
- recipe¶
Recipe definition for crafting this block.
- Type:
RecipeJson
- item_group¶
Creative tab assignment for the block item.
- Type:
ItemGroup | str
- left_click_event¶
Java code executed on left click.
- Type:
str | list[str] | None
- right_click_event¶
Java code executed on right click.
- Type:
str | list[str] | None
- break_event¶
Java code executed after block is broken.
- Type:
str | list[str] | None
- loot_table¶
Loot table for block drops (defaults to dropping itself).
- Type:
LootTable | None
- hardness¶
Block hardness (mining time).
- Type:
float | None
- resistance¶
Blast resistance.
- Type:
float | None
- mining_level¶
Minimum tool tier for drops.
- Type:
str | None
- mining_speeds¶
Per-tool speed overrides.
- Type:
dict[str,float] | None
Example
Creating a basic block:
block = Block( id="mymod:copper_block", name="Copper Block", block_texture_path="textures/blocks/copper_block.png", item_group=fabricpy.item_group.BUILDING_BLOCKS )
Creating a block with mining configuration:
block = 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 = 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", )
- __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)[source]¶
Initialize a new Block instance.
- Parameters:
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.
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. Can be a string, a list of strings, or None. 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. Can be a string, a list of strings, or None. Prefer overriding
on_right_click()in a subclass.break_event (str | Sequence[str] | None) – Java code to execute after the block is broken. Can be a string, a list of strings, or None. 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.
hardness (float | None) – Block hardness (mining time base).
resistance (float | None) – Blast resistance.
mining_level (str | None) – Minimum tool tier (
"stone","iron", or"diamond").requires_tool (bool | None) – Whether correct tool is required for drops. Inferred from
tool_typewhenNone.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 recognised value.
- on_left_click()[source]¶
Java code executed when the block is left clicked.
Subclasses can override this to return a string of Java statements, a list of strings (joined automatically), or
None. The default implementation returns the value ofleft_click_eventpassed to the constructor.ActionResult.SUCCESSis automatically returned, so only include the statements to run when the block is clicked.Example:
def on_left_click(self): return [ drop_item("DIAMOND", count=3), play_sound("EXPERIENCE_ORB_PICKUP"), give_xp(25), ]
- on_right_click()[source]¶
Java code executed when the block is right clicked.
Subclasses can override this to return a string of Java statements, a list of strings (joined automatically), or
None. The default implementation returnsright_click_eventfrom the constructor.ActionResult.SUCCESSis automatically returned.Example:
def on_right_click(self): return [ apply_effect("SPEED", 600, 1), play_sound("WITCH_DRINK"), send_message("You feel energised!"), ]
- on_break()[source]¶
Java code executed after the block is broken (destroyed).
This hook fires server-side after the block has been successfully removed from the world via
PlayerBlockBreakEvents.AFTER. The callback receivesworld,player,pos,state(the block state before breaking), andentity(theBlockEntity, may benull).Subclasses can override this to return a string of Java statements, a list of strings (joined automatically), or
None. The default implementation returnsbreak_eventfrom the constructor.Example:
def on_break(self): return [ summon_lightning(), play_sound("LIGHTNING_BOLT_THUNDER"), ]
fabricpy.toolitem module¶
Tool item registration and definition for Fabric mods.
This module provides the ToolItem class, which extends the base Item class with tool-specific properties such as durability and mining characteristics.
- class ToolItem(id=None, name=None, max_stack_size=1, texture_path=None, durability=0, mining_speed_multiplier=1.0, attack_damage=1.0, mining_level=0, enchantability=0, repair_ingredient=None, recipe=None, item_group=None)[source]¶
Bases:
ItemRepresents a tool item in a Fabric mod.
ToolItem extends the base
Itemclass to add properties relevant to tools and weapons, including durability, mining speed, attack damage, mining level, enchantability and a repair ingredient.- Parameters:
id (str | None) – The registry identifier for the tool item (e.g.,
"mymod:obsidian_pickaxe"). IfNone, must be set before compilation.name (str | None) – The display name for the tool item shown in-game. If
None, must be set before compilation.max_stack_size (int) – Maximum number of items that can be stacked together. Defaults to
1for tools.texture_path (str | None) – Path to the item’s texture file relative to mod resources. If
None, a default texture will be used.durability (int) – Number of uses before the tool breaks. Defaults to
0.mining_speed_multiplier (float) – Speed multiplier when mining blocks. Defaults to
1.0.attack_damage (float) – Damage dealt when used as a weapon. Defaults to
1.0.mining_level (int) – Mining level of the tool. Defaults to
0.enchantability (int) – How easily the tool can receive enchantments. Defaults to
0.repair_ingredient (str | None) – Item ID used to repair the tool. Defaults to
None.recipe (object | None) – Recipe definition for crafting this tool item. Can be a
RecipeJsoninstance orNonefor no recipe.item_group (object | str | None) – Creative tab to place this item in. Can be an
ItemGroupinstance, a string constant fromfabricpy.item_group, orNone.
- repair_ingredient¶
Item ID used to repair the tool.
- Type:
str | None
Example
Creating a ruby pickaxe:
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", )
fabricpy.itemgroup module¶
Custom creative tab (ItemGroup) creation for Fabric mods.
This module provides the ItemGroup class for creating custom creative tabs in Minecraft. Custom ItemGroups allow you to organize your mod’s items and blocks into their own dedicated creative inventory tabs.
Example
Creating a custom creative tab:
import fabricpy
# Create a custom creative tab
grp = fabricpy.ItemGroup(id="new_foods", name="New Foods")
grp.set_icon(MyFoodItem)
# Assign items to the custom tab
item = fabricpy.Item(
id="mymod:special_apple",
name="Special Apple",
item_group=grp
)
- class ItemGroup(item_id=None, name=None, icon=None, id=None)[source]¶
Bases:
objectRepresents a custom creative tab (ItemGroup) in a Fabric mod.
ItemGroups are the tabs shown in the creative inventory that organize items and blocks by category. This class allows creation of custom tabs for mod content.
- Parameters:
item_id (str) – The registry identifier for the ItemGroup (e.g., “new_foods”). This should be unique and follow mod naming conventions.
name (str) – The display name shown to players in the creative inventory. This is used as the language key for localization.
icon (Optional[Type]) – The item class or instance whose ItemStack will be displayed as the tab icon. Can be set later using set_icon().
- icon¶
The item class used as the tab icon.
- Type:
Optional[Type]
Example
Creating a food-themed creative tab:
# Create the ItemGroup food_group = ItemGroup( item_id="my_mod_foods", name="My Mod Foods" ) # Set an icon (using an existing item class) food_group.set_icon(AppleItem) # Use in item definitions golden_apple = Item( id="mymod:golden_apple", name="Golden Apple", item_group=food_group )
- __init__(item_id=None, name=None, icon=None, id=None)[source]¶
Initialize a new ItemGroup.
- Parameters:
item_id (str) – The registry identifier for the ItemGroup. Should be unique and follow standard mod naming conventions (lowercase, underscores). Can also be passed as ‘id’ for convenience.
name (str) – The display name shown in the creative inventory. This will be used as a language key for localization.
icon (Type | None) – Optional item class to use as the tab icon. Can be set later using set_icon().
id (str) – Alias for item_id. Use either ‘id’ or ‘item_id’, not both.
- Raises:
ValueError – If both id and item_id are provided.
Example
Basic ItemGroup creation:
tools_group = ItemGroup(item_id="my_tools", name="My Tools") # or equivalently: tools_group = ItemGroup(id="my_tools", name="My Tools")
With initial icon:
weapons_group = ItemGroup( id="my_weapons", name="My Weapons", icon=MySwordItem )
Note
While None values are technically allowed for error handling scenarios, proper usage requires both an ID and name for the ItemGroup to function correctly in mod compilation.
- property id: str¶
Get the ItemGroup’s ID.
- Returns:
The registry identifier for this ItemGroup.
- Return type:
Note
This is an alias for item_id to maintain compatibility with tests and existing code that expects an ‘id’ property.
- property icon_item_id: 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.
- Returns:
- The item ID of the icon, or None if no icon is set
or the icon has no ID attribute.
- Return type:
str | None
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"
- set_icon(icon)[source]¶
Set the icon item for this ItemGroup.
The icon appears on the creative inventory tab and should represent the category of items contained within the group.
- Parameters:
icon (Type) – The item class whose ItemStack will be displayed as the tab icon. This should be a class that extends Item, FoodItem, or Block.
Example
Setting a custom icon:
magic_group = ItemGroup("magic_items", "Magic Items") magic_group.set_icon(MagicWandItem)
Note
The icon item should be registered before the ItemGroup is used in mod compilation to ensure proper icon rendering.
- __eq__(other)[source]¶
Check equality with another ItemGroup.
Two ItemGroups are considered equal if they have the same ID, regardless of their name or icon.
- Parameters:
other (object) – The object to compare with.
- Returns:
True if both objects are ItemGroups with the same ID.
- Return type:
Example
Comparing ItemGroups:
group1 = ItemGroup(id="weapons", name="Weapons") group2 = ItemGroup(id="weapons", name="Combat Items") print(group1 == group2) # True (same ID)
fabricpy.recipejson module¶
Recipe JSON handling for Fabric mods.
This module provides the RecipeJson class for defining and managing Minecraft recipe data. Recipes define how items and blocks can be crafted, smelted, or otherwise created through various game mechanics.
The RecipeJson class handles both string and dictionary representations of recipe data, with validation and convenient access to recipe properties.
- class RecipeJson(src)[source]¶
Bases:
objectWrapper for Minecraft recipe JSON data.
This class holds a validated dictionary representation of a Minecraft recipe along with the original JSON text. It provides validation, convenient property access, and ensures the exact text can be written back to disk unchanged.
Recipes define how items are crafted, smelted, or created through other game mechanics. They must follow Minecraft’s recipe JSON format.
- Parameters:
src (
str | dict[str,Any]) – Recipe data as either a JSON string or a dictionary. If a string, it will be parsed as JSON. If a dict, it will be used directly and converted to JSON text.
- data¶
The parsed dictionary representation of the recipe.
- Type:
dict[str,Any]
- Raises:
ValueError – If the recipe is missing a required ‘type’ field or has an invalid ‘type’ value.
json.JSONDecodeError – If the input string is not valid JSON.
Example
Creating a recipe from JSON string:
recipe_json = ''' { "type": "minecraft:crafting_shaped", "pattern": ["##", "##"], "key": {"#": "minecraft:stone"}, "result": {"id": "mymod:stone_block", "count": 1} } ''' recipe = RecipeJson(recipe_json)
Creating a recipe from dictionary:
recipe_data = { "type": "minecraft:smelting", "ingredient": "minecraft:iron_ore", "result": "minecraft:iron_ingot", "experience": 0.7, "cookingtime": 200 } recipe = RecipeJson(recipe_data)
Getting the result item ID:
result_id = recipe.result_id # "mymod:stone_block"
- __init__(src)[source]¶
Initialize a new RecipeJson instance.
- Parameters:
src (
str | dict[str,Any]) – Recipe data as JSON string or dictionary.- Raises:
ValueError – If recipe is missing ‘type’ field or has invalid ‘type’.
json.JSONDecodeError – If input string is not valid JSON.
- property result_id: str | None¶
Get the result item identifier from the recipe.
Extracts the item ID from the recipe’s result field, which is used to name the generated recipe JSON file. Handles both string and dictionary result formats.
- Returns:
- The result item identifier (e.g., “mymod:stone_block”),
or None if no valid result ID is found.
- Return type:
str | None
Example
Getting result ID from different recipe formats:
# String result format recipe1 = RecipeJson({"type": "minecraft:smelting", "result": "minecraft:iron_ingot"}) print(recipe1.result_id) # "minecraft:iron_ingot" # Dictionary result format (1.21+) recipe2 = RecipeJson({ "type": "minecraft:crafting_shaped", "result": {"id": "mymod:custom_item", "count": 2} }) print(recipe2.result_id) # "mymod:custom_item" # Dictionary result format (pre-1.21) recipe3 = RecipeJson({ "type": "minecraft:crafting_shaped", "result": {"item": "mymod:legacy_item", "count": 1} }) print(recipe3.result_id) # "mymod:legacy_item"
- get_result_id()[source]¶
Get the result ID from the recipe.
This is an alias for the result_id property, provided for backward compatibility and explicit method-style access.
- Returns:
The result item identifier, or None if not found.
- Return type:
str | None
Example
Using the method-style accessor:
recipe = RecipeJson({"type": "minecraft:smelting", "result": "minecraft:iron_ingot"}) result = recipe.get_result_id() # "minecraft:iron_ingot"
fabricpy.loottable module¶
Loot table definition and generation for Fabric mods.
This module provides the LootTable class for defining loot tables that
control what items are dropped when blocks are broken, entities are killed,
or chests are opened in Minecraft. It supports both raw JSON input and
convenient builder-style class methods for common patterns such as blocks
that drop themselves, silk-touch-only drops, and fortune-affected ore drops.
Loot table JSON files follow the Minecraft data-pack format and are written
to data/<mod_id>/loot_table/<category>/<name>.json during compilation.
Tested against Minecraft 1.21+ / Fabric-API 0.141.3.
- class LootPool[source]¶
Bases:
objectFluent builder for a single loot-table pool.
A pool specifies a set of entries, how many rolls to make, and optional conditions or functions applied to the whole pool.
Example
Building a pool manually:
pool = ( LootPool() .rolls(1) .entry("mymod:ruby", weight=3) .entry("mymod:sapphire", weight=1) .condition({"condition": "minecraft:survives_explosion"}) .build() )
- entry(item_id, *, weight=None, quality=None, conditions=None, functions=None)[source]¶
Add an
minecraft:itementry to this pool.- Parameters:
item_id (str) – Registry identifier of the item (e.g.
"mymod:ruby").weight (int | None) – Relative weight for random selection among entries.
quality (int | None) – Luck-based weight modifier.
conditions (List[Dict[str, Any]] | None) – Entry-level conditions.
functions (List[Dict[str, Any]] | None) – Entry-level item-modifier functions.
- class LootTable(src, *, loot_type=None, category='blocks')[source]¶
Bases:
objectWrapper for Minecraft loot-table JSON data.
A
LootTableholds a validated dictionary representation of a Minecraft loot table. It can be created from raw JSON, a plain dict, or via convenient class-method builders for common patterns.The finished object is attached to a
Block(via itsloot_tableattribute) or registered directly withModConfigfor entity / chest loot tables. Duringcompile()the JSON file is written to the appropriatedata/<mod_id>/loot_table/directory.- Parameters:
src (str | Dict[str, Any] | List[LootPool]) – Loot-table data as a JSON string, a dictionary, or a list of
LootPoolbuilder objects. When pools are passed theloot_typekeyword is required.loot_type (str | None) – The
"type"field value (e.g."minecraft:block","minecraft:entity"). Required when src is a pool list; otherwise inferred from the dict/JSON.category (str) – Sub-directory under
loot_table/when written to disk (e.g."blocks","entities","chests"). Defaults to"blocks".
- data¶
The parsed dictionary representation.
- Type:
dict[str,Any]
- Raises:
ValueError – If the loot table is missing the
"type"field.json.JSONDecodeError – If a string src is not valid JSON.
Example
Creating a loot table from a dictionary:
lt = LootTable({ "type": "minecraft:block", "pools": [{ "rolls": 1, "entries": [{"type": "minecraft:item", "name": "mymod:my_block"}], "conditions": [{"condition": "minecraft:survives_explosion"}] }] })
Using a builder class method:
lt = LootTable.drops_self("mymod:ruby_block")
- classmethod drops_self(block_id)[source]¶
Create a loot table where the block drops itself.
This is the most common loot table pattern — the block simply drops one of itself when broken, subject to explosion protection.
- Parameters:
block_id (str) – Registry identifier of the block (e.g.
"mymod:ruby_block").- Returns:
A loot table configured for self-drops.
- Return type:
Example
lt = LootTable.drops_self("mymod:ruby_block") block = Block( id="mymod:ruby_block", name="Ruby Block", loot_table=lt, )
- classmethod drops_item(block_id, item_id, count=1, *, min_count=None, max_count=None)[source]¶
Create a loot table where the block drops a specific item.
- Parameters:
block_id (str) – Registry identifier of the block being broken.
item_id (str) – The item to drop.
count (int) – Fixed number to drop (used when min_count / max_count are not provided).
min_count (int | None) – Minimum items dropped (uniform distribution).
max_count (int | None) – Maximum items dropped (uniform distribution).
- Returns:
A configured loot table.
- Return type:
Example
lt = LootTable.drops_item( "mymod:ruby_ore", "mymod:ruby", min_count=1, max_count=3, )
- classmethod drops_nothing()[source]¶
Create an empty loot table (the block drops nothing).
- Returns:
A loot table with no pools.
- Return type:
Example
lt = LootTable.drops_nothing()
- classmethod drops_with_silk_touch(block_id, silk_touch_item=None, *, no_silk_touch_item=None, no_silk_touch_count=1)[source]¶
Create a loot table with silk-touch behaviour.
When mined with Silk Touch the silk_touch_item is dropped (defaults to block_id). When mined without Silk Touch, no_silk_touch_item is dropped if provided, otherwise nothing.
- Parameters:
- Returns:
A configured loot table.
- Return type:
Example
Glass-style — drops itself with silk touch, nothing otherwise:
lt = LootTable.drops_with_silk_touch("mymod:crystal_glass")
Ore-style — silk touch gives ore block, otherwise raw material:
lt = LootTable.drops_with_silk_touch( "mymod:ruby_ore", no_silk_touch_item="mymod:ruby", no_silk_touch_count=1, )
- classmethod drops_with_fortune(block_id, item_id, *, min_count=1, max_count=1, silk_touch_drops_self=True)[source]¶
Create a fortune-affected loot table (ore-style drops).
Mimics vanilla ore behaviour: without Silk Touch the block drops item_id with fortune scaling; with Silk Touch the block drops itself (if silk_touch_drops_self is
True).- Parameters:
- Returns:
A configured loot table.
- Return type:
Example
lt = LootTable.drops_with_fortune( "mymod:ruby_ore", "mymod:ruby", min_count=1, max_count=2, )
- classmethod entity(pools)[source]¶
Create an entity loot table from a list of pools.
- Parameters:
pools (List[LootPool | Dict[str, Any]]) – List of
LootPoolbuilders or raw pool dicts.- Returns:
A loot table with
typeset tominecraft:entity.- Return type:
Example
lt = LootTable.entity([ LootPool() .rolls(1) .entry("mymod:monster_fang", weight=1) .condition({"condition": "minecraft:survives_explosion"}) ])
- classmethod chest(pools)[source]¶
Create a chest loot table from a list of pools.
- Parameters:
pools (List[LootPool | Dict[str, Any]]) – List of
LootPoolbuilders or raw pool dicts.- Returns:
A loot table with
typeset tominecraft:chest.- Return type:
Example
lt = LootTable.chest([ LootPool() .rolls({"type": "minecraft:uniform", "min": 2, "max": 4}) .entry("mymod:golden_key", weight=5) .entry("minecraft:diamond", weight=1) ])
fabricpy.item_group module¶
Vanilla creative tab identifiers for Minecraft Fabric mods.
This module provides string constants for all vanilla Minecraft creative tabs (CreativeModeTabs). These constants match the names used in net.minecraft.world.item.CreativeModeTabs and can be used when assigning items and blocks to creative tabs.
The constants provided here represent the standard creative tabs available in vanilla Minecraft. For custom creative tabs, use the ItemGroup class instead.
Example
Assigning an item to a vanilla creative tab:
import fabricpy
item = fabricpy.Item(
id="mymod:copper_sword",
name="Copper Sword",
item_group=fabricpy.item_group.COMBAT
)
block = fabricpy.Block(
id="mymod:marble_block",
name="Marble Block",
item_group=fabricpy.item_group.BUILDING_BLOCKS
)
- BUILDING_BLOCKS
Building blocks and construction materials.
- Type:
- NATURAL
Natural blocks like stone, dirt, and ores.
- Type:
- FUNCTIONAL
Functional blocks like crafting tables and furnaces.
- Type:
- REDSTONE
Redstone components and mechanisms.
- Type:
- TOOLS
Tools and utility items.
- Type:
- COMBAT
Weapons, armor, and combat-related items.
- Type:
- FOOD_AND_DRINK
Food items and potions.
- Type:
- INGREDIENTS
Crafting ingredients and materials.
- Type:
- SPAWN_EGGS
Spawn eggs for entities.
- Type:
- BUILDING_BLOCKS = 'building_blocks'
Creative tab for building blocks and construction materials.
- Type:
- NATURAL = 'natural_blocks'
Creative tab for natural blocks like stone, dirt, and ores.
- Type:
- FUNCTIONAL = 'functional_blocks'
Creative tab for functional blocks like crafting tables and furnaces.
- Type:
- REDSTONE = 'redstone_blocks'
Creative tab for redstone components and mechanisms.
- Type:
- TOOLS = 'tools_and_utilities'
Creative tab for tools and utility items.
- Type:
- COMBAT = 'combat'
Creative tab for weapons, armor, and combat-related items.
- Type:
- FOOD_AND_DRINK = 'food_and_drinks'
Creative tab for food items and potions.
- Type:
- INGREDIENTS = 'ingredients'
Creative tab for crafting ingredients and materials.
- Type:
- SPAWN_EGGS = 'spawn_eggs'
Creative tab for spawn eggs for entities.
- Type:
fabricpy.actions module¶
Action helper functions for generated Fabric mods.
These helpers return Java code snippets that perform in-game actions such as
replacing blocks, teleporting players, applying potion effects, and more.
They are intended for use in block event handlers (Block.on_left_click(),
Block.on_right_click(), Block.on_break()).
All functions return a string of Java source code. Multiple actions can be combined by returning them as a list from a hook method — the framework joins them automatically.
The default variable names (player, world, pos) match the
parameter names available inside every block event callback generated by
fabricpy. Override them only if you use a custom callback signature.
Example
Using actions inside a block hook:
from fabricpy.actions import (
summon_lightning, play_sound, give_xp, launch_player,
)
class ThunderBlock(fabricpy.Block):
def on_break(self):
return [
summon_lightning(),
play_sound("LIGHTNING_BOLT_THUNDER"),
give_xp(50),
launch_player(dy=1.5),
]
- replace_block(block, *, pos_var='pos', world_var='world')[source]¶
Replace the block at the event position with another block.
- Parameters:
- Returns:
Java code that replaces the block.
- Return type:
Example:
replace_block("DIAMOND_BLOCK") # → world.setBlockAndUpdate(pos, Blocks.DIAMOND_BLOCK.defaultBlockState());
- teleport_player(x, y, z, *, relative=False, player_var='player', pos_var='pos')[source]¶
Teleport the player to a position.
- Parameters:
x (float) – X coordinate (absolute, or offset when relative is
True).y (float) – Y coordinate (absolute, or offset when relative is
True).z (float) – Z coordinate (absolute, or offset when relative is
True).relative (bool) – When
Truethe coordinates are offsets from the block position referenced by pos_var.player_var (str) – Name of the player variable in scope.
pos_var (str) – Name of the
BlockPosvariable in scope (used when relative isTrue).
- Returns:
Java code that teleports the player.
- Return type:
Example:
teleport_player(100, 200, 100) # absolute teleport_player(0, 10, 0, relative=True) # 10 blocks above the block
- apply_effect(effect, duration=200, amplifier=0, *, player_var='player')[source]¶
Apply a potion / status effect to the player.
- Parameters:
effect (str) –
MobEffectsconstant name (Mojang mappings), e.g."SPEED","STRENGTH","REGENERATION","NIGHT_VISION","INVISIBILITY","JUMP_BOOST","SLOW_FALLING","POISON","FIRE_RESISTANCE","LUCK".duration (int) – Duration in ticks (20 ticks = 1 second). Defaults to 200 (10 seconds).
amplifier (int) – Effect amplifier (0 = level I, 1 = level II, …).
player_var (str) – Name of the player variable in scope.
- Returns:
Java code that applies the effect.
- Return type:
Example:
apply_effect("SPEED", duration=600, amplifier=1)
- play_sound(sound, volume=1.0, pitch=1.0, *, source='BLOCKS', pos_var='pos', world_var='world')[source]¶
Play a sound at the block position.
- Parameters:
sound (str) –
SoundEventsconstant name (Mojang mappings — without theENTITY_/BLOCK_/ITEM_prefix), e.g."LIGHTNING_BOLT_THUNDER","ANVIL_LAND","EXPERIENCE_ORB_PICKUP","ENDER_DRAGON_GROWL".volume (float) – Sound volume (1.0 = normal).
pitch (float) – Sound pitch (1.0 = normal, higher = faster).
source (str) –
SoundSourceconstant:"BLOCKS","PLAYERS","HOSTILE","NEUTRAL","MASTER", etc.pos_var (str) – Name of the
BlockPosvariable in scope.world_var (str) – Name of the
Levelvariable in scope.
- Returns:
Java code that plays the sound.
- Return type:
Note
Use Mojang-mapped field names (without
ENTITY_/BLOCK_/ITEM_prefixes). A handful ofSoundEventsfields areHolder<SoundEvent>rather than plainSoundEvent(e.g.NOTE_BLOCK_PLING,UI_BUTTON_CLICK). These are not compatible with this helper — use a plainSoundEventfield instead (the vast majority).Example:
play_sound("ANVIL_LAND", volume=2.0, pitch=1.5)
- summon_lightning(*, pos_var='pos', world_var='world')[source]¶
Summon a lightning bolt at the block position.
Only fires on the logical server (
ServerLevelcheck).- Parameters:
- Returns:
Java code that summons lightning.
- Return type:
Example:
summon_lightning()
- drop_item(item, count=1, *, pos_var='pos', world_var='world')[source]¶
Drop item(s) at the block position.
- Parameters:
- Returns:
Java code that drops items.
- Return type:
Example:
drop_item("DIAMOND", count=3)
- launch_player(dx=0.0, dy=1.0, dz=0.0, *, player_var='player')[source]¶
Launch the player upward or apply knockback.
Adds to the player’s velocity and marks it for immediate client sync.
- Parameters:
- Returns:
Java code that launches the player.
- Return type:
Example:
launch_player(dy=2.0) # launch straight up launch_player(dx=3.0, dy=0.5, dz=0.0) # knockback sideways
- place_fire(*, above=True, pos_var='pos', world_var='world')[source]¶
Place fire at or above the block position.
Only places fire if the target position is currently air.
- Parameters:
- Returns:
Java code that places fire.
- Return type:
Example:
place_fire() # fire above the block place_fire(above=False) # fire at the block position
- extinguish_area(radius=3, *, pos_var='pos', world_var='world')[source]¶
Extinguish fire blocks in a cubic radius around the position.
- Parameters:
- Returns:
Java code that replaces all
FIREblocks withAIR.- Return type:
Example:
extinguish_area(radius=5)
- give_xp(amount, *, player_var='player')[source]¶
Give experience points to the player.
- Parameters:
- Returns:
Java code that gives XP.
- Return type:
Example:
give_xp(100)
- remove_xp(amount, *, player_var='player')[source]¶
Remove experience points from the player.
- Parameters:
- Returns:
Java code that removes XP (passes a negative value internally).
- Return type:
Example:
remove_xp(50)
- damage_nearby(amount, radius=5.0, *, exclude_player=True, pos_var='pos', world_var='world', player_var='player')[source]¶
Damage nearby living entities with magic damage.
- Parameters:
amount (float) – Damage amount (half-hearts).
radius (float) – Search radius in blocks (default 5).
exclude_player (bool) – If
True(default), the triggering player is excluded from the damage.pos_var (str) – Name of the
BlockPosvariable in scope.world_var (str) – Name of the
Levelvariable in scope.player_var (str) – Name of the player variable in scope.
- Returns:
Java code that damages nearby entities.
- Return type:
Example:
damage_nearby(6.0, radius=8.0)
- heal_nearby(amount, radius=5.0, *, pos_var='pos', world_var='world')[source]¶
Heal nearby living entities.
- Parameters:
- Returns:
Java code that heals nearby entities.
- Return type:
Example:
heal_nearby(4.0, radius=10.0)
- delayed_action(action_code, ticks=20, *, world_var='world')[source]¶
Schedule an action to run after a delay.
Wraps the given Java code in a
TickTaskscheduled on the server, guarded by aServerLevelinstanceof check.- Parameters:
- Returns:
Java code that schedules the delayed action.
- Return type:
Example:
delayed_action(give_xp(100), ticks=40) # give XP after 2 seconds delayed_action(summon_lightning(), ticks=60)
- sculk_event(event, *, pos_var='pos', world_var='world', player_var='player')[source]¶
Emit a game event that sculk sensors can detect.
- Parameters:
event (str) –
GameEventconstant name, e.g."BLOCK_CHANGE","BLOCK_DESTROY","EXPLODE","STEP","ENTITY_SHAKE","NOTE_BLOCK_PLAY","INSTRUMENT_PLAY","LIGHTNING_STRIKE".pos_var (str) – Name of the
BlockPosvariable in scope.world_var (str) – Name of the
Levelvariable in scope.player_var (str) – Name of the player variable in scope (emitter).
- Returns:
Java code that emits the game event.
- Return type:
Example:
sculk_event("BLOCK_CHANGE") sculk_event("EXPLODE")