### Full Plugin Event Listener Setup Source: https://htdevlib.netlify.app/docs/EventHelper An example demonstrating how to set up multiple event listeners within a plugin's setup method. This includes player join, chat, item drop, item pickup, crafting, and player disconnect events, showcasing a comprehensive event handling structure. ```java @Override protected void setup() { getLogger().at(Level.INFO).log("Setting up plugin..."); // Register all event listeners EventHelper.onPlayerJoinWorldWithUUID(this, (world, uuid, username) -> { getLogger().at(Level.INFO).log("[Join] " + username + " (" + uuid + ") joined " + world.getName()); loadPlayerData(uuid); }); EventHelper.onPlayerChat(this, (username, message) -> { getLogger().at(Level.INFO).log("[Chat] " + username + ": " + message); }); EventHelper.onItemDrop(this, (itemId, quantity, playerEntity) -> { String playerName = EntityHelper.getName(playerEntity); getLogger().at(Level.INFO).log("[Drop] " + playerName + " dropped " + quantity + "x " + itemId); }); EventHelper.onItemPickup(this, (itemId, quantity, playerEntity) -> { String playerName = EntityHelper.getName(playerEntity); getLogger().at(Level.INFO).log("[Pickup] " + playerName + " picked up " + quantity + "x " + itemId); }); EventHelper.onCraftRecipe(this, (outputItemId, quantity, playerEntity) -> { String playerName = EntityHelper.getName(playerEntity); getLogger().at(Level.INFO).log("[Craft] " + playerName + " crafted " + quantity + "x " + outputItemId); }); EventHelper.onPlayerDisconnect(this, (uuid, username) -> { getLogger().at(Level.INFO).log("[Disconnect] " + username + " (" + uuid + ") left"); savePlayerData(uuid); }); } ``` -------------------------------- ### Complete ECS Event Setup Example in Java Source: https://htdevlib.netlify.app/docs/EcsEventHelper This comprehensive Java example demonstrates how to set up various ECS event listeners when a player joins a world. It registers listeners for block breaks, block placements, block damage, and zone discoveries, logging relevant information for each event. It emphasizes registering events within onPlayerJoinWorld. ```java @Override protected void setup() { // Register ECS events when world is available EventHelper.onPlayerJoinWorld(this, world -> { getLogger().at(Level.INFO).log("World available, registering ECS events..."); EcsEventHelper.onBlockBreak(world, (position, blockTypeId) -> { getLogger().at(Level.INFO).log("[Break] " + blockTypeId + " at " + position); }); EcsEventHelper.onBlockPlace(world, (position, itemId) -> { getLogger().at(Level.INFO).log("[Place] " + itemId + " at " + position); }); EcsEventHelper.onBlockDamage(world, (position, blockTypeId, currentDamage, damage, itemInHand) -> { String tool = itemInHand != null ? itemInHand : "Hand"; getLogger().at(Level.INFO).log("[Damage] " + blockTypeId + " - " + String.format("%.1f%%", currentDamage * 100) + " with " + tool); }); EcsEventHelper.onZoneDiscovery(world, (discoveryInfo) -> { getLogger().at(Level.INFO).log("[Discovery] " + discoveryInfo.zoneName()); }); }); } ``` -------------------------------- ### ItemDrop Class Examples (Java) Source: https://htdevlib.netlify.app/docs/LootHelper Demonstrates the creation and usage of the ItemDrop class for defining items to be dropped. Includes examples for default velocity, random velocity, custom velocity, and dropping multiple items. ```Java // Default velocity (slight upward motion) new LootHelper.ItemDrop("Rock_Gem_Diamond", 1) // Random velocity for natural spread LootHelper.ItemDrop.withRandomVelocity("Rock_Gem_Diamond", 1) // Custom velocity new LootHelper.ItemDrop("Rock_Gem_Diamond", 3, new Vector3d(0.1, 0.3, -0.1)) // Multiple items with random velocity return Arrays.asList( LootHelper.ItemDrop.withRandomVelocity("Rock_Gem_Ruby", 1), LootHelper.ItemDrop.withRandomVelocity("Rock_Gem_Topaz", 1) ); ``` -------------------------------- ### Handle Admin Chat Commands (Java) Source: https://htdevlib.netlify.app/docs/PlayerHelper This example shows how to process player chat messages to implement simple admin commands like changing game modes. It checks for messages starting with '!' and uses PlayerHelper for permissions and game mode manipulation. ```Java EventHelper.onPlayerChat(plugin, (username, message) -> { if (!message.startsWith("!")) return; Entity player = EntityHelper.getPlayerByName(world, username); if (player == null) return; String[] parts = message.split(" "); String command = parts[0].substring(1); // Remove ! switch (command) { case "creative": if (PlayerHelper.hasPermission(player, "admin.gamemode")) { PlayerHelper.setGameMode(player, GameMode.CREATIVE); PlayerHelper.sendMessage(player, "Game mode set to Creative!"); } else { PlayerHelper.sendMessage(player, "No permission!"); } break; case "survival": if (PlayerHelper.hasPermission(player, "admin.gamemode")) { PlayerHelper.setGameMode(player, GameMode.SURVIVAL); PlayerHelper.sendMessage(player, "Game mode set to Survival!"); } break; } }); ``` -------------------------------- ### Get Item Information with ItemHelper Utilities Source: https://htdevlib.netlify.app/docs/ItemHelper Demonstrates how to extract details from an ItemStack using `getItemId`, `getQuantity`, and `isEmptyStack`. These methods are essential for inspecting individual items within the game. ```java ItemStack item = ItemHelper.getItemFromSlot(chest, 0); if (item != null && !ItemHelper.isEmptyStack(item)) { String id = ItemHelper.getItemId(item); int quantity = ItemHelper.getQuantity(item); LOGGER.log("Item: " + id + " x" + quantity); } ``` -------------------------------- ### Log All Container Activity Source: https://htdevlib.netlify.app/docs/ContainerHelper This example shows how to log all item additions and removals from a specific container. It registers a listener for container changes and logs the quantity and item ID whenever an item is added or removed. ```java // Log all container activity Vector3i chestPos = new Vector3i(100, 64, 100); ContainerHelper.onContainerChange(world, chestPos, (transaction) -> { if (transaction.isAdded()) { WorldHelper.log(world, "[CHEST LOG] Item added: " + transaction.getQuantity() + "x " + transaction.getItemId()); } else if (transaction.isRemoved()) { WorldHelper.log(world, "[CHEST LOG] Item removed: " + transaction.getQuantity() + "x " + transaction.getItemId()); } }); ``` -------------------------------- ### Initialize and Track Zones on World Load (Java) Source: https://htdevlib.netlify.app/docs/ZoneHelper Initializes zone tracking upon world load and sets up an event listener for zone discovery. It also includes an example of manual zone tracking based on player position within a tick interval. ```java @Override public void onWorldLoad(AddPlayerToWorldEvent event) { World world = event.getWorld(); // Initialize zone tracking ZoneHelper.initializeZoneTracking(world); // Set up zone discovery event EcsEventHelper.onZoneDiscovery(world, (discoveryInfo) -> { String zoneName = discoveryInfo.zoneName(); WorldHelper.log(world, "Zone discovered: " + zoneName); }); } // Manual zone tracking with player movement WorldHelper.onTickInterval(world, 20, tick -> { List players = EntityHelper.getAllEntities(world); for (Entity player : players) { if (!(player instanceof Player)) continue; Vector3d pos = EntityHelper.getPosition(player); if (pos.x > 100 && pos.x < 200 && pos.z > 100 && pos.z < 200) { String oldZone = ZoneHelper.getCurrentZone(player); String newZone = "Forest_Clearing"; if (!newZone.equals(oldZone)) { ZoneHelper.setCurrentZone(player, newZone); // Check if it's a new discovery if (ZoneHelper.discoverZone(player, newZone)) { PlayerHelper.sendMessage(player, "🎉 Discovered: " + newZone); } } } } }); ``` -------------------------------- ### Player Home and Respawn Functions Source: https://htdevlib.netlify.app/docs/EntityHelper Provides functions to get a player's home/respawn position (bed or world spawn) and their respawn transform (position and rotation). It also includes a function to teleport the player to their respawn location. ```Java Vector3d homePos = EntityHelper.getPlayerHome(player); if (homePos != null) { WorldHelper.log(world, "Player's home is at: " + homePos); double distance = EntityHelper.getDistance(player, homePos); WorldHelper.log(world, "Distance from home: " + distance + " blocks"); } ``` ```Java Transform respawnTransform = EntityHelper.getPlayerRespawnPosition(player); if (respawnTransform != null) { Vector3d pos = respawnTransform.getPosition(); Vector3f rotation = respawnTransform.getRotation(); } ``` ```Java if (EntityHelper.teleportPlayerHome(player)) { WorldHelper.log(world, "Teleported player home!"); } ``` -------------------------------- ### Spawn NPC Entities in Java Source: https://htdevlib.netlify.app/docs/EntityHelper Provides examples of spawning NPC entities using the EntityHelper.spawnNPC() method. It covers spawning by role name and position (Vector3d or coordinates), and also includes an option for specifying rotation (yaw). The method returns the spawned Entity or null if spawning fails. ```Java // Spawn a cow at a position Vector3d spawnPos = new Vector3d(100, 64, 100); Entity cow = EntityHelper.spawnNPC(world, "Cow", spawnPos); if (cow != null) { WorldHelper.log(world, "Successfully spawned a Cow!"); } // Spawn using coordinates Entity deer = EntityHelper.spawnNPC(world, "Deer_Doe", 105, 64, 100); // Spawn with rotation (yaw in radians) Entity chicken = EntityHelper.spawnNPC(world, "Chicken", 110, 64, 100, (float) Math.PI); ``` ```Java Vector3d playerPos = EntityHelper.getPosition(player); // Spawn a cow in front Entity cow = EntityHelper.spawnNPC(world, "Cow", playerPos.getX() + 5, playerPos.getY(), playerPos.getZ()); // Spawn a deer to the right Entity deer = EntityHelper.spawnNPC(world, "Deer_Doe", playerPos.getX(), playerPos.getY(), playerPos.getZ() + 5); // Spawn a chicken behind with rotation Entity chicken = EntityHelper.spawnNPC(world, "Chicken", playerPos.getX() - 5, playerPos.getY(), playerPos.getZ(), (float) Math.PI); ``` -------------------------------- ### Apply Armor Stat Bonuses with EquipmentHelper Source: https://htdevlib.netlify.app/docs/StatsHelper Shows how to dynamically add or remove stat modifiers when a player equips or unequips armor. This example uses EquipmentHelper to hook into equipment changes and StatsHelper to manage additive health bonuses. ```java // When player equips armor EquipmentHelper.onEquipmentChange(world, player, (change, container) -> { if (change.isEquipping() && change.getNewItemId().contains("Armor")) { // Add +20 max health per armor piece StatsHelper.addAdditiveModifier(player, "Health", "armor_" + change.getNewItemId(), 20.0f); float newMaxHealth = StatsHelper.getStatMax(player, "Health"); PlayerHelper.sendMessage(player, "Max health increased to " + newMaxHealth); } if (change.isUnequipping() && change.getOldItemId().contains("Armor")) { // Remove armor bonus StatsHelper.removeModifier(player, "Health", "armor_" + change.getOldItemId()); float newMaxHealth = StatsHelper.getStatMax(player, "Health"); PlayerHelper.sendMessage(player, "Max health decreased to " + newMaxHealth); } }); ``` -------------------------------- ### Current Zone Queries Source: https://htdevlib.netlify.app/docs/ZoneHelper Provides methods to get and set the current zone a player is in, and to check if a player is within a specific zone. ```APIDOC ## getCurrentZone(player) ### Description Get the current zone a player is in. ### Method `getCurrentZone` ### Parameters #### Path Parameters * **player** (Entity) - Required - The player entity. ### Response #### Success Response (200) * **String** - The zone name, or null if not in a tracked zone. ### Response Example ```java String currentZone = ZoneHelper.getCurrentZone(player); if (currentZone != null) { PlayerHelper.sendMessage(player, "You are in: " + currentZone); } else { PlayerHelper.sendMessage(player, "You are not in a named zone"); } ``` ``` ```APIDOC ## setCurrentZone(player, zoneName) ### Description Set the current zone for a player. This is typically called automatically by zone tracking systems. ### Method `setCurrentZone` ### Parameters #### Path Parameters * **player** (Entity) - Required - The player entity. * **zoneName** (String) - Optional - The zone name (null to clear). ### Request Example ```java // Manually set player's current zone ZoneHelper.setCurrentZone(player, "Forest_Clearing"); // Clear current zone ZoneHelper.setCurrentZone(player, null); ``` ### Response This method does not return a value. ``` ```APIDOC ## isInZone(player, zoneName) ### Description Check if a player is in a specific zone. ### Method `isInZone` ### Parameters #### Path Parameters * **player** (Entity) - Required - The player entity. * **zoneName** (String) - Required - The zone name to check. ### Response #### Success Response (200) * **boolean** - true if the player is in the specified zone. ### Response Example ```java if (ZoneHelper.isInZone(player, "Dangerous_Cave")) { PlayerHelper.sendMessage(player, "⚠ Warning: This area is dangerous!"); } // Quest requirement if (ZoneHelper.isInZone(player, "Ancient_Temple")) { // Complete quest objective PlayerHelper.sendMessage(player, "Quest objective complete!"); } ``` ``` -------------------------------- ### Manage Player Health with StatsHelper Source: https://htdevlib.netlify.app/docs/StatsHelper Demonstrates how to get current and maximum health, apply damage, heal, and fully restore a player's health using the StatsHelper utility. This is fundamental for any game with a health system. ```java // Get current health float health = StatsHelper.getHealth(player); float maxHealth = StatsHelper.getStatMax(player, "Health"); getLogger().at(Level.INFO).log("Health: " + health + " / " + maxHealth); // Damage player StatsHelper.addStat(player, "Health", -10.0f); // Heal player StatsHelper.addStat(player, "Health", 20.0f); // Fully heal StatsHelper.maximizeStat(player, "Health"); ``` -------------------------------- ### Apply Timed Potion Effects with WorldHelper Source: https://htdevlib.netlify.app/docs/StatsHelper Illustrates how to apply temporary stat multipliers to a player using potion effects. This example uses StatsHelper for multiplicative modifiers and WorldHelper to schedule the removal of these effects after a specified duration. ```java public void applyStrengthPotion(Entity player, int durationTicks) { // Add 1.5x health multiplier StatsHelper.addMultiplicativeModifier(player, "Health", "strength_potion", 1.5f); // Add 1.3x stamina multiplier StatsHelper.addMultiplicativeModifier(player, "Stamina", "strength_potion", 1.3f); PlayerHelper.sendMessage(player, "Strength potion applied!"); // Remove after duration WorldHelper.waitTicks(world, durationTicks, () -> { StatsHelper.removeModifier(player, "Health", "strength_potion"); StatsHelper.removeModifier(player, "Stamina", "strength_potion"); PlayerHelper.sendMessage(player, "Strength potion wore off."); }); } ``` -------------------------------- ### Apply Class-Based Stat Bonuses with Switch Statement Source: https://htdevlib.netlify.app/docs/StatsHelper Demonstrates how to apply different stat bonuses based on a player's class using a switch statement. This example utilizes StatsHelper to add or multiply modifiers for Health, Stamina, and Mana, tailoring player stats to their chosen class. ```java public void applyClassBonuses(Entity player, String playerClass) { switch (playerClass) { case "Warrior": // Warriors get +50 max health and +20 max stamina StatsHelper.addAdditiveModifier(player, "Health", "class_bonus", 50.0f); StatsHelper.addAdditiveModifier(player, "Stamina", "class_bonus", 20.0f); break; case "Mage": // Mages get 2x max mana but -20 max health StatsHelper.addMultiplicativeModifier(player, "Mana", "class_bonus", 2.0f); StatsHelper.addAdditiveModifier(player, "Health", "class_bonus", -20.0f); break; case "Rogue": // Rogues get 1.5x max stamina StatsHelper.addMultiplicativeModifier(player, "Stamina", "class_bonus", 1.5f); break; } PlayerHelper.sendMessage(player, "Class bonuses applied: " + playerClass); } ``` -------------------------------- ### Register Block Interaction for Container Tracking (Java) Source: https://htdevlib.netlify.app/docs/ContainerHelper This code snippet demonstrates how to register a player join world event to then set up a block interaction listener. When a player interacts with a block, it checks if it's a container and registers it for further tracking. This is the recommended way to start container tracking. ```java @Override public void start() { EventHelper.onPlayerJoinWorld(this, world -> { // Register block interaction event to detect container usage EcsEventHelper.onBlockInteract(world, (position, blockTypeId) -> { // Check if this is a container block if (ContainerHelper.isContainerType(blockTypeId)) { // Register the container when player interacts with it ContainerHelper.onContainerChange(world, position, (transaction) -> { // ContainerTransaction automatically parses the event! WorldHelper.log(world, "Action: " + transaction.getAction()); if (transaction.getItemId() != null) { WorldHelper.log(world, "Item: " + transaction.getItemId()); WorldHelper.log(world, "Quantity: " + transaction.getQuantity()); } // Check action type with helper methods if (transaction.isAdded()) { WorldHelper.log(world, "Item added to container!"); } else if (transaction.isRemoved()) { WorldHelper.log(world, "Item removed from container!"); } }); WorldHelper.log(world, "Registered container at " + position); } }); WorldHelper.log(world, "Container tracking enabled!"); WorldHelper.log(world, "Containers will be registered when players interact with them"); }); } ``` -------------------------------- ### Toggle Main Menu on Player Chat Command Source: https://htdevlib.netlify.app/docs/UIHelper This example uses EventHelper to listen for player chat messages. If a player types '!menu', it toggles the 'main_menu' UI page, informing the player whether the menu was opened or closed. It handles null player checks. ```java EventHelper.onPlayerChat(plugin, (username, message) -> { if (!message.equals("!menu")) return; Entity player = EntityHelper.getPlayerByName(world, username); if (player == null) return; // Toggle menu if (UIHelper.isPageOpen(player, "main_menu")) { UIHelper.closePage(player, "main_menu"); PlayerHelper.sendMessage(player, "Menu closed."); } else { UIHelper.openPage(player, "main_menu"); PlayerHelper.sendMessage(player, "Menu opened."); } }); ``` -------------------------------- ### Apply Difficulty Scaling Modifiers with Switch Statement Source: https://htdevlib.netlify.app/docs/StatsHelper Shows how to adjust player health based on game difficulty using a switch statement. This example removes any existing difficulty modifiers before applying a new multiplicative health modifier using StatsHelper, supporting different difficulty levels like Easy, Normal, Hard, and Nightmare. ```java public void applyDifficultyModifiers(Entity player, String difficulty) { // Remove old difficulty modifiers StatsHelper.removeModifier(player, "Health", "difficulty"); switch (difficulty) { case "Easy": StatsHelper.addMultiplicativeModifier(player, "Health", "difficulty", 1.5f); break; case "Normal": // No modifier break; case "Hard": StatsHelper.addMultiplicativeModifier(player, "Health", "difficulty", 0.75f); break; case "Nightmare": StatsHelper.addMultiplicativeModifier(player, "Health", "difficulty", 0.5f); break; } } ``` -------------------------------- ### Enforce Build Height Limit in Java Source: https://htdevlib.netlify.app/docs/EcsEventHelper This example shows how to enforce a build height limit by preventing players from placing blocks above a certain Y-coordinate. It utilizes EcsEventHelper.onBlockPlace to monitor block placement events. If a block is placed above the limit, it's removed (replaced with air), and a message is sent to the player. ```java EcsEventHelper.onBlockPlace(world, (position, itemId) -> { if (position.getY() > 100) { // Remove the placed block BlockHelper.setBlock(world, position, 0); // 0 = air WorldHelper.broadcastMessage(world, Message.raw("Cannot build above Y=100!")); } }); ``` -------------------------------- ### Get Component from Entity Source: https://htdevlib.netlify.app/docs/ComponentHelper Retrieves a specific component from an entity using its accessor and component type. It returns the component if found, otherwise null. Example shows how to get an ItemComponent and extract its item ID. ```java ComponentType itemType = ItemComponent.getComponentType(); ItemComponent item = ComponentHelper.getComponent(accessor, entityRef, itemType); if (item != null) { String itemId = item.getItemStack().getItemId(); } ``` -------------------------------- ### Give Starter Kit (Java) Source: https://htdevlib.netlify.app/docs/InventoryHelper This function provides a player with a set of initial items, often referred to as a starter kit. It uses InventoryHelper to add various items like weapons, tools, and food to the player's inventory. ```java public void giveStarterKit(Entity player) { // Give starter items InventoryHelper.giveItem(player, "Weapon_Sword_Crude", 1); InventoryHelper.giveItem(player, "Tool_Pickaxe_Crude", 1); InventoryHelper.giveItem(player, "Tool_Axe_Crude", 1); InventoryHelper.giveItem(player, "Furniture_Crude_Torch", 10); InventoryHelper.giveItem(player, "Food_Apple", 5); PlayerHelper.sendMessage(player, "You received a starter kit!"); } ``` -------------------------------- ### Place Chest and Fill with Items (Java) Source: https://htdevlib.netlify.app/docs/BlockStateHelper Demonstrates how to place a chest block in the world, wait for its state to initialize, and then fill it with various items using ItemHelper. It includes error handling for blocks that do not support item containers and ensures the state is saved. ```java int x = 100, y = 64, z = 100; BlockHelper.setBlockByName(world, x, y, z, "Furniture_Desert_Chest_Small"); WorldHelper.waitTicks(world, 2, () -> { BlockState state = BlockStateHelper.ensureState(world, x, y, z); if (state instanceof ItemContainerState chestState) { ItemContainer container = chestState.getItemContainer(); ItemHelper.fillContainerRandom(container, "Furniture_Crude_Torch", 2, "Ingredient_Bone_Fragment", 10, "Item_Diamond", 5 ); BlockStateHelper.markNeedsSave(chestState); LOGGER.log("Chest created and filled with loot!"); } else { LOGGER.log("Block doesn't support item containers"); } }); ``` -------------------------------- ### BlockHelper - Getting Block Information Source: https://htdevlib.netlify.app/docs/BlockHelper Retrieve information about blocks, including their names and IDs, and check if a position is empty. ```APIDOC ## BlockHelper - Getting Block Information ### Description Provides methods to query information about blocks at specific locations or to get block IDs from names, and to check for air blocks. ### Methods #### `getBlockName(world, position)` Gets the human-readable name of the block at the specified position. - **world** (World) - The world to query. - **position** (Vector3d or x, y, z) - The coordinates of the block. - **Returns** (String) - The name of the block. #### `getBlockName(world, x, y, z)` An overloaded version of `getBlockName` that accepts individual coordinates. - **world** (World) - The world to query. - **x, y, z** (number) - The coordinates of the block. - **Returns** (String) - The name of the block. #### `getBlockId(blockName)` Gets the numeric ID of a block from its human-readable name. - **blockName** (String) - The name of the block (e.g., 'Rock_Stone'). - **Returns** (int) - The numeric ID of the block. #### `isAir(world, position)` Checks if the block at the specified position is an air block. - **world** (World) - The world to query. - **position** (Vector3d or x, y, z) - The coordinates to check. - **Returns** (boolean) - `true` if the position is air, `false` otherwise. ### Request Example ```java // Get block name at position String blockName = BlockHelper.getBlockName(world, 100, 64, 100); WorldHelper.log(world, "Block: " + blockName); // e.g., "Rock_Stone" // Get block ID from name int stoneId = BlockHelper.getBlockId("Rock_Stone"); // Check if a position is air Vector3d pos = new Vector3d(100, 64, 100); if (BlockHelper.isAir(world, pos)) { WorldHelper.log(world, "Position is empty!"); } ``` ``` -------------------------------- ### Send Welcome Message on Player Join (Java) Source: https://htdevlib.netlify.app/docs/PlayerHelper This snippet demonstrates how to send a personalized welcome message to a player when they join the world. It utilizes EventHelper to listen for player join events and PlayerHelper to send messages. ```Java EventHelper.onPlayerJoinWorldWithUUID(plugin, (world, uuid, username) -> { Entity player = EntityHelper.getPlayerByUUID(world, uuid); if (player != null) { // Send welcome message PlayerHelper.sendMessage(player, "Welcome to the server, " + username + "!"); // Broadcast join message WorldHelper.broadcastMessage(world, Message.raw(username + " has joined the game!")); } }); ``` -------------------------------- ### Create Item Stacks with ItemHelper Source: https://htdevlib.netlify.app/docs/ItemHelper Demonstrates how to create item stacks using the `createStack` method. This method takes an item ID and an optional quantity, returning an ItemStack object or null if creation fails. It's fundamental for initializing items in the game. ```java ItemStack torch = ItemHelper.createStack("Furniture_Crude_Torch", 5); ItemStack bones = ItemHelper.createStack("Ingredient_Bone_Fragment", 10); ItemStack sword = ItemHelper.createStack("Weapon_Sword_Iron"); // quantity 1 ``` -------------------------------- ### Get Block Type from State (Java) Source: https://htdevlib.netlify.app/docs/BlockStateHelper Retrieves the BlockType of a block associated with a given BlockState. Returns null if the block type cannot be determined. ```java BlockState state = BlockStateHelper.getState(world, x, y, z); BlockType type = BlockStateHelper.getBlockType(state); if (type != null) { LOGGER.log("Block type: " + type.getId()); } ``` -------------------------------- ### Manage Selected Hotbar Slot (JavaScript) Source: https://htdevlib.netlify.app/docs/InventoryHelper Enables getting and setting the currently active hotbar slot. Slots are indexed from 0 to 8. ```javascript // Get current selection int slot = InventoryHelper.getSelectedHotbarSlot(player); PlayerHelper.sendMessage(player, "Selected slot: " + slot); // Force select slot 0 InventoryHelper.setSelectedHotbarSlot(player, 0); ``` -------------------------------- ### Get Block State (Java) Source: https://htdevlib.netlify.app/docs/BlockStateHelper Retrieves the BlockState object for a block at the given world coordinates. Returns null if the block does not have any state data. ```java BlockState state = BlockStateHelper.getState(world, x, y, z); if (state != null) { LOGGER.log("Found state data for block"); } ``` -------------------------------- ### Fill Containers Sequentially and Randomly with ItemHelper Source: https://htdevlib.netlify.app/docs/ItemHelper Shows how to use `fillContainer` for sequential item placement and `fillContainerRandom` for random placement within a container. Both methods return the count of successfully added items and are useful for populating containers with multiple items. ```java // Sequential (Organized) int added = ItemHelper.fillContainer(chest, "Furniture_Crude_Torch", 1, "Ingredient_Bone_Fragment", 10, "Rock_Gem_Diamond", 5 ); // Items will be in slots 0, 1, 2 // Random (Natural Loot) // Items placed in random slots each time int added = ItemHelper.fillContainerRandom(chest, "Furniture_Crude_Torch", 2, "Ingredient_Bone_Fragment", 10, "Weapon_Sword_Iron", 1 ); ``` -------------------------------- ### Get Component Accessor Source: https://htdevlib.netlify.app/docs/ComponentHelper Retrieves the component accessor from the world's entity store. This accessor is essential for performing component operations on entities. ```java ComponentAccessor accessor = world.getEntityStore().getStore().getAccessor(); ``` -------------------------------- ### Create Platform with DevLib Source: https://htdevlib.netlify.app/docs/BlockHelper Creates a rectangular platform of a specified block type in the game world. It takes two corner points and a block name as input. Ensure the world and block name are valid. ```Java // Create a 10x10 stone platform at y=64 Vector3d corner1 = new Vector3d(0, 64, 0); Vector3d corner2 = new Vector3d(10, 64, 10); BlockHelper.fillRegionByName(world, corner1, corner2, "Rock_Stone"); ``` -------------------------------- ### Get All Discovered Zones for Player Source: https://htdevlib.netlify.app/docs/ZoneHelper Retrieves a list of all zone names that a player has discovered. This can be used to display discovered areas to the player or for other tracking purposes. ```Java List discovered = ZoneHelper.getDiscoveredZones(player); PlayerHelper.sendMessage(player, "You have discovered " + discovered.size() + " zones:"); for (String zone : discovered) { PlayerHelper.sendMessage(player, " - " + zone); } ``` -------------------------------- ### ZoneHelper Initialization Source: https://htdevlib.netlify.app/docs/ZoneHelper Initializes zone discovery tracking for a given world. This method should be called once when the world loads. ```APIDOC ## initializeZoneTracking(world) ### Description Initialize zone discovery tracking for a world. This should be called once when the world loads. ### Method `initializeZoneTracking` ### Parameters #### Path Parameters * **world** (World) - Required - The world to track zones in. ### Request Example ```java @Override public void onWorldLoad(AddPlayerToWorldEvent event) { World world = event.getWorld(); // Initialize zone tracking ZoneHelper.initializeZoneTracking(world); LOGGER.log("Zone tracking initialized"); } ``` ### Response This method does not return a value. ``` -------------------------------- ### Get Block Position from State (Java) Source: https://htdevlib.netlify.app/docs/BlockStateHelper Retrieves the world coordinates (Vector3i) of a block associated with a given BlockState. Returns null if the position cannot be determined. ```java BlockState state = BlockStateHelper.getState(world, x, y, z); Vector3i pos = BlockStateHelper.getBlockPosition(state); if (pos != null) { LOGGER.log("Block is at: " + pos.x + ", " + pos.y + ", " + pos.z); } ``` -------------------------------- ### Get Item ID and Quantity from Entity Source: https://htdevlib.netlify.app/docs/ComponentHelper Convenience methods specifically for entities that are items. They allow quick retrieval of the item's ID and quantity. ```java String itemId = ComponentHelper.getItemId(accessor, entityRef); int quantity = ComponentHelper.getItemQuantity(accessor, entityRef); if (itemId != null) { getLogger().at(Level.INFO).log("Found item: " + itemId + " x" + quantity); } ``` -------------------------------- ### Get Current Moon Phase Source: https://htdevlib.netlify.app/docs/WorldHelper Retrieve the current phase of the moon, represented by an integer from 0 to 7 by default. This can be used for events that depend on lunar cycles. ```java int moonPhase = WorldHelper.getMoonPhase(world); WorldHelper.log(world, "Moon phase: " + moonPhase); ``` -------------------------------- ### Entity Type Retrieval Source: https://htdevlib.netlify.app/docs/EntityHelper Get the readable name for an entity's type. This includes specific NPC names, uninitialized NPCs, or general class names for non-NPC entities. ```APIDOC ## GET /entity/type ### Description Retrieves the human-readable type name for a given entity. Handles specific NPC names, uninitialized NPCs, and general entity class names. ### Method GET ### Endpoint `/entity/type` ### Parameters #### Query Parameters - **entity** (Entity) - Required - The entity object to get the type for. ### Request Example ``` // Assuming 'entity' is a valid Entity object String type = EntityHelper.getEntityType(entity); WorldHelper.log(world, "Entity type: " + type); ``` ### Response #### Success Response (200) - **entityType** (String) - The readable name of the entity type (e.g., 'Minnow', 'Player', 'ItemEntity'). #### Response Example ```json { "entityType": "Skeleton_Fighter" } ``` ``` -------------------------------- ### Get Player UUID and Name with PlayerHelper Source: https://htdevlib.netlify.app/docs/PlayerHelper Retrieves a player's unique identifier (UUID) and their display name. Requires a Player entity. Useful for logging or identifying players. ```Java UUID playerUuid = PlayerHelper.getUUID(player); String playerName = PlayerHelper.getName(player); WorldHelper.log(world, "Player: " + playerName + " (" + playerUuid + ")"); ``` -------------------------------- ### Place Block and Add State (Java) Source: https://htdevlib.netlify.app/docs/BlockStateHelper A pattern for placing a block and then modifying its state. It involves placing the block, waiting for initialization, ensuring the state exists, modifying it (e.g., adding items to a container), and then saving the changes. ```java // 1. Place the block BlockHelper.setBlockByName(world, x, y, z, "Furniture_Desert_Chest_Small"); // 2. Wait for initialization WorldHelper.waitTicks(world, 2, () -> { // 3. Get/create state BlockState state = BlockStateHelper.ensureState(world, x, y, z); // 4. Modify state if (state instanceof ItemContainerState chestState) { ItemContainer container = chestState.getItemContainer(); ItemHelper.fillContainer(container, "Item_Diamond", 5); // 5. Save BlockStateHelper.markNeedsSave(chestState); } }); ``` -------------------------------- ### Get Players and Player Count (Java) Source: https://htdevlib.netlify.app/docs/WorldHelper Retrieves a list of all entities representing players in the world or just the total count of players. This is helpful for game logic that depends on player presence or number. ```Java List players = WorldHelper.getPlayers(world); int count = WorldHelper.getPlayerCount(world); ``` -------------------------------- ### Get Count of Tracked Containers (Java) Source: https://htdevlib.netlify.app/docs/ContainerHelper This function returns the total number of containers currently being tracked within a given world. It's useful for monitoring the state of container tracking. ```java int count = ContainerHelper.getTrackedContainerCount(world); WorldHelper.log(world, "Tracking " + count + " containers"); ``` -------------------------------- ### Player Home and Respawn Information Source: https://htdevlib.netlify.app/docs/EntityHelper Retrieve the player's home or respawn position, and their respawn transform. Also includes a method to teleport the player to their home. ```APIDOC ## Player Home and Respawn API ### GET /player/home #### Description Get the player's home or respawn position (bed spawn or world spawn). #### Method GET #### Endpoint `/player/home` #### Parameters ##### Query Parameters - **player** (Player) - Required - The player object. #### Request Example ``` Vector3d homePos = EntityHelper.getPlayerHome(player); if (homePos != null) { WorldHelper.log(world, "Player's home is at: " + homePos); } ``` #### Response ##### Success Response (200) - **position** (Vector3d) - The home/respawn position, or null if not available. ##### Response Example ```json { "position": { "x": 100.5, "y": 64.0, "z": -200.0 } } ``` ### GET /player/respawn/transform #### Description Get the full Transform (position + rotation) for the player's respawn location. #### Method GET #### Endpoint `/player/respawn/transform` #### Parameters ##### Query Parameters - **player** (Player) - Required - The player object. #### Request Example ``` Transform respawnTransform = EntityHelper.getPlayerRespawnPosition(player); if (respawnTransform != null) { Vector3d pos = respawnTransform.getPosition(); Vector3f rotation = respawnTransform.getRotation(); } ``` #### Response ##### Success Response (200) - **transform** (Transform) - The respawn transform, or null if not available. ##### Response Example ```json { "transform": { "position": {"x": 100.5, "y": 64.0, "z": -200.0}, "rotation": {"x": 0.0, "y": 0.0, "z": 0.0} } } ``` ### POST /player/teleport/home #### Description Teleports a player to their home or respawn location. #### Method POST #### Endpoint `/player/teleport/home` #### Parameters ##### Query Parameters - **player** (Player) - Required - The player object. #### Request Example ``` if (EntityHelper.teleportPlayerHome(player)) { WorldHelper.log(world, "Teleported player home!"); } ``` #### Response ##### Success Response (200) - **success** (boolean) - true if the teleport was successful, false otherwise. ##### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Broadcast Custom Death Messages Source: https://htdevlib.netlify.app/docs/DeathHelper Generates and broadcasts custom death messages to all players based on the cause of death (entity, projectile, environment, or other). This example utilizes DeathHelper, WorldHelper, and Message classes. ```java DeathHelper.onEntityDeath(world, (death) -> { String victim = death.getEntityName(); String message; if (death.wasKilledByEntity()) { String killer = death.getKillerName(); if (death.isKillerPlayer()) { message = victim + " was slain by " + killer; } else { message = victim + " was killed by a " + killer; } } else if (death.wasKilledByProjectile()) { String shooter = death.getKillerName(); message = victim + " was shot by " + shooter; } else if (death.wasKilledByEnvironment()) { String envType = death.getEnvironmentType(); message = victim + " died from " + envType; } else { message = victim + " died"; } // Broadcast to all players WorldHelper.broadcastMessage(world, Message.raw("[Death] " + message)); }); ``` -------------------------------- ### Track Player Equipment Changes on Join (Java) Source: https://htdevlib.netlify.app/docs/EquipmentHelper Tracks equipment changes for players when they join the world. It first listens for player join events, then finds the LivingEntity associated with the player's UUID, and finally sets up an EquipmentHelper listener for that entity. ```java EventHelper.onPlayerJoinWorldWithUUID(plugin, (world, uuid, username) -> { // Find the player entity by UUID for (Entity entity : world.getPlayers()) { if (EntityHelper.getUUID(entity).equals(uuid) && entity instanceof LivingEntity livingEntity) { EquipmentHelper.onEquipmentChange(world, livingEntity, (change, container) -> { LOGGER.at(Level.INFO).log(username + " changed equipment: " + change.getSlotType()); }); break; } } }); ``` -------------------------------- ### Get All Discovered Zones Globally Source: https://htdevlib.netlify.app/docs/ZoneHelper Fetches a set of all unique zone names discovered by any player in the game. This function returns a Set and is useful for global statistics or tracking overall exploration. ```java Set allZones = ZoneHelper.getAllDiscoveredZones(); WorldHelper.log(world, "Total zones discovered by all players: " + allZones.size()); for (String zone : allZones) { WorldHelper.log(world, " - " + zone); } ``` -------------------------------- ### Query Container Contents with ItemHelper Source: https://htdevlib.netlify.app/docs/ItemHelper Demonstrates how to retrieve item information from containers using `getItemsFromContainer` (all items), `getItemFromSlot` (specific slot), and `countItemInContainer` (count of a specific item). These methods are essential for inventory inspection and logic. ```java // Get all items List items = ItemHelper.getItemsFromContainer(chest); for (ItemStack item : items) { String id = ItemHelper.getItemId(item); int qty = ItemHelper.getQuantity(item); LOGGER.log("Found: " + id + " x" + qty); } // Get item from specific slot ItemStack item = ItemHelper.getItemFromSlot(chest, 0); // Count specific item int torchCount = ItemHelper.countItemInContainer(chest, "Furniture_Crude_Torch"); ``` -------------------------------- ### Get Current Player Zone Source: https://htdevlib.netlify.app/docs/ZoneHelper Retrieves the current zone a player is located in. If the player is not in a tracked zone, it returns null. This is useful for implementing zone-specific game logic or providing player feedback. ```Java String currentZone = ZoneHelper.getCurrentZone(player); if (currentZone != null) { PlayerHelper.sendMessage(player, "You are in: " + currentZone); } else { PlayerHelper.sendMessage(player, "You are not in a named zone"); } ``` -------------------------------- ### Initialize Zone Tracking Source: https://htdevlib.netlify.app/docs/ZoneHelper Initializes zone discovery tracking for a given world. This method should be called once when the world loads, typically within an AddPlayerToWorldEvent handler. It sets up the necessary data structures for zone management. ```Java @Override public void onWorldLoad(AddPlayerToWorldEvent event) { World world = event.getWorld(); // Initialize zone tracking ZoneHelper.initializeZoneTracking(world); LOGGER.log("Zone tracking initialized"); } ``` -------------------------------- ### Check Container and Item Status with ItemHelper Source: https://htdevlib.netlify.app/docs/ItemHelper Shows how to check the status of containers and items using `hasSpace`, `isEmpty`, and `isStackable`. These utility functions help in determining if an item can be added, if a container is empty, or if an item can be stacked. ```java // Check if container has space ItemStack newItem = ItemHelper.createStack("Rock_Gem_Diamond", 10); if (ItemHelper.hasSpace(chest, newItem)) { ItemHelper.addToContainer(chest, "Rock_Gem_Diamond", 10); } // Check if empty if (ItemHelper.isEmpty(chest)) { LOGGER.log("Chest is empty!"); } // Check if item is stackable if (ItemHelper.isStackable(itemStack)) { // Can stack with other items of same type } ``` -------------------------------- ### Check Day/Night Status and Sunlight Factor Source: https://htdevlib.netlify.app/docs/WorldHelper Determine if the current game time is daytime or nighttime, and get the current sunlight intensity. The sunlight factor ranges from 0.0 (night) to 1.0 (full daylight). ```java // Check if it's day or night if (WorldHelper.isDaytime(world)) { WorldHelper.log(world, "It's daytime!"); } if (WorldHelper.isNighttime(world)) { WorldHelper.log(world, "It's nighttime!"); } // Get sunlight factor (0.0 = night, 1.0 = full daylight) double sunlight = WorldHelper.getSunlightFactor(world); WorldHelper.log(world, "Sunlight: " + (sunlight * 100) + "%"); ``` -------------------------------- ### Handle Player Join World Event with EventHelper Source: https://htdevlib.netlify.app/docs/EventHelper Fires a callback when a player joins the world, providing the world reference. This is useful for initializing world-specific data or checking existing players. Note that the player may not be fully added to the world's player list immediately. ```Java EventHelper.onPlayerJoinWorld(this, world -> { getLogger().at(Level.INFO).log("Player joined world: " + world.getName()); // Example: Send welcome message, initialize player data }); ``` -------------------------------- ### Get Discovered Zone Count for Player Source: https://htdevlib.netlify.app/docs/ZoneHelper Retrieves the total number of unique zones a specific player has discovered. This function returns an integer representing the count. It can be used for tracking player progress or triggering achievements. ```java int count = ZoneHelper.getDiscoveredZoneCount(player); PlayerHelper.sendMessage(player, "Zones discovered: " + count + "/50"); // Achievement check if (count >= 25) { PlayerHelper.sendMessage(player, "🏆 Achievement: Explorer!"); } ``` -------------------------------- ### Manage Custom UI Pages with UIHelper Source: https://htdevlib.netlify.app/docs/UIHelper Functions to open, close, and check the status of custom UI pages for a player. Requires player and page ID as parameters. ```javascript // Open a custom menu UIHelper.openPage(player, "custom_shop_menu"); // Close the menu UIHelper.closePage(player, "custom_shop_menu"); if (UIHelper.isPageOpen(player, "custom_shop_menu")) { // Menu is already open PlayerHelper.sendMessage(player, "Close the menu first!"); return; } // Close all menus when player enters combat UIHelper.closeAllPages(player); ```