### Timer-Based Events for NPC Behavior Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt Allows scheduling of recurring or one-time events for NPCs using timers. This example shows how to start timers during NPC initialization and handle timer events for patrol movements and timed announcements before despawning. ```javascript /** * @param {NpcEvent.InitEvent} event */ function init(event) { var timers = event.npc.getTimers(); // Start repeating timer (ID: 1, 100 ticks = 5 seconds, repeat: true) timers.start(1, 100, true); // Start one-time timer (ID: 2, 600 ticks = 30 seconds, repeat: false) timers.start(2, 600, false); // Store timer state event.npc.getTempdata().put("patrolIndex", 0); } /** * @param {NpcEvent.TimerEvent} event */ function timer(event) { if (event.id === 1) { // Repeating patrol behavior var data = event.npc.getTempdata(); var index = data.get("patrolIndex"); var waypoints = [ {x: 100, y: 64, z: 200}, {x: 120, y: 64, z: 200}, {x: 120, y: 64, z: 220}, {x: 100, y: 64, z: 220} ]; var point = waypoints[index]; event.npc.getAi().setReturnPosition(point.x, point.y, point.z); // Cycle to next waypoint data.put("patrolIndex", (index + 1) % waypoints.length); } else if (event.id === 2) { // One-time announcement event.npc.say("§eShift change! I'm going off duty."); // Remove NPC after announcement event.npc.despawn(); } } ``` -------------------------------- ### NPC Entity Creation and Management Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt Create and configure NPCs with custom appearance, stats, equipment, and behavior. ```APIDOC ## POST /api/npc/create ### Description Creates and configures a new NPC in the world with specified properties. ### Method POST ### Endpoint /api/npc/create ### Parameters #### Request Body - **world** (string) - Required - The world where NPC will be spawned - **x** (number) - Required - X coordinate - **y** (number) - Required - Y coordinate - **z** (number) - Required - Z coordinate - **name** (string) - Optional - NPC display name - **skin** (string) - Optional - Player skin to use - **health** (number) - Optional - Max health value - **strength** (number) - Optional - Melee attack strength - **faction** (number) - Optional - Faction ID - **behavior** (number) - Optional - Movement behavior type ### Request Example { "world": "overworld", "x": 100, "y": 64, "z": 200, "name": "Guard", "skin": "Steve", "health": 40, "strength": 5, "faction": 1, "behavior": 1 } ### Response #### Success Response (200) Returns the created NPC object with all configured properties. #### Response Example { "id": "npc_123", "name": "Guard", "position": {"x": 100, "y": 64, "z": 200}, "stats": {"health": 40, "strength": 5}, "equipment": {"mainhand": "minecraft:diamond_sword"} } ``` -------------------------------- ### Quest System Integration Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt Manages player quest progress, including checking quest status, completing objectives, and awarding factions or items. It handles different quest states like not started, active, and finished, and can offer quests or provide feedback to the player. ```javascript /** * @param {NpcEvent.InteractEvent} event */ function interact(event) { var player = event.player; var questId = 1; // Check quest state and provide appropriate response if (player.hasFinishedQuest(questId)) { event.npc.sayTo(player, "Thank you for completing my quest!"); // Give faction reward player.addFactionPoints(1, 50); } else if (player.hasActiveQuest(questId)) { // Check if objectives are complete var quest = player.getActiveQuest(questId); if (quest.getProgress() >= 1.0) { player.finishQuest(questId); event.npc.sayTo(player, "Excellent work! Here's your reward."); // Give rewards var reward = event.npc.world.createItem("minecraft:diamond", 0, 5); player.giveItem(reward); player.playSound("minecraft:entity.player.levelup", 1.0, 1.0); } else { event.npc.sayTo(player, "You still have work to do."); } } else if (player.canQuestBeAccepted(questId)) { // Offer quest event.npc.sayTo(player, "I have a task for you."); player.showDialog(10, event.npc.getName()); // Quest offer dialog } else { event.npc.sayTo(player, "I have nothing for you right now."); } } ``` -------------------------------- ### Custom GUI Creation and Interaction Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt Enables the creation of custom graphical user interfaces (GUIs) with labels, buttons, and item slots. This function demonstrates how to display a shop menu, process button clicks for purchases, and update the player's balance and inventory. ```javascript /** * @param {NpcEvent.InteractEvent} event */ function interact(event) { // Create custom GUI (ID: 1, 250x140 pixels, doesn't pause game) var gui = event.API.createCustomGui(1, 250, 140, false); // Add title label var title = gui.addLabel(1, "§6§lShop Menu", 10, 10, 230, 20); title.setScale(2.0); // Add purchase buttons gui.addButton(10, "Buy Sword (10g)", 10, 40); gui.addButton(11, "Buy Armor (25g)", 10, 70); gui.addButton(12, "Buy Potion (5g)", 10, 100); // Add balance display var balance = event.player.getStoreddata().get("gold") || 0; gui.addLabel(2, "Balance: " + balance + "g", 150, 40, 90, 20); // Show GUI to player event.player.showCustomGui(gui); } /** * @param {CustomGuiEvent.ButtonEvent} event */ function customGuiButton(event) { var player = event.player; var buttonId = event.buttonId; var data = player.getStoreddata(); var gold = data.get("gold") || 0; var purchases = { 10: {name: "Diamond Sword", cost: 10, item: "minecraft:diamond_sword"}, 11: {name: "Iron Chestplate", cost: 25, item: "minecraft:iron_chestplate"}, 12: {name: "Healing Potion", cost: 5, item: "minecraft:potion"} }; var purchase = purchases[buttonId]; if (purchase) { if (gold >= purchase.cost) { // Process purchase data.put("gold", gold - purchase.cost); var item = player.world.createItem(purchase.item, 0, 1); player.giveItem(item); player.message("§aPurchased " + purchase.name); player.playSound("minecraft:entity.experience_orb.pickup", 1.0, 1.0); // Update GUI event.gui.getComponent(2).setText("Balance: " + (gold - purchase.cost) + "g"); event.gui.update(player); } else { player.message("§cNot enough gold!"); player.playSound("minecraft:entity.villager.no", 1.0, 1.0); } } } ``` -------------------------------- ### Data Persistence - Stored Storage Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt API for persistent data storage that survives script reloads and world restarts. ```APIDOC ## POST /api/data/stored ### Description Stores persistent data that survives script reloads and world restarts (strings/numbers only). ### Method POST ### Endpoint /api/data/stored ### Parameters #### Path Parameters - **scope** (string) - Required - Storage scope ("npc" or "world") - **id** (string) - Required - NPC ID or world name #### Request Body - **key** (string) - Required - Data identifier - **value** (string|number) - Required - Data to store ### Request Example { "scope": "npc", "id": "npc_123", "key": "killCount", "value": 0 } ### Response #### Success Response (200) Confirms data was stored persistently. #### Response Example { "status": "success", "scope": "npc", "id": "npc_123", "key": "killCount", "persistent": true } ``` -------------------------------- ### Create and Configure NPC Entity with JavaScript Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt Demonstrates how to programmatically create and configure a custom NPC entity in the Minecraft world. It covers setting the NPC's name, skin, stats, equipment, faction, and AI behavior using JavaScript. ```javascript /** * @param {NpcEvent.InitEvent} event */ function init(event) { // Create NPC at specific location var npc = event.API.spawnNPC(event.npc.world, 100, 64, 200); // Configure appearance var display = npc.getDisplay(); display.setName("Guard"); display.setSkinPlayer("Steve"); // Configure stats var stats = npc.getStats(); stats.setMaxHealth(40); stats.setMeleeStrength(5); // Give equipment var sword = event.npc.world.createItem("minecraft:diamond_sword", 0, 1); npc.setMainhandItem(sword); // Set faction and behavior npc.setFaction(1); npc.getAi().setMovingType(1); // Standing } ``` -------------------------------- ### Data Persistence - Temporary Storage Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt API for storing temporary runtime data that persists until script reload or world restart. ```APIDOC ## POST /api/data/temp ### Description Stores temporary data at NPC or world level that persists until script reload. ### Method POST ### Endpoint /api/data/temp ### Parameters #### Path Parameters - **scope** (string) - Required - Storage scope ("npc" or "world") - **id** (string) - Required - NPC ID or world name #### Request Body - **key** (string) - Required - Data identifier - **value** (any) - Required - Data to store (supports complex objects) ### Request Example { "scope": "npc", "id": "npc_123", "key": "playerVisits", "value": [] } ### Response #### Success Response (200) Confirms data was stored successfully. #### Response Example { "status": "success", "scope": "npc", "id": "npc_123", "key": "playerVisits" } ``` -------------------------------- ### NPC Dynamic Equipment Management (JavaScript) Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt Saves and restores an NPC's mainhand item based on combat state using NBT serialization. It hides the weapon when not in combat and restores it when combat begins. Requires NPC and item NBT manipulation. ```javascript /** * @param {NpcEvent.InitEvent} event */ function init(e) { var data = e.npc.getStoreddata(); var item = e.npc.getMainhandItem(); // Save weapon as NBT JSON for later restoration if (!item.isEmpty()) { var nbtJson = item.getItemNbt().toJsonString(); data.put('weapon', nbtJson); } // Hide weapon if not in combat if (!e.npc.getAttackTarget()) { var air = e.npc.world.createItem('minecraft:air', 0, 1); e.npc.setMainhandItem(air); } } /** * @param {NpcEvent.TargetEvent} event */ function target(e) { // Restore weapon when entering combat var data = e.npc.getStoreddata(); if (data.has('weapon')) { var nbtString = data.get('weapon'); var nbt = e.API.stringToNbt(nbtString); var item = e.npc.world.createItemFromNbt(nbt); e.npc.setMainhandItem(item); } } /** * @param {NpcEvent.TargetLostEvent} event */ function targetLost(e) { // Hide weapon when leaving combat var air = e.npc.world.createItem('minecraft:air', 0, 1); e.npc.setMainhandItem(air); } ``` -------------------------------- ### Implement Faction System with Dynamic Pricing in JavaScript Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt This script demonstrates how to create an in-game economy system where prices and item availability are dynamically adjusted based on a player's faction standing with the NPC. It takes an NpcEvent.InteractEvent and uses player faction status to determine dialogue, pricing multipliers, and access to special items. Dependencies include the CNPC mod and its API for player interaction and GUI management. ```javascript /** * @param {NpcEvent.InteractEvent} event */ function interact(event) { var player = event.player; var npcFactionId = 1; var standing = player.factionStatus(npcFactionId); // Determine access and pricing based on faction standing if (standing < -100) { // Hostile event.npc.sayTo(player, "§cLeave now, enemy!"); event.npc.setAttackTarget(player); return; } else if (standing < 0) { // Unfriendly - high prices event.npc.sayTo(player, "I don't trust you. Prices are doubled."); showShop(event, 2.0); } else if (standing < 100) { // Neutral - normal prices event.npc.sayTo(player, "Welcome, traveler."); showShop(event, 1.0); } else if (standing < 500) { // Friendly - discount event.npc.sayTo(player, "Good to see you, friend! 25% discount."); showShop(event, 0.75); } else { // Allied - best prices and special items event.npc.sayTo(player, "§6Welcome, honored ally! Special items available."); showShop(event, 0.5); showSpecialItems(event); } } function showShop(event, priceMultiplier) { var gui = event.API.createCustomGui(2, 200, 150, false); var basePrice = 10; var adjustedPrice = Math.floor(basePrice * priceMultiplier); gui.addLabel(1, "§6Shop", 10, 10, 180, 20); gui.addButton(10, "Sword (" + adjustedPrice + " gold)", 10, 40); gui.addLabel(2, "Faction discount: " + Math.floor((1 - priceMultiplier) * 100) + "%", 10, 120, 180, 20); event.player.showCustomGui(gui); } function showSpecialItems(event) { // Grant access to rare items for high faction standing var specialItem = event.npc.world.createItem("minecraft:enchanted_golden_apple", 0, 1); event.npc.sayTo(event.player, "I have something special for you."); } ``` -------------------------------- ### Transporter Role with Payment (JavaScript) Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt Enables an NPC with a transporter role to charge players before teleporting them. It stores the destination, checks for the required payment item ('minecraft:emerald'), and teleports the player upon successful payment. Requires dialog event handling and item manipulation. ```javascript /** * @param {NpcEvent.InitEvent} event */ function init(event) { // Store location name for later use in transport var locationName = event.npc.role.location.getName(); event.npc.world.getStoreddata().put("destination_" + event.npc.getUUID(), locationName); } /** * @param {DialogEvent.CloseEvent} event */ function dialogClose(event) { var dialogId = event.dialog.getId(); // Check if player selected transport dialog if (dialogId === 5) { // Replace with your dialog ID var paymentItem = "minecraft:emerald"; var paymentAmount = 10; // Attempt to charge player if (event.player.removeItem(paymentItem, 0, paymentAmount)) { // Payment successful, transport player var mcEntity = event.player.getMCEntity(); var destName = event.npc.world.getStoreddata().get("destination_" + event.npc.getUUID()); event.npc.role.transport(mcEntity, destName); event.npc.sayTo(event.player, "Safe travels!"); event.player.playSound("minecraft:entity.enderman.teleport", 1.0, 1.0); } else { // Payment failed event.npc.sayTo(event.player, "You need " + paymentAmount + " emeralds for transport."); event.player.playSound("minecraft:entity.villager.no", 1.0, 1.0); } } } ``` -------------------------------- ### Lockable Door System (JavaScript) Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt Implements a lockable door system for custom blocks. Doors can be locked or unlocked using a specific item ('Golden Key'). The script manages the door's appearance and interaction based on its locked state. Requires block event handling and item checking. ```javascript var key_name = "Golden Key"; var door_name = "Treasury Door"; var locked = true; /** * @param {BlockEvent.InitEvent} event */ function init(event) { // Set initial appearance based on lock state event.block.setBlockModel("minecraft:iron_door"); } /** * @param {BlockEvent.InteractEvent} event */ function interact(event) { var player = event.player; var heldItem = player.getMainhandItem(); // Check if player is holding the key if (heldItem.getDisplayName() === key_name) { // Toggle lock state locked = !locked; // Change door appearance var model = locked ? "minecraft:iron_door" : "minecraft:wooden_door"; event.block.setBlockModel(model); // Provide feedback var status = locked ? "locked" : "unlocked"; player.message("<" + door_name + "> This door is now " + status); player.playSound("minecraft:block.enchantment_table.use", 1.0, 1.0); // Prevent normal door interaction event.setCanceled(true); } else if (locked) { // Deny access when locked event.setCanceled(true); player.message("<" + door_name + "> This door is locked"); player.playSound("minecraft:block.anvil.land", 1.0, 1.5); } // If unlocked and no key held, allow normal door operation } ``` -------------------------------- ### Handle NPC Killed Entity Event (JavaScript) Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt Triggers when the NPC kills an entity, granting health restoration, a temporary strength buff, and incrementing a persistent kill counter. Announces a milestone message every ten kills using storeddata for persistence. ```javascript /**\n * @param {NpcEvent.KilledEntityEvent} event\n */\nfunction killed(event) {\n var victim = event.entity;\n\n // Heal on kill\n var currentHealth = event.npc.getHealth();\n event.npc.setHealth(Math.min(currentHealth + 5, eventpc.getMaxHealth()));\n\n // Gain temporary buff\n event.npc.addPotionEffect(5, 200, 0, false); // Strength for 10 seconds\n\n // Track kills for rewards\n var data = event.npc.getStoreddata();\n var kills = data.get(\"totalKills\") || 0;\n data.put(\"totalKills\", kills + 1);\n\n // Announce milestone\n if ((kills + 1) % 10 === 0) {\n event.npc.say(\"§6\" + (kills + 1) + \" victories achieved!\");\n }\n}\n ``` -------------------------------- ### Manipulate World and Spawn Entities with JavaScript Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt This script allows for the modification of blocks, spawning of entities, and creation of visual effects within the game world. It utilizes the CNPC API to interact with the game environment, taking an NpcEvent.InteractEvent as input and performing actions like particle spawning, entity creation, block replacement, and querying nearby entities. Dependencies include the CNPC mod and its associated JavaScript API. ```javascript /** * @param {NpcEvent.InteractEvent} event */ function interact(event) { var world = event.npc.world; var pos = event.npc.getPos(); // Create explosion effect world.spawnParticle("minecraft:explosion", pos.getX(), pos.getY() + 1, pos.getZ(), 0, 0, 0, 0.1, 10); world.playSoundAt(pos, "minecraft:entity.generic.explode", 1.0, 1.0); // Spawn entity at location var zombie = world.createEntity("minecraft:zombie"); zombie.setPosition(pos.getX() + 5, pos.getY(), pos.getZ()); world.spawnEntity(zombie); // Modify blocks in area for (var x = -2; x <= 2; x++) { for (var z = -2; z <= 2; z++) { var blockX = pos.getX() + x; var blockY = pos.getY() - 1; var blockZ = pos.getZ() + z; var block = world.getBlock(blockX, blockY, blockZ); if (block.getName() === "minecraft:grass_block") { world.setBlock(blockX, blockY, blockZ, "minecraft:stone", 0); } } } // Query nearby entities var nearbyPlayers = world.getNearbyEntities(pos, 10, 1); // Type 1 = players for (var i = 0; i < nearbyPlayers.length; i++) { var player = nearbyPlayers[i]; player.message("§cThe ground shakes!"); } } ``` -------------------------------- ### Handle NPC Melee Attack Event (JavaScript) Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt Modifies melee attack damage based on the NPC's current, enabling aerk mode when health is low, and applies slowness and poison debuffs to the target. Demonstrates conditional damage scaling and effect application via NpcEvent.MeleeAttackEvent. ```javascript /**\n * @param {NpcEvent.MeleeAttackEvent} event\n */\nfunction meleeAttack(event) {\n // Increase damage based on NPC health\n var healthPercent = event.npc.getHealth() / event.npc.getMaxHealth();\n if (healthPercent < 0.3) {\n event.damage = event.damage * 2; // Berserk mode\n event.npc.say(\"§4Desperate fury!\");\n }\n\n // Apply deb to target\n event.target.addPotionEffect(2, 60, 0, false); // Slowness for 3 seconds\n event.target.addPotionEffect(19, 60, 0, false); // Poison for 3 seconds\n}\n ``` -------------------------------- ### NPC Temporary Data Persistence with JavaScript Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt Illustrates how to use temporary data storage for NPCs, which persists until script reload or world restart. This method supports complex JavaScript objects for storing runtime data like player visits and configuration settings. It also shows how to access world-wide temporary data. ```javascript /** * @param {NpcEvent.InitEvent} event */ function init(event) { // Store complex data in NPC tempdata event.npc.getTempdata().put("playerVisits", []); event.npc.getTempdata().put("config", { greetingCooldown: 60, lastGreeting: 0, messageQueue: [] }); // Store world-wide data accessible by all NPCs event.npc.world.getTempdata().put("globalCounter", 0); } /** * @param {NpcEvent.InteractEvent} event */ function interact(event) { // Retrieve and modify array data var visits = event.npc.getTempdata().get("playerVisits"); if (!visits.includes(event.player.getName())) { visits.push(event.player.getName()); event.npc.say("Welcome, " + event.player.getName() + "!"); } else { event.npc.say("Welcome back!"); } // Update global counter var counter = event.npc.world.getTempdata().get("globalCounter"); event.npc.world.getTempdata().put("globalCounter", counter + 1); } ``` -------------------------------- ### NPC Stored Data Persistence with JavaScript Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt Explains how to use stored data for NPCs, which is persistent across script reloads and world restarts. This storage is limited to Strings and Numbers and is suitable for saving critical game data like kill counts and player names. It also covers world-level stored data. ```javascript /** * @param {NpcEvent.InitEvent} event */ function init(event) { // Initialize persistent storage with defaults var data = event.npc.getStoreddata(); if (!data.has("killCount")) { data.put("killCount", 0); } if (!data.has("playerName")) { data.put("playerName", "Unknown"); } // World-level persistent data var worldData = event.npc.world.getStoreddata(); if (!worldData.has("serverUptime")) { worldData.put("serverUptime", 0); } } /** * @param {NpcEvent.KilledEntityEvent} event */ function killed(event) { // Increment kill counter var data = event.npc.getStoreddata(); var kills = data.get("killCount"); data.put("killCount", kills + 1); event.npc.say("Kill count: " + (kills + 1)); } /** * @param {NpcEvent.InteractEvent} event */ function interact(event) { // Display stored data var kills = event.npc.getStoreddata().get("killCount"); event.player.message("This NPC has " + kills + " kills"); } ``` -------------------------------- ### Handle NPC Damage Event (JavaScript) Source: https://context7.com/noppes/cnpcs-scripting-examples/llms.txt Adjusts incoming damage, reduces projectile damage, performs a retaliation attack on melee hits, and triggers an emergency regeneration when health is low. Uses NpcEvent.DamagedEvent properties to modify damage and interact with the NPC and attacker. Suitable for adding defensive and reactive combat logic. ```javascript /**\n * @param {NpcEvent.DamagedEvent} event\n */\nfunction damaged(event) {\n var damageSource = event.damageSource;\n var attacker = damageSource.getTrueSource();\n\n // Reduce damage from ranged attacks\n (damageSource.isProjectile()) {\n event.damage = event.damage * 0.5;\n event.npc.say(\"Arrows barely scratch me!\");\n }\n\n // Counter-attack on melee damage\n if (attacker && !damageSource.isProjectile()) {\n attacker.damage(2.0); // Deal 2 hearts back\n event.npc.world.spawnParticle(\"minecraft:angry_villager\",\n attacker.getX(), attacker.getY() + 2, attacker.getZ(),\n 0, 0, 0.1, 5);\n }\n\n // Emergency heal at health\n (event.npc.getHealth() - event.damage < 10) {\n event.npc.addPotionEffect(10, 100, 1, false); // Regeneration\n event.npc.say(\"§cI won't fall so easily!\");\n }\n}\n ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.