### Example Tinkers Construct Recipes (1.19.2/1.18.2 and below) Source: https://kubejs.com/wiki/addons/tinkers-construct Example script demonstrating how to create Tinkers Construct casting table and basin recipes using KubeJS for older game versions. Includes examples for single-use casts and custom cast materials. ```javascript onEvent('recipes', event => { const { casting_table, casting_basin } = event.recipes.tconstruct casting_table('minecraft:carrot', 'minecraft:water').singleUseCast('nugget') casting_basin('minecraft:coal_block', 'minecraft:lava') casting_basin('minecraft:emerald', 'minecraft:water').cast('#forge:dusts/emerald') }) ``` -------------------------------- ### Vacuumizing Recipe Example Source: https://kubejs.com/wiki/addons/vintage-kubejs Defines a vacuumizing recipe using the Compressor and Basin with a specified processing time. ```javascript ServerEvents.recipes(event => { event.recipes.vintageimprovements.vacuumizing('minecraft:powder_snow_bucket', ['minecraft:bucket', 'minecraft:snow_block']).processingTime(500) }) ``` -------------------------------- ### Recipe JSON Insertion Example Source: https://kubejs.com/wiki/addons/probejs Demonstrates direct insertion of recipe JSONs using ProbeJS, simplifying recipe creation. ```javascript event.recipes.kubejs.custom_recipe({"type": "minecraft:smelting", "ingredient": {"item": "minecraft:iron_ore"}, "result": "minecraft:iron_ingot", "experience": 0.7, "cookingtime": 200}); ``` -------------------------------- ### KubeJS Shaped Recipe Examples Source: https://kubejs.com/wiki/test Examples of defining shaped recipes for different KubeJS versions. ```javascript ServerEvents.recipes(event => { event.shaped( Item.of('minecraft:stone', 3), // arg 1: output [ 'A B', ' C ', // arg 2: the shape (array of strings) 'B A' ], { A: 'minecraft:andesite', B: 'minecraft:diorite', //arg 3: the mapping object C: 'minecraft:granite' } ) }) ``` ```javascript onEvent('recipes', event => { event.shaped( Item.of('minecraft:stone', 3), // arg 1: output [ 'A B', ' C ', // arg 2: the shape (array of strings) 'B A' ], { A: 'minecraft:andesite', B: 'minecraft:diorite', //arg 3: the mapping object C: 'minecraft:granite' } ) }) ``` -------------------------------- ### Turning Recipe Example Source: https://kubejs.com/wiki/addons/vintage-kubejs Defines a turning recipe for the Lathe, supporting custom processing times. ```javascript ServerEvents.recipes(event => { event.recipes.vintageimprovements.turning(Item.of('create:fluid_pipe', 12), 'minecraft:copper_block').processingTime(300) }) ``` -------------------------------- ### Create Sequenced Assembly Recipes Source: https://kubejs.com/wiki/addons/create Examples of defining complex sequenced assembly recipes with multiple outputs and processing steps. ```javascript ServerEvents.recipes(event => { event.recipes.create.sequenced_assembly( // Outputs: [ CreateItem.of('create:precision_mechanism', 0.13), // Main output, will appear in JEI as the result CreateItem.of('create:golden_sheet', 0.008), // Rest of these items will be considered Random Salvage CreateItem.of('create:andesite_alloy', 0.008), CreateItem.of('create:cogwheel', 0.005), CreateItem.of('create:shaft', 0.002), CreateItem.of('create:crushed_gold_ore', 0.002), CreateItem.of('2x minecraft:gold_nugget', 0.002), CreateItem.of('minecraft:iron_ingot', 0.001), CreateItem.of('minecraft:clock', 0.001) ], // Input: 'create:golden_sheet', // Sequence: [ // The transitional item set by `transitionalItem('create:incomplete_large_cogwheel')` is the item used during the intermediate stages of the assembly // Like a normal recipe function, it's used as a sequence step in this array. Input and output have the transitional item event.recipes.create.deploying('create:incomplete_precision_mechanism', ['create:incomplete_precision_mechanism', 'create:cogwheel',]), event.recipes.create.deploying('create:incomplete_precision_mechanism', ['create:incomplete_precision_mechanism', 'create:large_cogwheel',]), event.recipes.create.deploying('create:incomplete_precision_mechanism', ['create:incomplete_precision_mechanism', 'minecraft:iron_nugget',]), ] ) .transitionalItem('create:incomplete_precision_mechanism') // Set the transitional item .loops(5) // Set the number of loops // For this code to work, kubejs:incomplete_spore_blossom needs to be added to the game const transitional = 'kubejs:incomplete_spore_blossom' // Making a constant to store the transitional item makes the code more readable event.recipes.create.sequenced_assembly( // Outputs: [ CreateItem.of('minecraft:spore_blossom', 0.16), // Main output, will appear in JEI as the result CreateItem.of('minecraft:flowering_azalea_leaves', 0.16), // Rest of these items will be considered Random Salvage CreateItem.of('minecraft:azalea_leaves', 0.02), CreateItem.of('minecraft:oak_leaves', 0.01), CreateItem.of('minecraft:spruce_leaves', 0.01), CreateItem.of('minecraft:birch_leaves', 0.01), CreateItem.of('minecraft:jungle_leaves', 0.01), CreateItem.of('minecraft:acacia_leaves', 0.01), CreateItem.of('minecraft:dark_oak_leaves', 0.01) ], // Input: 'minecraft:flowering_azalea_leaves', // Sequence: [ // The transitional item is a constant, that is 'kubejs:incomplete_spore_blossom' and is used during the intermediate stages of the assembly. // Like a normal recipe function, is used as a sequence step in this array. Input and output have the transitional item. event.recipes.create.pressing(transitional, transitional), event.recipes.create.deploying(transitional, [transitional, 'minecraft:hanging_roots']), event.recipes.create.filling(transitional, [transitional, Fluid.of('minecraft:water', 420)]), event.recipes.create.deploying(transitional, [transitional, 'minecraft:moss_carpet']), event.recipes.create.cutting(transitional, transitional) ] ) .transitionalItem(transitional) // Set the transitional item .loops(2) // Set the number of loops }) ``` -------------------------------- ### Example Blood Magic Script (1.19.2+ and 1.18.2 and below) Source: https://kubejs.com/wiki/addons/blood-magic A comprehensive example script demonstrating how to use various Blood Magic recipe functions in KubeJS for older Minecraft versions. Ensure the addon is compatible with your version. ```javascript onEvent('recipes', event => { const { altar, array, soulforge, arc, alchemytable } = event.recipes.bloodmagic alchemytable('minecraft:gold_ingot', ['minecraft:iron_ingot', 'minecraft:iron_ingot', 'minecraft:iron_ingot', 'minecraft:iron_ingot']).upgradeLevel(2) altar('minecraft:carrot', 'minecraft:apple') arc('minecraft:netherite_ingot', 'minecraft:iron_ingot', 'minecraft:iron_pickaxe', [Item.of('minecraft:cobblestone').withChance(0.4)]) array('minecraft:spruce_planks', 'minecraft:oak_planks', 'minecraft:birch_planks') soulforge('minecraft:stone', ['minecraft:gold_ore', 'minecraft:diamond_ore', 'minecraft:iron_ore']).drain(1) }) ``` -------------------------------- ### Add Tooltips with Basic and Shift Requirements Source: https://kubejs.com/wiki/events/ItemEvents/modifyTooltips Demonstrates adding tooltips to items. The first example adds a red tooltip to all red blocks. The subsequent examples show how to add tooltips to 'minecraft:campfire' conditionally based on whether the shift key is pressed. ```javascript ItemEvents.modifyTooltips(event => { // Show this tooltip for all red blocks event.add(/minecraft:red_/, Text.red('Red!')) // Only show this text when shift is not pressed event.add('minecraft:campfire', {shift: false}, Text.gray('Campfire :D')) // Only show this text when shift is pressed event.add('minecraft:campfire', {shift: true}, Text.gray('Campfire :(')) }) ``` -------------------------------- ### Add Freezing Recipe Source: https://kubejs.com/wiki/addons/garnished Use this to add a freezing recipe. This example shows how to create powder snow from water. ```javascript event.recipes.garnished.freezing('minecraft:powder_snow_bucket', 'minecraft:water_bucket', 200).id('garnished_kubejs:freezing/powder_snow_bucket_from_water_bucket') ``` -------------------------------- ### Check and Get Chemical Block Info Source: https://kubejs.com/wiki/addons/alchemistry-chemlib/helpers This example demonstrates how to check if a block is a chemical block and retrieve its chemical abbreviation and color when a player right-clicks it. It only runs on the server side. ```javascript BlockEvents.rightClicked(event => { const { player, block, level } = event if (level.isClientSide()) return if (ChemicalBlock.isChemicalBlock(block.id)) { const color = ChemicalBlock.getChemicalColor(block) const chemical = ChemicalBlock.getBlockChemical(block) player.sendSystemMessage( "Chemical Block: " + chemical.getAbbreviation() + ", Color: " + color ) } }) ``` -------------------------------- ### Get Player List with Beans Source: https://kubejs.com/wiki/tips/beans Demonstrates how to use beans to get a list of online players, shortening the syntax from `event.getServer().getPlayers()` to `event.server.players`. ```javascript event.server.players ``` -------------------------------- ### Using Consumer Callback Source: https://kubejs.com/wiki/ref/Consumer Example of how to use a method that accepts a Consumer callback. The callback receives an argument, which is a string in this case. ```javascript object.example(obj => { console.log(obj) // obj is a string }) ``` -------------------------------- ### Sandpaper Polishing Recipe Examples Source: https://kubejs.com/wiki/addons/create Defines recipes using sandpaper to polish items, supporting chance-based outputs. ```javascript ServerEvents.recipes(event => { event.recipes.create.sandpaper_polishing('minecraft:diamond', 'minecraft:coal_block') event.recipes.create.sandpaper_polishing(CreateItem.of('minecraft:diamond', 0.5), 'minecraft:coal_block') }) ``` ```javascript ServerEvents.recipes(event => { event.recipes.create.sandpaper_polishing('minecraft:diamond', 'minecraft:coal_block') event.recipes.create.sandpaper_polishing(Item.of('minecraft:diamond').withChance(0.5), 'minecraft:coal_block') }) ``` -------------------------------- ### FTBQuestsEvents: Handle Quest Start Source: https://kubejs.com/wiki/addons/ftb-xmod-compat Executes custom code when a player starts a quest. The server will broadcast a message. ```javascript FTBQuestsEvents.started('quest_id', event => { event.server.tell('A player started a quest!') }) ``` -------------------------------- ### Registering a Basic GUI Source: https://kubejs.com/wiki/addons/screenjs This is for creating completely separate, basic GUIs that are not tied to specific blocks or entities. It has a minimal setup. ```javascript StartupEvents.registry('menu', event => { event.create('name_here' /*name can be anything*/) /*default parameter set*/ }) ``` -------------------------------- ### Pressurizing Recipe Examples Source: https://kubejs.com/wiki/addons/vintage-kubejs Defines pressurizing recipes using the Compressor and Basin, supporting heated states and secondary fluid inputs/outputs. ```javascript ServerEvents.recipes(event => { event.recipes.vintageimprovements.pressurizing(Fluid.of('vintageimprovements:sulfur_dioxide', 1000), '#forge:gems/sulfur').heated().secondaryFluidOutput(0) event.recipes.vintageimprovements.pressurizing(Fluid.of('vintageimprovements:sulfuric_acid', 1000), [Fluid.of('vintageimprovements:sulfur_trioxide', 1000), Fluid.of('minecraft:water', 1000)]).secondaryFluidInput(1) }) ``` -------------------------------- ### Registering a Menu for Entities Source: https://kubejs.com/wiki/addons/screenjs Use this to create a custom GUI that opens when interacting with a specific entity. It's a simpler setup compared to block entities. ```javascript StartupEvents.registry('menu', event => { event.create('snow_golem' /*name can be anything*/, 'entity') /*default parameter set*/ .setEntity('minecraft:snow_golem') // the enity type that should open this GUI on right-click }) ``` -------------------------------- ### Item Snippet Example Source: https://kubejs.com/wiki/addons/probejs Example of how ProbeJS generates code snippets for items, enabling autocompletion for item IDs. ```javascript event.recipes.kubejs.shaped("minecraft:iron_ingot", ["aaa", "a a", "aaa"], {"a": "minecraft:iron_ingot"}); ``` -------------------------------- ### Create a Simple Ponder Scene Source: https://kubejs.com/wiki/addons/ponder-for-kubejs Demonstrates how to create a basic scene with a structure, idle time, entity creation, text display, and control animations. Use this as a starting point for creating your own Ponder scenes. ```javascript // for 1.18 pls use: onEvent("ponder.registry", event => { ... }) Ponder.registry((event) => { event.create("minecraft:paper").scene("our_first_scene", "First example scene", (scene, util) => { /** * Shows the whole structure. * Alternatively, `scene.showBasePlate()` can be used to show the base plate. * Useful for animating different parts of the structure. */ scene.showStructure(); /** * Encapsulate the structure bounds to given positions. This is useful if the custom structure has no proper bounds. * scene.showStructure() automatically encapsulates the bounds. */ // scene.encapsulateBounds(blockPos) /** * idle(ticks) or idleSeconds(seconds) is used to wait for a certain amount of time. * 20 ticks = 1 second */ scene.idle(10); /** * `.createEntity()` returns an entity link from Create which will be used * as reference in the future * [x, y, z] is the position but any KubeJS way to represent a position can be used. * * Don't modify the entity directly! */ const creeperLink = scene.world.createEntity("creeper", [2.5, 1, 2.5]); /** * 50 -> the tick length of the instruction * [x, y, z] -> the position that the text should point at */ scene .text(60, "Example text", [2, 2.5, 2.5]) /** * Optional | Sets the color of the text. * Possible values: * - PonderPalette.WHITE, PonderPalette.BLACK * - PonderPalette.RED, PonderPalette.GREEN, PonderPalette.BLUE * - PonderPalette.SLOW, PonderPalette.MEDIUM, PonderPalette.FAST * - PonderPalette.INPUT, PonderPalette.OUTPUT */ .colored(PonderPalette.RED) /** * Optional | Places the text closer to the target position. */ .placeNearTarget() /** * Optional | Adds a keyframe to the scene. */ .attachKeyFrame(); /** * 120 -> the tick length of the instruction * [x, y, z] -> the position that the controls should point at * "down" -> the direction that is used by the controls for pointing */ scene .showControls(60, [2.5, 3, 2.5], "down") /** * Uses mouse right click as icon. * Alternatively, `.leftClick()` can be used * or `.showing(icon)` for a custom icon. */ .rightClick() // Defines the item that should be shown with the icon. .withItem("shears") /** * Optional | Defines that controls are only shown when sneaking. * `.whileSneaking()` and `.withCTRL()` can not be used simultaneously. */ .whileSneaking() /** * Optional | Defines that controls are only shown when holding CTRL. * `.whileSneaking()` and `.withCTRL()` can not be used simultaneously. */ .whileCTRL(); }); }); ``` -------------------------------- ### Basic JavaScript Code Example Source: https://kubejs.com/wiki/test A simple JavaScript snippet for testing code block rendering. ```javascript const code = 'JavaScript code test' console.log('Hello, World!') ``` -------------------------------- ### Rich Item Display Example Source: https://kubejs.com/wiki/addons/probejs Illustrates ProbeJS's capability for rich item display, providing detailed information on hover (requires VSCode extension v4.8.0+). ```javascript event.item.addTooltip("minecraft:diamond", "A precious gem."); ``` -------------------------------- ### Add Multiple Machines to a Recipe Source: https://kubejs.com/wiki/addons/kubejs-tfmg To specify multiple machines for a recipe, simply add them as additional arguments to the `.machines()` method. This example requires three electrodes. ```javascript .machines("tfmg:electrode", "tfmg:electrode", "tfmg:electrode") ``` -------------------------------- ### Make Goats Milkable with Bucket Source: https://kubejs.com/wiki/tutorials/item-interactions Handle entity interaction events to customize player interactions with entities. This example makes goats milkable using a bucket, consuming the bucket and giving milk. ```javascript ItemEvents.entityInteracted('minecraft:bucket', event => { if(event.target.type != 'minecraft:goat') return event.item.count-- event.player.giveInHand('minecraft:milk_bucket') event.target.playSound('minecraft:entity.cow.milk') }) ``` ```javascript onEvent('item.entity_interact', event => { if (event.target.type != 'minecraft:goat' || event.item.id != 'minecraft:bucket') return event.item.count-- event.player.giveInHand('minecraft:milk_bucket') event.target.playSound('minecraft:entity.cow.milk') }) ``` -------------------------------- ### Adding Farmers Delight Cutting Recipes Source: https://kubejs.com/wiki/addons/farmers-delight Add custom cutting recipes in `server_scripts/`. This example shows how to cut cobblestone using a pickaxe, yielding stone and a chance for flint. ```javascript ServerEvents.recipes(event => { event.recipes.farmersdelight.cutting( 'minecraft:cobblestone', '#minecraft:pickaxes', // tool [ // results "minecraft:stone", ChanceResult.of("minecraft:flint", 0.75) ], // '' // sound ) event.recipes.farmersdelight.cooking( "meals", // recipe book tab - valid values: meals, drinks, misc ["minecraft:cobblestone"], "minecraft:stone", // output 30, // exp 10, // cookTime "minecraft:bowl" // container ) }) ``` -------------------------------- ### JavaScript Code Formatting Example Source: https://kubejs.com/wiki/contributing Demonstrates correct formatting for JavaScript code, including semicolon usage and array iteration. Note the specific case where a semicolon is required to prevent misinterpretation of subsequent code. ```javascript console.log('Hello, world!') // Here, a semicolon is needed in order for code to be not parsed as: // console.log('Hello, world!')['minecraft:stone', 'minecraft:cobblestone'].forEach(item => {}) ;['minecraft:stone', 'minecraft:cobblestone'].forEach(item => {}) ``` -------------------------------- ### Create a Ponder Scene with Custom Structure Source: https://kubejs.com/wiki/addons/ponder-for-kubejs This example demonstrates how to create a ponder scene that uses a custom NBT schematic as its structure. It requires specifying the structure ID in addition to the scene details. ```javascript // for 1.18 use: onEvent("ponder.registry", event => { ... }) Ponder.registry((event) => { /** * Scene with custom structure */ event .create("minecraft:paper") .scene( "our_first_scene", "Example scene for paper with structure", "kubejs:your_structure_id", (scene, util) => { // your scene code here } ); }); ``` -------------------------------- ### Registering a Menu for Any Block Source: https://kubejs.com/wiki/addons/screenjs This snippet shows how to create a custom GUI that opens when interacting with a specific block. It requires setting up item handlers and input slots. ```javascript StartupEvents.registry('menu', event => { event.create('grass_block' /*name can be anything*/, 'block') /*default parameter set*/ .addItemHandler(9) // adds an item handler. .addItemHandler(1) .inputSlotIndices(0) .setBlock('minecraft:grass_block') // the block that should open this GUI on right-click }) ``` -------------------------------- ### Create Rectangle using Command Alternative Source: https://kubejs.com/wiki/tutorials/painter-api Demonstrates the command-line alternative for creating a rectangle using the Painter API. ```bash /kubejs painter @p {example: {type: 'rectangle', x: 10, y: 10, w: 20, h: 20}} ``` -------------------------------- ### Register custom items in startup script Source: https://kubejs.com/wiki/tutorials/item-registry Use the StartupEvents.registry('item', ...) event to define new items. This event must be placed in a startup script. ```javascript // Listen to item registry event StartupEvents.registry('item', event => { // The texture for this item has to be placed in kubejs/assets/kubejs/textures/item/test_item.png // If you want a custom item model, you can create one in Blockbench and put it in kubejs/assets/kubejs/models/item/test_item.json event.create('test_item') // If you want to specify a different texture location you can do that too, like this: event.create('test_item_1').texture('mobbo:item/lava') // This texture would be located at kubejs/assets/mobbo/textures/item/lava.png // You can chain builder methods as much as you like event.create('test_item_2').maxStackSize(16).glow(true) // You can specify item type as 2nd argument in create(), some types have different available methods event.create('custom_sword', 'sword').tier('diamond').attackDamageBaseline(10) }) ``` -------------------------------- ### Fluid Snippet Example Source: https://kubejs.com/wiki/addons/probejs Example of ProbeJS generating code snippets for fluids, facilitating autocompletion for fluid IDs. ```javascript event.recipes.kubejs.fluid_transposer("kubejs:fluid_transposer", "minecraft:water", "minecraft:lava", 1000); ``` -------------------------------- ### Build, Validate, and Add Recipes Source: https://kubejs.com/wiki/addons/applied-kjs Build recipe JSON first, validate it, and then add it to the game. ```APIDOC ### #Build JSON first, validate, then add You can also build recipe JSON first and inspect it before adding it: ``` ServerEvents.recipes(event => { const json = AE2Recipes.inscriberPress( 'minecraft:gold_ingot', 'ae2:logic_processor_press', 'ae2:printed_logic_processor' ) AE2Recipes.validateOrThrow(json) console.log('AE2 recipe JSON:', AE2Recipes.stringify(json)) AE2Recipes.add(event, json, 'kubejs:ae2/inscriber/printed_logic_processor') }) ``` ``` -------------------------------- ### Update an Existing Rectangle with Painter API Source: https://kubejs.com/wiki/tutorials/painter-api Update an existing object by providing its ID and new properties. This example updates the 'example' rectangle's x-position. ```javascript event.player.paint({example: {x: 50}}) ``` -------------------------------- ### Registering Custom Fluids in Startup Scripts Source: https://kubejs.com/wiki/tutorials/fluid-registry-legacy Use the StartupEvents.registry('fluid', ...) method to define new fluids. This event is not cancellable and must be placed in a startup script. ```javascript StartupEvents.registry('fluid', event => { // Basic "thick" (looks like lava) fluid with red tint event.create('thick_fluid') .thickTexture(0xFF0000) .bucketColor(0xFF0000) .displayName('Thick Fluid') // Basic "thin" (looks like water) fluid with cyan tint, has no bucket and is not placeable event.create('thin_fluid') .thinTexture(0xFF0000) .bucketColor(0x00FFFF) .displayName('Thin Fluid') .noBucket() .noBlock() // Fluid with custom textures event.create('strawberry_cream') .displayName('Strawberry Cream') .stillTexture('kubejs:block/strawberry_still') .flowingTexture('kubejs:block/strawberry_flow') .bucketColor(0xFF33FF) // Fluid with a modified bucket item const tacoSauce = event .create('taco_sauce') .thickTexture(0xff0000) .bucketColor(0xff0000) tacoSauce.bucketItem.group('food') }) ``` ```javascript onEvent('fluid.registry', event => { // Basic "thick" (looks like lava) fluid with red tint event.create('thick_fluid') .thickTexture(0xFF0000) .bucketColor(0xFF0000) .displayName('Thick Fluid') // Basic "thin" (looks like water) fluid with cyan tint, has no bucket and is not placeable event.create('thin_fluid') .thinTexture(0xFF0000) .bucketColor(0x00FFFF) .displayName('Thin Fluid') .noBucket() // 1.18.2 only .noBlock() // 1.18.2 only // Fluid with custom textures event.create('strawberry_cream') .displayName('Strawberry Cream') .stillTexture('kubejs:block/strawberry_still') .flowingTexture('kubejs:block/strawberry_flow') .bucketColor(0xFF33FF) // Fluid with a modified bucket item const tacoSauce = event .create('taco_sauce') .thickTexture(0xff0000) .bucketColor(0xff0000) tacoSauce.bucketItem.group('food') }) ``` -------------------------------- ### PonderJS Fading Example Scene Source: https://kubejs.com/wiki/addons/ponder-for-kubejs An example demonstrating animated section fading using the `fadeInSection` helper function. It sets up specific blocks and then fades them in sequentially with delays. ```javascript // for 1.18 use: onEvent("ponder.registry", event => { ... }) Ponder.registry((event) => { event.create("minecraft:hopper").scene("section_fading", "Let's fade", (scene, util) => { /** * Blocks used for fading so they aren't shown directly. * If a custom structure is used, the blocks can be directly added to the structure file. */ scene.world.setBlocks([4, 1, 2], "minecraft:dispenser"); scene.world.setBlocks([3, 1, 2], "minecraft:chest"); scene.world.setBlocks([2, 1, 2], "minecraft:dropper"); scene.world.setBlocks([2, 2, 2], "minecraft:hopper"); // Only shows the base plate and the hopper that was just manually placed. scene.showBasePlate(); scene.world.showSection([2, 2, 2], Facing.DOWN); scene.idle(20); fadeInSection(scene, [4, 1, 2], [-2, 0, 0], Direction.EAST, 15); fadeInSection(scene, [3, 1, 2], [-1, 0, 0], Direction.EAST, 15); fadeInSection(scene, [2, 1, 2], [0, 0, 0], Direction.EAST, 15); }); }); ``` -------------------------------- ### Get Associated Block Source: https://kubejs.com/wiki/concepts/item-stack Retrieves the associated Block object if the ItemStack is a BlockItem, otherwise returns null. ```javascript item.block ``` -------------------------------- ### Register a basic block Source: https://kubejs.com/wiki/tutorials/block-registry The simplest way to register a new block using the StartupEvents registry. ```javascript StartupEvents.registry('block', event => { event.create('example_block') // Create a new block with ID 'kubejs:example_block' }) ``` -------------------------------- ### Get First Matching Item Source: https://kubejs.com/wiki/concepts/ingredient The .first property resolves the ingredient and returns the first item stack that matches it. ```javascript ingredient.first ``` -------------------------------- ### Apply Attributes to Entities (EntityJS) Source: https://kubejs.com/wiki/addons/irons-spells If EntityJS is installed, use `EntityJSEvents.attributes` for a more streamlined way to apply attributes to entities. ```javascript EntityJSEvents.attributes(event => { event.allTypes.forEach(type => { event.modify(type, (a) => { a.add('kubejs:test_spell_power') a.add('kubejs:test_spell_resistance') }) }) }) ``` -------------------------------- ### Mekanism Sawing Recipe Source: https://kubejs.com/wiki/addons/mekanism Create a Mekanism sawing recipe by specifying the output, input, and any extra output. ```javascript event.recipes.mekanism.sawing(output, input, extraOutput) ``` -------------------------------- ### Mekanism Crystallizing Recipe Source: https://kubejs.com/wiki/addons/mekanism Create a Mekanism crystallizing recipe, specifying the output and the input gas. ```javascript event.recipes.mekanism.crystallizing(output, inputGas) ``` -------------------------------- ### Create a New Creative Tab Source: https://kubejs.com/wiki/tutorials/creative-tabs Create a new creative tab with a specified icon and content using StartupEvents.registry. The content can be a list of item IDs. ```javascript StartupEvents.registry('creative_mode_tab', event => { event.create('dirt').icon(() => 'minecraft:dirt').content(() => [ 'minecraft:dirt', 'minecraft:grass_block', 'minecraft:podzol', 'minecraft:coarse_dirt', 'minecraft:rooted_dirt' ]) }) ``` -------------------------------- ### Dump Game Data with ProbeJS Source: https://kubejs.com/wiki/addons/probejs Run this command in-game to generate KubeJS typings. This is the first step to enabling Intellisense in VSCode. ```bash /probejs dump ``` -------------------------------- ### Add Tinkers' Construct Alloying Recipe Source: https://kubejs.com/wiki/tutorials/recipes Use event.custom() to add a Tinkers' Construct alloying recipe. This example creates Molten Electrum. ```javascript // Adding the Molten Electrum alloying recipe from Tinkers' Construct event.custom({ type: 'tconstruct:alloy', inputs: [ { tag: 'forge:molten_gold', amount: 90 }, { tag: 'forge:molten_silver', amount: 90 } ], result: { fluid: 'tconstruct:molten_electrum', amount: 180 }, temperature: 760 }) ``` -------------------------------- ### FTBQuestsEvents: Add Item to Custom Filter Source: https://kubejs.com/wiki/addons/ftb-xmod-compat Adds specified ItemStacks to a custom filter used in FTB Quests. Use 'acacia_boat' as an example. ```javascript FTBQuestsEvents.customFilterItem(event => { event.addStack('acacia_boat') }) ``` -------------------------------- ### Disable Dropping Cobblestone Source: https://kubejs.com/wiki/tutorials/item-interactions The dropped event allows you to cancel the dropping of specific items. This example disables dropping cobblestone and is applicable to 1.19.2+ and 1.18.2 and below. ```javascript ItemEvents.dropped('minecraft:cobblestone', e => e.cancel()) ``` -------------------------------- ### KubeJS Recipe Registration with Indentation Variants Source: https://kubejs.com/wiki/test Demonstrates defining recipes using a helper function to reduce repetition, shown with both space and tab indentation. ```javascript // this code uses space indents ServerEvents.recipes(event => { const potting = (output, pottedInput) => { event.shaped(output, [ 'BIB', ' B ' ], { B: 'minecraft:brick', I: pottedInput }) } //Now we can make many 'potting' recipes without typing that huge block over and over! potting('kubejs:potted_snowball', 'minecraft:snowball') potting('kubejs:potted_lava', 'minecraft:lava_bucket') potting('minecraft:blast_furnace', 'minecraft:furnace') }) ``` ```javascript // and this uses tab indents ServerEvents.recipes(event => { const potting = (output, pottedInput) => { event.shaped(output, [ 'BIB', ' B ' ], { B: 'minecraft:brick', I: pottedInput }) } //Now we can make many 'potting' recipes without typing that huge block over and over! potting('kubejs:potted_snowball', 'minecraft:snowball') potting('kubejs:potted_lava', 'minecraft:lava_bucket') potting('minecraft:blast_furnace', 'minecraft:furnace') }) ``` -------------------------------- ### Register World Transmutations with ProjectE Source: https://kubejs.com/wiki/addons/projecte Define world transmutation recipes using `ProjectEEvents.registerWorldTransmutations` in startup scripts. This allows specific blocks to transform into others when transmuted. ```javascript ProjectEEvents.registerWorldTransmutations(event => { event.transform('minecraft:tnt', 'minecraft:oak_planks') }) ``` -------------------------------- ### Add Farmer's Delight Cutting Recipe Source: https://kubejs.com/wiki/tutorials/recipes Use event.custom() to add a recipe for Farmer's Delight cutting board. This example slices a cake. ```javascript // Slice cake on a cutting board! event.custom({ type: 'farmersdelight:cutting', ingredients: [ { item: 'minecraft:cake' } ], tool: { tag: 'forge:tools/knives' }, result: [ { item: 'farmersdelight:cake_slice', count: 7 } ] }) ``` -------------------------------- ### Registering a recipe event listener Source: https://kubejs.com/wiki/tutorials/recipes Use these patterns to listen for the recipe event. The callback function executes when the server processes recipes. ```javascript /* * ServerEvents.recipes(callback) is a function that accepts another function, * called the "callback", as a parameter. The callback gets run when the * server is working on recipes, and then we can make our own changes. * When the callback runs, it is also known as the event "firing". */ // Listen for the "recipes" server event. ServerEvents.recipes(event => { // You can replace `event` with any name you like, as // long as you change it inside the callback too! // This part, inside the curly braces, is the callback. // You can modify as many recipes as you like in here, // without needing to use ServerEvents.recipes() again. console.log('Hello! The recipe event has fired!') }) ``` ```javascript /* * onEvent('recipes', callback) is a function that accepts another function, * called the "callback", as a parameter. The callback gets run when the * server is working on recipes, and then we can make our own changes. * When the callback runs, it is also known as the event "firing". */ // Listen for the "recipes" server event. onEvent('recipes', event => { // You can replace `event` with any name you like, as // long as you change it inside the callback too! // This part, inside the curly braces, is the callback. // You can modify as many recipes as you like in here, // without needing to use ServerEvents.recipes() again. console.log('Hello! The recipe event has fired!') }) ``` -------------------------------- ### Deploying Recipes with Multiple Outputs Source: https://kubejs.com/wiki/addons/create Defines deploying recipes that can yield multiple different items. Supports chance-based outputs and keeping the held item. ```javascript ServerEvents.recipes(event => { event.recipes.create.deploying('minecraft:diamond', ['minecraft:coal_block', 'minecraft:sand']) event.recipes.create.deploying(['minecraft:diamond', 'minecraft:emerald'], ['minecraft:coal_block', 'minecraft:sand']).keepHeldItem() event.recipes.create.deploying(['minecraft:diamond', CreateItem.of('minecraft:diamond', 0.5)], ['minecraft:coal_block', 'minecraft:sand']) }) ``` ```javascript ServerEvents.recipes(event => { event.recipes.create.deploying('minecraft:diamond', ['minecraft:coal_block', 'minecraft:sand']) event.recipes.create.deploying(['minecraft:diamond', 'minecraft:emerald'], ['minecraft:coal_block', 'minecraft:sand']).keepHeldItem() event.recipes.create.deploying(['minecraft:diamond', Item.of('minecraft:diamond').withChance(0.5)], ['minecraft:coal_block', 'minecraft:sand']) }) ``` -------------------------------- ### Modify Method Parameter Type in Document Source: https://kubejs.com/wiki/addons/probejs/dynamic-document-modification Transform the documentation of a specific method to suggest a custom 'Special.' type for its parameters. This example modifies the 'stage' method in RecipeJS. ```javascript ProbeJSEvents.generateDoc(event => { // So we will load the class and tell ProbeJS that we will transform the document of it event.transformDocument(Java.loadClass('dev.latvian.mods.kubejs.recipe.RecipeJS'), document => { // Find the first method with name "stage", it is also possible to find others by having more conditions document.methods.find(method => method.name == "stage") // Adds a property to modify the parameter, this will be explained in detail later .addPropertyJson({ // The type of the property type: "property:modify", // The name of the property, property name will not change if this is omitted name: "sussy_baka", // The ordinal of the parameter to be modified index: 0, // The new type of property to be modified, type will not change if this is omitted newType: { type: "type:primitive", name: "Special.Advancement" } }) }) }) ``` -------------------------------- ### Compacting Recipes Source: https://kubejs.com/wiki/addons/create Demonstrates how to create compacting recipes using the Mechanical Press. Supports multiple inputs/outputs, heated/superheated variants, and chance-based outputs. ```javascript ServerEvents.recipes(event => { event.recipes.create.compacting('minecraft:diamond', 'minecraft:coal_block') event.recipes.create.compacting('minecraft:diamond', 'minecraft:coal_block').heated() event.recipes.create.compacting('minecraft:diamond', 'minecraft:coal_block').superheated() event.recipes.create.compacting([Fluid.of('minecraft:water', 10), 'minecraft:dead_bush'], [Ingredient.of('#minecraft:saplings'), Ingredient.of('#minecraft:saplings')]) event.recipes.create.compacting(['minecraft:diamond', CreateItem.of('minecraft:diamond', 0.3)], 'minecraft:coal_block') }) ``` ```javascript ServerEvents.recipes(event => { event.recipes.create.compacting('minecraft:diamond', 'minecraft:coal_block') event.recipes.create.compacting('minecraft:diamond', 'minecraft:coal_block').heated() event.recipes.create.compacting('minecraft:diamond', 'minecraft:coal_block').superheated() event.recipes.create.compacting([Fluid.of('minecraft:water', 10), 'minecraft:dead_bush'], ['#minecraft:saplings', '#minecraft:saplings']) event.recipes.create.compacting(['minecraft:diamond', Item.of('minecraft:diamond').withChance(0.3)], 'minecraft:coal_block') }) ``` -------------------------------- ### Get All Matching Items Source: https://kubejs.com/wiki/concepts/ingredient The .items property resolves the ingredient and returns a list of all item stacks that match it. Variants like .stacks, .stackArray, and .displayStacks also exist. ```javascript ingredient.items ``` -------------------------------- ### Loop Through Dye Colors for Shapeless Recipes (KubeJS) Source: https://kubejs.com/wiki/tutorials/recipes Demonstrates looping through a predefined array of dye colors to generate shapeless recipes. This avoids manually creating a recipe for each color, making the code more concise. ```javascript ServerEvents.recipes(event => { // There's a useful built-in array that contains all the dye colors. // It can be looped over using `forEach`, so you don't need to specify a separate recipe for each color! Color.DYE.forEach(color => { event.shapeless(`kubejs:$==={color}===_clay`, ['minecraft:clay', `minecraft:$==={color}===_dye`]) }) // You can also create your own arrays... const metals = ['iron', 'copper', 'gold', 'netherite'] // ... and loop over them the same way! metals.forEach(metal => { event.shapeless(`kubejs:$==={metal}===_plate`, [`minecraft:$==={metal}===_ingot`, 'kubejs:hammer']) .damageIngredient('kubejs:hammer') }) }) ``` -------------------------------- ### Combine multiple header types Source: https://kubejs.com/wiki/tips/headers Demonstrates stacking multiple headers to define complex load conditions. ```javascript //priority: 10 //packmode: hard //requires: create //requires: tconstruct console.log('I am complicated!') ``` -------------------------------- ### Bulk Create/Update Painter API Objects Source: https://kubejs.com/wiki/tutorials/painter-api Create or update multiple painter objects simultaneously by including them in a single `paint` call. This example updates 'a', 'b', and creates 'c'. ```javascript event.player.paint({a: {x: 10}, b: {x: 30}, c: {type: 'rectangle', x: 10}}) ``` -------------------------------- ### Altar Recipe Syntax Source: https://kubejs.com/wiki/addons/blood-magic Provides the syntax for adding Altar recipes. Supports specifying upgrade level, altar syphon, consumption rate, and drain rate. ```javascript event.recipes.bloodmagic.altar(output, input) ``` ```javascript event.recipes.bloodmagic.altar(output, input).upgradeLevel(int).altarSyphon(int).consumptionRate(int).drainRate(int) ``` -------------------------------- ### FTBQuestsEvents: Add Custom Task Logic Source: https://kubejs.com/wiki/addons/ftb-xmod-compat Implements custom logic for 'Custom Tasks' in FTB Quests. This example progresses a task every 20 ticks if the player is in a thunderstorm. ```javascript FTBQuestsEvents.customTask('custom_task_id', event => { event.maxProgress = 100 // Sets the Progress Count. event.setCheckTimer(20) // Checks for progress every 1 second (20 ticks). event.setCheck((task, player) => { if(player.level.thundering) { //Checks if it is Thundering at a player. task.progress++ // Adds progress to the quest. } }) }) ``` -------------------------------- ### Get elements in a specific period Source: https://kubejs.com/wiki/addons/alchemistry-chemlib/helpers Use PeriodicTableHelper.getPeriodElements to retrieve all elements belonging to a specific period (row) on the periodic table. This can be used to display or process elements by their periodic grouping. ```javascript ItemEvents.rightClicked(event => { const { player, item, hand, level } = event if (level.isClientSide()) return const elements = PeriodicTableHelper.getPeriodElements(6) elements.forEach(item => player.sendSystemMessage(item.toString())) }) ``` -------------------------------- ### Liquifier Recipe Source: https://kubejs.com/wiki/addons/alchemistry-chemlib/recipes Use the liquifier recipe to convert items into fluids. Specify input item and output fluid. ```javascript ServerEvents.recipes(event => { event.recipes.alchemistry.liquifier("minecraft:netherrack", "minecraft:lava") event.recipes.alchemistry.liquifier(Item.of("chemlib:calcium", 16), Fluid.of("minecraft:milk", 250)) }) ``` -------------------------------- ### Add Game Stage on Crafting Diamond Boots Source: https://kubejs.com/wiki/tutorials/item-interactions The crafted event fires when an item is crafted. Use it to add game stages or perform other actions. This example applies to 1.19.2+ and 1.18.2 and below. ```javascript ItemEvents.crafted('minecraft:diamond_boots', e => e.addGameStage('myCoolStage')) ``` -------------------------------- ### JavaScript Conditional Formatting Example Source: https://kubejs.com/wiki/contributing Illustrates the correct way to format conditional statements in JavaScript. Code blocks are generally required unless the conditional branch results in an early return. ```javascript if (player.hand == "OFF_HAND") return; // Here, `return` doesn't need to be wrapped in a block. if (player.hand == "MAIN_HAND") { console.log("Right-clicked with main hand") } ``` -------------------------------- ### Share Item Data with Global Object Source: https://kubejs.com/wiki/tips/global This snippet demonstrates how to use the global object to store item data in startup scripts. This data can then be accessed by server scripts. ```javascript // Startup scripts global.items = [ ['hi_wiki', '4x diamond'] ] StartupEvents.registry('item', event => { // Register the items global.items.forEach(items => event.register(items[0])) }) ``` ```javascript // Server scripts ServerEvents.recipes(event => { // Add the recipes global.items.forEach(items => event.shapeless(items[0], items[1])) }) ```