### Ore Finder Example Source: https://github.com/kasperstudios/kashub/blob/main/README.md Example script demonstrating how to find and move to the nearest diamond ore. ```APIDOC ## Ore Finder Script Example ### Description This script demonstrates how to use the `scanner` and `player` objects to find the nearest diamond ore and move the player to its location. ### Code ```javascript // Find and mine nearest diamond let ores = scanner.blocks("diamond_ore", 64) if (ores.length > 0) { let nearest = ores[0] System.print("Found diamond ore at " + nearest.x + ", " + nearest.y + ", " + nearest.z) player.moveTo(nearest.x, nearest.y, nearest.z) player.lookAt(nearest.x, nearest.y, nearest.z) System.print("Arrived at diamond ore!") } else { System.print("No diamonds nearby") } ``` ``` -------------------------------- ### Write Your First Kashub Script Source: https://github.com/kasperstudios/kashub/blob/main/README.md A basic script to get started with Kashub. It retrieves player health and name, prints a greeting, and checks for low health. ```javascript let health = player.getHealth() let name = player.getName() print "Hello, " + name + "!" print "Your health: " + health if (health < 10) { print "Low health! Be careful!" } ``` -------------------------------- ### Install Dependencies for Kashub VSCode Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/TESTING.md Run this command in the kashub-vscode directory to install necessary Node.js dependencies. ```bash cd kashub-vscode npm install ``` -------------------------------- ### w2p.record(name) Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/w2p-object.md Starts recording player actions into a macro with the specified name. If no name is provided, it defaults to 'default'. ```APIDOC ## w2p.record(name) ### Description Starts recording player actions into a macro with the specified name. ### Parameters #### Path Parameters - **name** (string, optional) - The name of the macro to record. Defaults to "default". ### Returns - `true` ### Request Example ```javascript // Start recording actions to "mining_run" w2p.record("mining_run") System.print("Recording started. Perform actions now.") ``` ``` -------------------------------- ### Combat Bot Example Source: https://github.com/kasperstudios/kashub/blob/main/README.md Example script for an auto-attack combat bot that targets the nearest hostile mob. ```APIDOC ## Combat Bot Script Example ### Description This script implements an auto-attack bot that continuously searches for and attacks the nearest hostile mob using the `vision` and `player` objects. ### Code ```javascript // Auto-attack nearest hostile mob crashguard(minFps=30) { while (true) { let enemy = vision.nearest("hostile", 4, "head") if (enemy != null) { player.lookAt(enemy.pos.x, enemy.pos.y, enemy.pos.z) player.attack(enemy) System.print("Attacking " + enemy.type + " (HP: " + enemy.health + ")") } System.wait(100) } } ``` ``` -------------------------------- ### Command Help Text Format in Java Source: https://github.com/kasperstudios/kashub/blob/main/DEVELOPMENT_NOTES.md Format command help text with usage, examples, and notes. Ensure descriptions are in English. ```java @Override public String getDetailedHelp() { return "Command description in English.\n\n" + "Usage:\n" + " command - Description\n\n" + "Examples:\n" + " command example\n\n" + "Notes:\n" + " - Important note"; } ``` -------------------------------- ### V1 to V2 Auto-Heal Script Migration Example Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/V2_API_MIGRATION.md Demonstrates the migration of an auto-heal script from V1 syntax to V2 syntax. ```APIDOC ## Auto-Heal Script Migration ### V1 - Old style ```javascript loop { if $PLAYER_HEALTH < 10 { print "Low health!" inventory use golden_apple wait 5000 } wait 1000 } ``` ### V2 - New style ```javascript while (true) { let health = player.getHealth() if (health < 10) { System.print("Low health!") inventory.use("golden_apple") System.wait(5000) } System.wait(1000) } ``` ``` -------------------------------- ### KashubClient WebSocket Example Source: https://context7.com/kasperstudios/kashub/llms.txt Demonstrates connecting to Kashub via WebSocket, streaming output and errors, running scripts, and debugging. Requires the KashubClient to be imported. ```typescript import { KashubClient } from './kashubClient'; const client = new KashubClient(); const connected = await client.connect(); console.log('Connected:', connected); // true // Stream all script output to stdout client.onOutput(event => { console.log(`[Task ${event.taskId}] ${event.level}: ${event.message}`); }); // Stream errors client.onError(event => { console.error(`[Task ${event.taskId}] ERROR on line ${event.line}: ${event.error}`); }); // Execute a script and track state changes const result = await client.runScript('System.print("WebSocket test!")', 'ws_test.kh'); console.log('Task ID:', result.taskId); // e.g. 5 client.onStateChange(ev => { console.log(`Task ${ev.taskId} (${ev.taskName}) → ${ev.state}`); }); // Debug: set breakpoints and step through client.setBreakpoints([3, 7, 12]); client.sendDebugAction('step_over', result.taskId); client.onDebugEvent(ev => { if (ev.event === 'PAUSED') { console.log(`Paused at line ${ev.line}`); client.requestVariables(ev.scriptId); } }); client.onVariablesResponse(ev => { console.log('Variables:', ev.variables); // { PLAYER_HEALTH: "20", myVar: "42", ... } }); // Stop the task when done await client.stopTask(result.taskId); client.disconnect(); ``` -------------------------------- ### Start Recording Player Actions with w2p.record() Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/w2p-object.md Use `w2p.record()` to begin capturing player actions. Specify a name for the macro; it defaults to 'default' if not provided. Perform actions immediately after calling this method. ```javascript w2p.record("mining_run") System.print("Recording started. Perform actions now.") ``` -------------------------------- ### Auto-completion Examples in JavaScript Source: https://github.com/kasperstudios/kashub/blob/main/docs/editor-guide.md Trigger auto-completion by typing a variable name followed by a dot. This shows available methods and properties for 'player' and 'System' objects. ```javascript player. // Shows: getHealth, moveTo, attack, etc. ``` ```javascript System. // Shows: print, log, wait, etc. ``` -------------------------------- ### Interact with World Data in JavaScript Source: https://context7.com/kasperstudios/kashub/llms.txt Use the World object to get block information, world time, weather, and register custom crafting recipes. Examples show checking blocks underfoot, reacting to night or thunder, and defining shaped/shapeless recipes. ```javascript // world.getBlock(x, y, z) – returns block ID string or null // world.getTime() – world time 0–24000 // world.getWeather() – "clear", "rain", or "thunder" // world.defineRecipe(type, id, ...args) – register custom crafting recipe // Check what block is underfoot let pos = player.getPos() let block = world.getBlock(Math.floor(pos.x), Math.floor(pos.y) - 1, Math.floor(pos.z)) System.print("Standing on: " + block) // Time-of-day and weather awareness let time = world.getTime() let isNight = (time > 13000 && time < 23000) let weather = world.getWeather() if (isNight || weather == "thunder") { System.print("Dangerous conditions – seeking shelter") player.chat("/home") } // Register a shaped recipe (client-side only) world.defineRecipe( "shaped", "custom_sword", " A ", " A ", " S ", "A:diamond", "S:stick", "result:diamond_sword" ) // Register a shapeless recipe world.defineRecipe( "shapeless", "custom_mix", "oak_planks", "stick", "result:wooden_sword" ) ``` -------------------------------- ### Record and Replay Player Actions in JavaScript Source: https://context7.com/kasperstudios/kashub/llms.txt Manage player action sequences as named macros using the W2P object. Examples demonstrate recording a mining run for a set duration and then replaying that macro. ```javascript // w2p.record([name]) – start recording actions into a macro // w2p.stop() – stop recording or playback // w2p.play([name]) – replay a previously recorded macro // Record a mining run System.print("Recording 'mining_run' – perform your actions now") w2p.record("mining_run") System.wait(30000) // capture 30 seconds of actions w2p.stop() System.print("Recording saved") // Replay it later System.print("Replaying macro...") w2p.play("mining_run") System.wait(35000) // allow time for playback w2p.stop() System.print("Macro done") ``` -------------------------------- ### player.moveTo(x, y, z, [radius], [relative]) Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/player-object.md Starts A* pathfinding to the specified coordinates, automatically avoiding obstacles and handling jumps. Coordinates can be absolute or relative. ```APIDOC ## player.moveTo(x, y, z, [radius], [relative]) ### Description Starts A* pathfinding to the specified coordinates. Automatically avoids obstacles, climbs ladders, and handles jumps. ### Parameters #### Path Parameters - **x** (number) - Required - Target X coordinate. - **y** (number) - Required - Target Y coordinate. - **z** (number) - Required - Target Z coordinate. - **radius** (number, optional) - Acceptance radius. Defaults to `1.0`. - **relative** (boolean, optional) - If `true`, coordinates are relative to player's current position. Defaults to `false`. ### Returns - `true` if pathfinding was successfully started. ### Example ```javascript // Move to specific coordinates player.moveTo(100, 64, 200) // Move 10 blocks forward relatively with 2 block tolerance player.moveTo(10, 0, 0, 2.0, true) ``` ``` -------------------------------- ### Package Kashub VSCode Extension Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/TESTING.md This command packages the Kashub VSCode extension into a .vsix file for manual installation. ```bash npm run package ``` -------------------------------- ### Code Folding Example in Kashub Source: https://github.com/kasperstudios/kashub/blob/main/docs/editor-guide.md Demonstrates code folding by showing a function definition. Click the arrow next to the line number to fold or unfold the code block. ```kashub fn myFunction() { ▼ // Code here } fn myFunction() { ▶ ``` -------------------------------- ### Get Environment Variables Source: https://context7.com/kasperstudios/kashub/llms.txt Retrieves all current environment variables available to scripts. ```APIDOC ## GET /api/variables ### Description Retrieves all current environment variables. ### Method GET ### Endpoint /api/variables ### Response #### Success Response (200) - **variables** (object) - An object containing key-value pairs of environment variables. ### Response Example ```json { "variables": { "PLAYER_HEALTH": "20", "PLAYER_X": "100.0", "PLAYER_Y": "64.0", "...": "..." } } ``` ``` -------------------------------- ### Get Environment Variables (API) Source: https://context7.com/kasperstudios/kashub/llms.txt Retrieve all current environment variables accessible by scripts. ```bash curl http://localhost:25566/api/variables # {"variables":{"PLAYER_HEALTH":"20","PLAYER_X":"100.0","PLAYER_Y":"64.0",...}} ``` -------------------------------- ### Write Your First Kashub Script Source: https://github.com/kasperstudios/kashub/blob/main/docs/quick-start.md This script prints a greeting and displays player information like name, health, hunger, and position. It's a good starting point for understanding basic Kashub commands. ```javascript // My First Kashub Script System.print("Hello, Kashub!") // Get player information let health = player.getHealth() let hunger = player.getHunger() let name = player.getName() let pos = player.getPos() // Display information System.print("Player: " + name) System.print("Health: " + health + "/20") System.print("Hunger: " + hunger + "/20") System.print("Position: X=" + pos.x + " Y=" + pos.y + " Z=" + pos.z) System.print("Script complete!") ``` -------------------------------- ### Auto-Heal Script Example Source: https://github.com/kasperstudios/kashub/blob/main/docs/quick-start.md This script continuously monitors player health and uses a golden apple when health drops below 10. It includes checks and waits to prevent spamming actions. ```javascript System.print("Auto-Heal script starting...") // Check health every second while (true) { let health = player.getHealth() if (health < 10) { System.print("Low health detected! Healing...") // Try to use a golden apple inventory.use("golden_apple") // Wait 5 seconds before checking again System.wait(5000) } // Check again in 1 second System.wait(1000) } ``` -------------------------------- ### Climbing Navigation (In Development) Source: https://github.com/kasperstudios/kashub/blob/main/docs/pathfinding-guide.md Shows how pathfinding will support climbing actions like ladders, vines, and scaffolding. ```javascript // Climbs ladders automatically player.moveTo(coordinatesUpLadder) ``` -------------------------------- ### Control Game Visuals in JavaScript Source: https://context7.com/kasperstudios/kashub/llms.txt Adjust client-side visual settings like brightness and field of view using the Game object. Examples include enabling fullbright and setting a custom field of view, or toggling fullbright based on world time. ```javascript // game.setGamma(value) – set brightness (e.g. 1.0 = default, 100.0 = max) // game.fullBright() – shortcut for maximum brightness (gamma = 100.0) // game.setFov(value) – set field of view in degrees // Enable fullbright for mining, restore defaults after game.fullBright() game.setFov(90) System.print("Fullbright ON, FOV = 90") // Example: toggle fullbright based on world time let time = world.getTime() if (time > 13000 && time < 23000) { game.fullBright() } else { game.setGamma(1.0) } ``` -------------------------------- ### Get Current Crosshair Target Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/vision-object.md Use this to get information about the block or entity the player is currently looking at. Returns null if no target is found. ```javascript let target = vision.getTarget() if (target != null && target.type == "block") { System.print("Looking at: " + target.blockId) } ``` -------------------------------- ### Replay a Recorded Macro with w2p.play() Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/w2p-object.md Use `w2p.play()` to execute a previously recorded macro. Provide the macro's name; it defaults to 'default' if omitted. This method is used to replay sequences of player actions. ```javascript w2p.play("mining_run") System.print("Playing macro...") ``` -------------------------------- ### world.getTime() Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/world-object.md Gets the current time of day within the world. ```APIDOC ## world.getTime() ### Description Returns the current world time of day. ### Returns Number (0-24000) ``` -------------------------------- ### tag.itemsWith(tagId) Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/tag-object.md Get a list of all items that have a specific tag. Returns a list of item IDs. ```APIDOC ## tag.itemsWith(tagId) ### Description Get a list of all items that have a specific tag. ### Parameters #### Path Parameters - **tagId** (string) - Required - Tag identifier ### Returns - **List[string]** - List of strings (item IDs) ### Example ```javascript let wools = tag.itemsWith("minecraft:wool") System.print("Found " + wools.length() + " types of wool") ``` ``` -------------------------------- ### w2p.play(name) Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/w2p-object.md Plays back a previously recorded macro. If no name is provided, it defaults to playing the 'default' macro. ```APIDOC ## w2p.play(name) ### Description Plays back a previously recorded macro. ### Parameters #### Path Parameters - **name** (string, optional) - The name of the macro to play. Defaults to "default". ### Returns - `true` ### Request Example ```javascript // Replay the "mining_run" macro w2p.play("mining_run") System.print("Playing macro...") ``` ``` -------------------------------- ### Getting Array Length Source: https://github.com/kasperstudios/kashub/blob/main/docs/khscript-syntax.md Determine the number of elements in an array. Useful for checking if any items were found or for loop conditions. ```javascript let ores = scanner.blocks("diamond_ore", 32) System.print("Found " + ores.length() + " ores") ``` -------------------------------- ### Get Current System Timestamp Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/system-object.md Retrieves the current system timestamp in milliseconds. This can be used to measure the duration of operations. ```javascript let start = System.time() // ... do something ... let elapsed = System.time() - start System.print("Action took " + elapsed + "ms") ``` -------------------------------- ### Round Up to Nearest Integer Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/math-object.md Use Math.ceil() to get the smallest integer greater than or equal to a given number. It rounds up. ```javascript Math.ceil(5.1) // 6 ``` -------------------------------- ### game.fullBright() Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/game-object.md Sets the client brightness to maximum (100.0). ```APIDOC ## game.fullBright() ### Description Sets the brightness to maximum (100.0). ### Method N/A (This is a method call, not an HTTP endpoint) ### Endpoint N/A ### Request Example ```javascript game.fullBright() ``` ### Response #### Success Response (200) - **value** (boolean) - `true` on success. ``` -------------------------------- ### System Object Methods Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/V2_API_MIGRATION.md Provides a list of available methods for the System object in V2. ```APIDOC ## System Object ### Methods - **System.print(message)**: Output to chat and console. - **System.log(message)**: Output to console only. - **System.chat(message)**: Send chat message. - **System.wait(ms)**: Sleep for milliseconds. - **System.time()**: Get current timestamp. - **System.exit()**: Stop script. - **System.gc()**: Garbage collection. - **System.memory()**: Memory usage info. ``` -------------------------------- ### Round Down to Nearest Integer Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/math-object.md Use Math.floor() to get the largest integer less than or equal to a given number. It rounds down. ```javascript Math.floor(5.9) // 5 ``` -------------------------------- ### Print Hello World in Kashub Source: https://github.com/kasperstudios/kashub/blob/main/docs/examples/README.md A basic script to print a message to the console. Useful for verifying script execution. ```javascript System.print("Hello, Kashub!") ``` -------------------------------- ### Get Absolute Value Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/math-object.md Use Math.abs() to return the absolute value of a number. It accepts one numeric argument. ```javascript Math.abs(-5) // 5 ``` -------------------------------- ### Array Data Type Source: https://github.com/kasperstudios/kashub/blob/main/docs/khscript-syntax.md Arrays store ordered lists of values. Examples include lists of ore locations or inventory items. ```javascript let ores = scanner.blocks("diamond_ore", 32) // [{x: 100, y: 12, z: 200}, ...] let items = inventory.getItems() // [{slot: 0, id: "diamond", count: 5}, ...] ``` -------------------------------- ### System Object Methods Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/V2_API_MIGRATION.md Lists available methods for the System object, used for output, timing, and script control. ```javascript System.print(message) // Output to chat and console System.log(message) // Output to console only System.chat(message) // Send chat message System.wait(ms) // Sleep for milliseconds System.time() // Get current timestamp System.exit() // Stop script System.gc() // Garbage collection System.memory() // Memory usage info ``` -------------------------------- ### Object Data Type Source: https://github.com/kasperstudios/kashub/blob/main/docs/khscript-syntax.md Objects represent collections of key-value pairs. Examples include player position or nearest enemy data. ```javascript let pos = player.getPos() // {x: 100, y: 64, z: 200} let enemy = vision.nearest("zombie", 10) // {type: "zombie", x: 105, ...} ``` -------------------------------- ### Replacing For Loops with While Loops Source: https://github.com/kasperstudios/kashub/blob/main/docs/khscript-syntax.md Demonstrates how to replicate the functionality of a `for` loop using a `while` loop, as `for` loops are not supported. ```javascript // Instead of: for (let i = 0; i < 10; i++) let i = 0 while (i < 10) { System.print(i) i = i + 1 } ``` -------------------------------- ### System.gc() Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/system-object.md Initiates a request for immediate Java Garbage Collection. ```APIDOC ## System.gc() ### Description Requests immediate Java Garbage Collection. ### Returns `null` ``` -------------------------------- ### System.print() Migration Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/V2_API_MIGRATION.md Migrates the V1 'print' command to the V2 'System.print()' method for outputting messages. ```APIDOC ## System.print() ### Description Outputs a message to both the chat and the console. ### Method System.print(message) ### Parameters - **message** (string) - Required - The message to print. ``` -------------------------------- ### Get Block ID at Coordinates Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/world-object.md Retrieves the block ID at specific x, y, and z coordinates. Returns null if the world is not loaded. ```javascript let blockAtFeet = world.getBlock(100, 64, 100) System.print("Standing on: " + blockAtFeet) ``` -------------------------------- ### Get Player Position Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/player-object.md Retrieves the player's current world coordinates. The returned object contains `x`, `y`, and `z` properties. ```javascript let pos = player.getPos() System.print("Currently at: " + pos.x + ", " + pos.y + ", " + pos.z) ``` -------------------------------- ### Manage Inventory with Inventory Object Source: https://context7.com/kasperstudios/kashub/llms.txt Use inventory.getItems() to list all items, inventory.count() to tally specific items, and inventory.getEmptySlots() to check available space. Items can be moved with inventory.swap() or dropped with inventory.drop(). ```javascript // Print full inventory let items = inventory.getItems() System.print("Inventory (" + items.length() + " stacks, " + inventory.getEmptySlots() + " free slots):") let i = 0 while (i < items.length()) { let it = items[i] System.print(" [" + it.slot + "] " + it.name + " x" + it.count) i = i + 1 } // Heal when health < 10, use golden apple let health = player.getHealth() if (health < 10) { let used = inventory.use("golden_apple") if (used) { System.print("Used golden apple (HP was " + health + ")") System.wait(5000) } else { System.print("No golden apple available!") } } // Move diamond sword from slot 9 to hotbar slot 0, then drop everything in slot 15 inventory.swap(9, 0) inventory.drop(15, true) // Count resources System.print("Diamonds: " + inventory.count("diamond")) System.print("Iron: " + inventory.count("iron_ingot")) ``` -------------------------------- ### Get Number of Empty Inventory Slots Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/inventory-object.md Returns the count of available empty slots within the main inventory (slots 0-35). ```javascript inventory.getEmptySlots() ``` -------------------------------- ### Configure Kashub VSCode Extension Settings Source: https://context7.com/kasperstudios/kashub/llms.txt Configure the Kashub extension's connection URLs and behavior. Ensure these match your running Minecraft mod instance. ```json // .vscode/settings.json { "kashub.apiUrl": "http://localhost:25566", "kashub.wsUrl": "ws://localhost:25567", "kashub.autoConnect": true, "kashub.showConsoleOnRun": true } ``` -------------------------------- ### Auto-Heal Script with Kashub Source: https://github.com/kasperstudios/kashub/blob/main/README.md An example of an auto-heal script that continuously monitors player health and uses a golden apple when health drops below a threshold. ```javascript // Monitor health and auto-heal while (true) { let health = player.getHealth() if (health < 10) { System.print("Low health! Healing...") inventory.use("golden_apple") System.wait(5000) } System.wait(1000) } ``` -------------------------------- ### Method Chaining (Simulated) Source: https://github.com/kasperstudios/kashub/blob/main/docs/khscript-syntax.md Method chaining is not directly supported. Simulate it by storing intermediate results in variables. ```javascript // Not directly supported, but you can do: let pos = player.getPos() player.moveTo(pos.x + 10, pos.y, pos.z) ``` -------------------------------- ### Safe Movement with Retries Source: https://github.com/kasperstudios/kashub/blob/main/docs/pathfinding-guide.md Implements a safe movement function that retries navigation up to a maximum number of attempts if the player gets stuck or times out. ```javascript fn safeMoveTo(x, y, z) { let maxAttempts = 3 let attempt = 0 while (attempt < maxAttempts) { player.moveTo(x, y, z) let timeout = 0 while (player.isMoveActive() && timeout < 60) { System.wait(1000) timeout = timeout + 1 } if (!player.isMoveActive()) { System.print("Arrived successfully!") return true } System.print("Timeout, retrying...") player.stopMove() attempt = attempt + 1 System.wait(2000) } System.print("Failed to reach destination") return false } ``` -------------------------------- ### System Object Methods Source: https://github.com/kasperstudios/kashub/blob/main/README.md Provides utility functions for script output, chat interaction, and execution control. Use 'System.print' for visible output and 'System.wait' for pausing execution. ```javascript System.print("message") // Output to chat and console System.log("message") // Output to console only System.chat("message") // Send chat message System.wait(ms) // Sleep for milliseconds System.time() // Get current timestamp System.exit() // Stop script execution System.gc() // Request garbage collection System.memory() // Get memory usage info ``` -------------------------------- ### Pathfinding Demo Script Source: https://github.com/kasperstudios/kashub/blob/main/docs/examples/README.md Demonstrates automated movement between a series of defined waypoints, utilizing the built-in obstacle avoidance of player.moveTo(). ```javascript System.print("Pathfinding demo starting...") // Define waypoints let waypoints = [ {x: 100, y: 64, z: 200}, {x: 150, y: 64, z: 250}, {x: 200, y: 64, z: 200}, {x: 150, y: 64, z: 150} ] let i = 0 while (i < waypoints.length()) { let wp = waypoints[i] System.print("Moving to waypoint " + (i + 1)) // player.moveTo() handles obstacle avoidance automatically player.moveTo(wp.x, wp.y, wp.z) // Wait until movement finishes while (player.isMoveActive()) { System.wait(100) } System.print("Arrived at " + (i + 1)) i = i + 1 } System.print("Pathfinding complete!") ``` -------------------------------- ### Valid Variable Names Source: https://github.com/kasperstudios/kashub/blob/main/docs/khscript-syntax.md Variable names must start with a letter or underscore, can contain letters, numbers, and underscores, are case-sensitive, and cannot be reserved keywords. ```javascript let health = 20 let player_name = "Steve" let _temp = 5 let value123 = 100 ``` -------------------------------- ### Use 'System.log()' for Debugging Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/V2_API_MIGRATION.md Utilize 'System.log()' for debugging purposes to avoid cluttering the in-game chat with excessive messages. ```javascript System.log("Debugging message") ``` -------------------------------- ### Inspect Variable Value in Debug Mode Source: https://github.com/kasperstudios/kashub/blob/main/docs/editor-guide.md When paused at a breakpoint, hover over variables to see their current values. This example shows how 'health' might be displayed. ```javascript let health = player.getHealth() // Hover shows: health = 20 ``` -------------------------------- ### Migrate V1 Auto-Heal Script to V2 Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/V2_API_MIGRATION.md Compares an old V1 auto-heal script with its V2 equivalent, demonstrating the use of `while`, `player.getHealth`, `System.print`, `inventory.use`, and `System.wait`. ```javascript // V1 - Old style loop { if $PLAYER_HEALTH < 10 { print "Low health!" inventory use golden_apple wait 5000 } wait 1000 } ``` ```javascript // V2 - New style while (true) { let health = player.getHealth() if (health < 10) { System.print("Low health!") inventory.use("golden_apple") System.wait(5000) } System.wait(1000) } ``` -------------------------------- ### Enable Full Brightness Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/game-object.md Maximizes the client's brightness to 100.0. Call this method for maximum visibility. ```javascript game.fullBright() ``` -------------------------------- ### Invalid Variable Names Source: https://github.com/kasperstudios/kashub/blob/main/docs/khscript-syntax.md Demonstrates invalid variable names that violate naming rules, such as starting with a number, using hyphens, or using reserved keywords. ```javascript let 123value = 100 // Cannot start with number let player-name = "Steve" // Cannot use hyphens let if = 5 // Cannot use keywords ``` -------------------------------- ### Simulating Multi-line Comments Source: https://github.com/kasperstudios/kashub/blob/main/docs/khscript-syntax.md Shows how to achieve multi-line comments by using multiple single-line comments, as multi-line comment syntax is not supported. ```javascript // This is a comment // This is another comment // And another one ``` -------------------------------- ### Update Version and Changelog for Release Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/TESTING.md Before building for release, update the version number in package.json and the CHANGELOG.md file. ```bash npm run compile npm run package ``` -------------------------------- ### Get and Display Player Information in Kashub Source: https://github.com/kasperstudios/kashub/blob/main/docs/examples/README.md Retrieves and displays the player's current health, hunger, name, and position. Requires player object to be available. ```javascript let health = player.getHealth() let hunger = player.getHunger() let name = player.getName() let pos = player.getPos() System.print("=== Player Info ===") System.print("Name: " + name) System.print("Health: " + health + "/20") System.print("Hunger: " + hunger + "/20") System.print("Position: " + pos.x + ", " + pos.y + ", " + pos.z) ``` -------------------------------- ### Kashub Snippet: player.moveTo() Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/TESTING.md Inserts the player.moveTo(x, y, z) function template. Trigger by typing 'pmove' and pressing Tab. ```plaintext pmove ``` -------------------------------- ### Kashub Object and Method Syntax Source: https://github.com/kasperstudios/kashub/blob/main/docs/quick-start.md Access object properties and call methods using dot notation. For example, `player` is an object, and `getHealth()` is a method called with parentheses. ```javascript player.getHealth() ``` -------------------------------- ### Kashub Snippet: System.print() Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/TESTING.md Inserts the System.print() function template. Trigger by typing 'sysprint' and pressing Tab. ```plaintext sysprint ``` -------------------------------- ### Get Memory Usage Information Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/system-object.md Returns an object containing details about the current memory usage, including used, free, total, and maximum available memory in MB. ```javascript let mem = System.memory() System.print("Memory usage: " + mem.used + " / " + mem.max + " MB") ``` -------------------------------- ### System Object API Source: https://context7.com/kasperstudios/kashub/llms.txt Global utilities for output, timing, memory, and script lifecycle control. All KHScript files have access to System without any import. ```APIDOC ## System Object API ### Description Global utilities for output, timing, memory, and script lifecycle control. ### Methods - **System.print(message)**: outputs to in-game chat ([KH] prefix) and console - **System.log(message)**: outputs to console only - **System.chat(message)**: sends a chat message / slash command - **System.wait(ms)**: pauses script execution for N milliseconds - **System.time()**: returns current system timestamp (ms) - **System.exit()**: immediately stops the current script - **System.gc()**: requests Java garbage collection - **System.memory()**: returns {used, free, total, max} in MB ### Example ```javascript System.print("Script started!") let start = System.time() let mem = System.memory() System.log("Memory: " + mem.used + " / " + mem.max + " MB") if ((mem.used / mem.max) * 100 > 80) { System.gc() } System.wait(2000) let elapsed = System.time() - start System.print("Done in " + elapsed + " ms") ``` ``` -------------------------------- ### Get all items with a specific tag Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/tag-object.md Use `tag.itemsWith` to retrieve a list of all item IDs that are associated with a given tag ID. This can be used to find all variations of a categorized item. ```javascript let wools = tag.itemsWith("minecraft:wool") System.print("Found " + wools.length() + " types of wool") ``` -------------------------------- ### Using Functions for Reusable Code Source: https://github.com/kasperstudios/kashub/blob/main/docs/khscript-syntax.md Shows how to define and use functions to encapsulate reusable logic, promoting modularity and reducing code duplication. ```javascript fn heal() { let health = player.getHealth() if (health < 10) { inventory.use("golden_apple") System.wait(5000) } } // Use the function multiple times heal() // ... do other stuff ... heal() ``` -------------------------------- ### System.print(message) Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/system-object.md Outputs a message to the in-game chat and the console. The in-game message is prefixed with "§7[KH]§r". ```APIDOC ## System.print(message) ### Description Outputs a message to the in-game chat (prefixed with `§7[KH]§r`) and the console. ### Parameters #### Parameters - `message` (string): The message to output. ### Returns `null` ### Example ```javascript System.print("Hello from KasHub!") ``` ``` -------------------------------- ### Registry API Usage for Status Effects (Minecraft 1.21+) Source: https://github.com/kasperstudios/kashub/blob/main/DEVELOPMENT_NOTES.md Use the correct method to get the path of a status effect in Minecraft 1.21 and later. The old method is deprecated. ```java // ❌ OLD (doesn't work in 1.21+) StatusEffect type = effect.getEffectType(); String name = Registries.STATUS_EFFECT.getId(type).getPath(); // ✅ NEW (correct for 1.21+) String name = Registries.STATUS_EFFECT.getId(effect.getEffectType().value()).getPath(); ``` -------------------------------- ### Debug Kashub Scripts with VSCode DAP Source: https://context7.com/kasperstudios/kashub/llms.txt Set up VSCode launch configuration to debug .kh scripts using the Debug Adapter Protocol. Set 'program' to '${file}' to debug the currently open script. ```json // .vscode/launch.json – debug a .kh script via DAP { "version": "0.2.0", "configurations": [ { "type": "kashub", "request": "launch", "name": "Debug Current Script", "program": "${file}" } ] } ``` -------------------------------- ### Kashub Snippet: player.stopMoving() Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/TESTING.md Inserts the player.stopMoving() function template. Trigger by typing 'pstop' and pressing Tab. ```plaintext pstop ``` -------------------------------- ### Generate Random Number Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/math-object.md Use Math.random() to generate a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive). Combine with Math.floor() to get random integers within a range. ```javascript // Random integer between 0 and 10 let r = Math.floor(Math.random() * 11) ``` -------------------------------- ### Get All Inventory Items Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/inventory-object.md Retrieves a list of all non-empty item stacks in the player's inventory. Each item object contains details like slot, ID, count, and name. ```javascript let items = inventory.getItems() for (let i = 0; i < items.length(); i++) { System.print("Slot " + items[i].slot + ": " + items[i].name) } ``` -------------------------------- ### Prevent Game Freezes with Delays in Loops Source: https://github.com/kasperstudios/kashub/blob/main/docs/quick-start.md Always include a delay within infinite loops to prevent the script from consuming all resources and freezing the game. The 'GOOD' example demonstrates this practice. ```javascript // BAD - Will freeze the game! while (true) { player.attack() } // GOOD - Adds delay while (true) { player.attack() System.wait(100) } ``` -------------------------------- ### CrashGuard with Options Source: https://github.com/kasperstudios/kashub/blob/main/docs/khscript-syntax.md Configure CrashGuard with specific options like timeout and minimum FPS to monitor. This allows for more fine-grained control over script execution safety. ```javascript crashguard(timeout=10000, minFps=30) { // Code with timeout and FPS monitoring let ores = scanner.blocks("diamond_ore", 64) // Process ores... } ``` -------------------------------- ### player Object Methods Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/V2_API_MIGRATION.md Provides a list of available methods for the player object in V2. ```APIDOC ## player Object ### Methods - **player.getHealth()**: Get health (0-20). - **player.getHunger()**: Get hunger (0-20). - **player.getName()**: Get player name. - **player.getPos()**: Get position {x, y, z}. - **player.moveTo(x, y, z)**: Move to coordinates. - **player.lookAt(x, y, z)**: Look at coordinates. - **player.sprint(enabled)**: Enable/disable sprint. - **player.attack([entity])**: Attack entity. - **player.breakBlock()**: Break block. - **player.placeBlock(name)**: Place block. - **player.chat(message)**: Send chat message. ``` -------------------------------- ### Force Stop and Retry Player Movement Source: https://github.com/kasperstudios/kashub/blob/main/docs/pathfinding-guide.md Use this snippet to force the player to stop their current movement and then attempt to move to the target coordinates again. Useful when the player gets stuck mid-path. ```javascript // Force stop and retry player.stopMove() System.wait(1000) player.moveTo(x, y, z) ``` -------------------------------- ### Kashub Snippet: player.input() Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/TESTING.md Inserts the player.input(action, type) function template. Trigger by typing 'pinput' and pressing Tab. ```plaintext pinput ``` -------------------------------- ### Inventory Object Methods Source: https://github.com/kasperstudios/kashub/blob/main/README.md Methods for managing the player's inventory, including checking items, counts, and performing actions like dropping or crafting. ```APIDOC ## Inventory Object ### Description Provides tools for interacting with and managing the player's inventory. ### Methods - `inventory.check()`: Get the current status of the inventory. - `inventory.count(itemName)`: Count the number of a specific item in the inventory. - `inventory.find(itemName)`: Find the slot number of a specific item. - `inventory.getItems()`: Get a list of all items in the inventory. - `inventory.getEmptySlots()`: Count the number of available empty slots. - `inventory.drop(slot, dropAll)`: Drop an item from a specified slot. - `inventory.swap(slot1, slot2)`: Swap items between two specified slots. - `inventory.equip(slot)`: Equip armor or a shield from a specified slot. - `inventory.use(itemName)`: Use an item by its name. - `inventory.craft(itemName, quantity)`: Craft a specified item in a given quantity. ``` -------------------------------- ### Simulate Player Input Actions Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/player-object.md Allows low-level simulation of player actions like movement, jumping, attacking, and interacting. Supports 'press', 'release', and 'tap' interaction types. ```javascript // Sprint forward player.input("forward", "press") player.input("sprint", "press") // Stop after 2 seconds System.wait(2000) player.input("forward", "release") player.input("sprint", "release") // Single jump player.input("jump", "tap") ``` -------------------------------- ### Perform Mathematical Operations in JavaScript Source: https://context7.com/kasperstudios/kashub/llms.txt Utilize the Math object for standard mathematical functions, similar to the browser's Math API. Examples demonstrate calculating distance between points and generating random numbers for cooldowns. ```javascript // Math.sqrt(x) Math.abs(x) Math.min(a,b) Math.max(a,b) // Math.floor(x) Math.ceil(x) Math.round(x) // Math.random() Math.pow(base, exp) // Distance between two points (ignoring Y) let pos = player.getPos() let targetX = 200 let targetZ = 300 let dx = targetX - pos.x let dz = targetZ - pos.z let dist = Math.sqrt(Math.pow(dx, 2) + Math.pow(dz, 2)) System.print("Distance to target: " + Math.round(dist) + " blocks") // Random cooldown between 800 and 1200 ms let cooldown = Math.floor(Math.random() * 400) + 800 System.wait(cooldown) // Clamp a value fn clamp(val, lo, hi) { return Math.max(lo, Math.min(hi, val)) } let safeHealth = clamp(player.getHealth(), 0, 20) ``` -------------------------------- ### player.input(action, type) Source: https://github.com/kasperstudios/kashub/blob/main/docs/api/player-object.md Simulates low-level player inputs such as movement, jumping, attacking, or using items. ```APIDOC ## player.input(action, type) ### Description Low-level simulation of player actions/inputs. ### Parameters #### Path Parameters - **action** (string) - Required - Action to perform. Supported: `"forward"` (`"w"`), `"back"` (`"s"`), `"left"` (`"a"`), `"right"` (`"d"`), `"jump"` (`"space"`), `"sneak"` (`"shift"`), `"sprint"`, `"attack"` (`"leftclick"`), `"use"` (`"rightclick"`). - **type** (string) - Required - Interaction type. Supported: `"press"` (hold down), `"release"`, `"tap"` (single click/press). ### Returns - `true` if valid, `false` otherwise. ### Example ```javascript // Sprint forward player.input("forward", "press") player.input("sprint", "press") // Stop after 2 seconds System.wait(2000) player.input("forward", "release") player.input("sprint", "release") // Single jump player.input("jump", "tap") ``` ``` -------------------------------- ### Autocomplete Script Prefixes (API) Source: https://context7.com/kasperstudios/kashub/llms.txt Provides code completion suggestions for a given prefix in a specific line and column. ```bash curl -X POST http://localhost:25566/api/autocomplete \ -H "Content-Type: application/json" \ -d '{"code":"","prefix":"player.","line":1,"column":7}' # {"items":[{"label":"getHealth","kind":"Method","detail":"Returns current health","insertText":"getHealth()"},...]} ``` -------------------------------- ### Inspect Target with Vision Object Source: https://context7.com/kasperstudios/kashub/llms.txt Use vision.getTarget() to get information about the block or entity the player is looking at. Use vision.getNearest() to find the closest entity matching criteria. vision.isLookingAt() checks if the player is targeting a specific entity or block. ```javascript // Inspect what the player is looking at let target = vision.getTarget() if (target != null) { if (target.type == "block") { System.print("Looking at block: " + target.blockId) } else if (target.type == "entity") { System.print("Looking at entity: " + target.entityId) } } // Find and engage the nearest hostile mob (within 10 blocks, aim for the head) let enemy = vision.getNearest("hostile", 10, "head") if (enemy != null) { System.print("Target: " + enemy.type + " HP: " + enemy.health + " dist: " + enemy.distance) player.lookAt(enemy.x, enemy.y, enemy.z) player.attack(enemy) } else { System.print("No hostiles nearby") } // Guard: abort if player is NOT looking at a crafting table if (!vision.isLookingAt("crafting_table", 4)) { System.print("Please look at a crafting table first.") System.exit() } ``` -------------------------------- ### Player Object Methods Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/V2_API_MIGRATION.md Lists available methods for the player object, controlling player actions and retrieving player state. ```javascript player.getHealth() // Get health (0-20) player.getHunger() // Get hunger (0-20) player.getName() // Get player name player.getPos() // Get position {x, y, z} player.moveTo(x, y, z) // Move to coordinates player.lookAt(x, y, z) // Look at coordinates player.sprint(enabled) // Enable/disable sprint player.attack([entity]) // Attack entity player.breakBlock() // Break block player.placeBlock(name) // Place block player.chat(message) // Send chat message ``` -------------------------------- ### HTTP REST API Endpoints Source: https://context7.com/kasperstudios/kashub/llms.txt The Kashub mod exposes a REST API on port 25566 when enabled in the configuration. Use it to get mod status, validate KHScript code, or execute scripts remotely. Requires `apiEnabled: true` in `config/kashub/config.json`. ```bash # GET /api/status – mod status and player info curl http://localhost:25566/api/status # {"status":"running","player":"Steve","taskCount":2,"version":"v0.9.0-beta"} ``` ```bash # POST /api/validate – validate KHScript code curl -X POST http://localhost:25566/api/validate \ -H "Content-Type: application/json" \ -d '{"code":"let h = player.getHealth()\nSystem.print(h)"}' # {"valid":true,"errors":[],"errorCount":0,"warningCount":0} ``` ```bash # POST /api/run – execute a script curl -X POST http://localhost:25566/api/run \ -H "Content-Type: application/json" \ -d '{"code":"System.print(\"Hello from curl!\")","filename":"test.kh"}' ``` -------------------------------- ### Math Object Methods Source: https://github.com/kasperstudios/kashub/blob/main/kashub-vscode/V2_API_MIGRATION.md Provides a list of available mathematical methods in V2. ```APIDOC ## Math Object ### Methods - **Math.sqrt(x)**: Square root. - **Math.abs(x)**: Absolute value. - **Math.min(a, b)**: Minimum. - **Math.max(a, b)**: Maximum. - **Math.floor(x)**: Round down. - **Math.ceil(x)**: Round up. - **Math.round(x)**: Round to nearest. - **Math.random()**: Random 0-1. - **Math.pow(base, exp)**: Power. ```