### Python Tuple and List Literals in Pyjinn Source: https://minescript.net/pyjinn Illustrates the creation of tuple and list literals in Pyjinn. Includes examples of tuple assignment and basic list/tuple construction. ```python # Tuple literal: (X, Y, Z) # Tuple assignment: X, Y = 1, 2 X, Y = (1, 2) X, Y = [1, 2] # List literal: [X, Y, Z] ``` -------------------------------- ### Get Help for Minescript Commands Source: https://minescript.net/docs The `\help` command displays documentation for a specified Minescript command or script name. This feature is available since version 1.19.2. ```text \help NAME ``` -------------------------------- ### Timer Command Examples Source: https://minescript.net/sdm_downloads/timer-v1 Illustrates practical applications of the timer command for various scenarios, including scheduling chat messages, self-echoes, executing in-game commands, and triggering custom actions like screenshots. Demonstrates escaping special characters within commands. ```plaintext # Send a chat at 12 noon: \timer 12pm chat "FYI: it is now noon" # Send a message to yourself at 12:30: \timer 12:30pm echo "note to self: time to eat lunch" # Copy blocks labeled “timed_copy” in 2 minutes: \timer 2m execute "\\copy ~ ~ ~ ~64 ~64 ~64 timed_copy" # Set game time to midday every hour: \timer 1h* execute "/time set day" # Take 3 screenshots 5 seconds apart: \timer 5s*3 eval "screenshot()" ``` -------------------------------- ### Manually Convert Pyjinn Function to Java Interface Source: https://minescript.net/pyjinn Demonstrates the manual conversion of a Pyjinn function to a Java interface implementation by calling the Java interface as a Python constructor. This example converts a lambda to a `Runnable` interface. ```Python Runnable = JavaClass("java.lang.Runnable") x = Runnable(lambda: print("hello!")) x.run() # prints: hello! ``` -------------------------------- ### Timer Command Examples Source: https://minescript.net/sdm_categories/featured-scripts Demonstrates various use cases for the timer command, including sending chat messages, echoing messages, executing game commands, and evaluating functions. It highlights different time formats and repetition options. ```plaintext \timer 12pm chat "FYI: it is now noon" \timer 12:30pm echo "note to self: time to eat lunch" \timer 2m execute "\\copy ~ ~ ~ ~64 ~64 ~64 timed_copy" \timer 1h* execute "/time set day" \timer 5s*3 eval "screenshot()" ``` -------------------------------- ### Reading and Generating Minecraft Commands from BlockPack (Python) Source: https://minescript.net/sdm_downloads/lib_blockpack_parser An example demonstrating how to read block data from a world region using BlockPack, parse it with BlockPackParser, and then generate Minecraft 'fill' and 'setblock' commands for each tile. It iterates through the parsed tiles and their respective command parameters. ```Python from minescript import BlockPack, echo from lib_blockpack_parser import BlockPackParser blockpack = BlockPack.read_world((0, 0, 0), (100, 100, 100)) parser = BlockPackParser.parse_blockpack(blockpack) for tile in parser.tiles: for pos1, pos2, block in tile.iter_fill_params(): echo(f"fill {pos1} {pos2} {parser.palette[block]}") for pos, block in tile.iter_setblock_params(): echo(f"setblock {pos} {parser.palette[block]}") ``` -------------------------------- ### Draw Text Library Usage in Python Source: https://minescript.net/sdm_downloads/draw_text-v2 This example shows how to import and use the draw_text script as a library in Python. It demonstrates drawing text, updating its position, color, and content dynamically. ```python from draw_text import (draw_string, draw_centered_string) import time text = draw_string("some white text", x=20, y=20, color=0xffffff, scale=4) time.sleep(5) text.x.set_value(25) # Move text to the right. time.sleep(1) text.y.set_value(25) # Move text down. time.sleep(1) text.color.set_value(0xff0000) # Change text color to red. text.string.set_value("now it's red") # Change text string. time.sleep(2) ``` -------------------------------- ### Built-in Commands Source: https://minescript.net/docs Details on essential built-in Minescript commands for listing commands, getting help, evaluating code, managing blocks, and controlling jobs. ```APIDOC ## Built-in Commands ### `ls` - **Description**: Lists all available Minescript commands, including built-in ones and user-created Python scripts. - **Usage**: `\ls` ### `help` - **Description**: Displays documentation for a specified script or command. - **Usage**: `\help NAME` - **Since**: v1.19.2 ### `eval` - **Description**: Executes Python code. Can be used for expressions (values are echoed) or statements. - **Usage**: `\eval PYTHON_CODE [LINE2 [LINE3 ...]]` - **Features**: Functions from `minescript.py` are automatically available. - **Examples**: - `\eval "entities()"` - `\eval "for e in entities(): echo(e['name'])"` - `\eval "import time" "time.sleep(3)" "screenshot()"` ### `copy` - **Description**: Copies blocks within a specified rectangular region. - **Usage**: `\copy X1 Y1 Z1 X2 Y2 Z2 [LABEL] [no_limit]` - **Parameters**: Defines the start and end coordinates of the region. `LABEL` is optional for naming the block set. `no_limit` removes the default chunk copy limit. - **Note**: See `\paste` for retrieving copied blocks. ### `paste` - **Description**: Pastes blocks previously copied using `\copy`. - **Usage**: `\paste X Y Z [LABEL]` - **Parameters**: Specifies the destination coordinates (X, Y, Z). If `LABEL` matches a previous `\copy` command, blocks from that specific copy are pasted; otherwise, the most recent unlabeled copy is used. - **Note**: Can be used across different worlds. ### `jobs` - **Description**: Lists active Minescript jobs. - **Usage**: `\jobs` or `\jobs all` - **Behavior**: `\jobs` lists parent jobs. `\jobs all` lists all jobs, including child jobs. ### `suspend` - **Description**: Pauses running Minescript jobs. - **Usage**: `\suspend [JOB_ID]` - **Behavior**: Suspends a specific job if `JOB_ID` is provided, otherwise suspends all running jobs. - **Alias**: `\z` - **Note**: See `\resume`. ### `z` - **Description**: Alias for the `\suspend` command. - **Usage**: `\z [JOB_ID]` ### `resume` - **Description**: Resumes suspended Minescript jobs. - **Usage**: `\resume [JOB_ID]` - **Behavior**: Resumes a specific suspended job if `JOB_ID` is provided, otherwise resumes all suspended jobs. - **Note**: See `\suspend`. ### `killjob` - **Description**: Terminates Minescript jobs. - **Usage**: `\killjob JOB_ID` - **Special Value**: `JOB_ID` of `-1` terminates all running and suspended jobs. ``` -------------------------------- ### Python Expressions in Pyjinn Source: https://minescript.net/pyjinn Provides examples of various Python constant expressions supported in Pyjinn, including None, booleans, numbers, strings (including raw and triple-quoted literals). ```python # Constant expressions: None # NoneType True # bool False # bool 123 # int 3.14 # float "hi" # str 'bye' # str r'\o/' # str (raw literal) """triple quoted""" '''triple quoted''' ``` -------------------------------- ### Autorun Commands Configuration Source: https://minescript.net/docs Details the configuration of autorun commands in Minescript, which execute automatically when entering specific worlds. It covers the wildcard '*' for all worlds, sequential command execution using semicolons, and provides an example of a welcome message. ```plaintext autorun[world_name]=command1; command2 autorun[*]=eval 'echo(f"Hello, {world_info().name}!")' ``` -------------------------------- ### Interact with Minecraft Java API using Minescript Source: https://minescript.net/docs Shows how to use the 'java' module in Minescript to access Minecraft's Java API. It demonstrates getting the Minecraft instance and retrieving the player's FPS. ```python from minescript import echo from java import JavaClass Minecraft = JavaClass("net.minecraft.client.Minecraft") minecraft = Minecraft.getInstance() echo("fps:", minecraft.getFps()) ``` -------------------------------- ### Minescript Python Scripting Examples Source: https://minescript.net/index This Python script demonstrates various Minescript functionalities, including sending chat messages, retrieving player data, manipulating blocks, and interacting with inventory and entities. It utilizes the `minescript` module for all game interactions. ```python import minescript # Write a message to the chat that only you can see: minescript.echo("Hello, world!") # Write a chat message that other players can see: minescript.chat("Hello, everyone!") # Get your player's current position: x, y, z = minescript.player_position() # Set the block directly beneath your player: x, y, z = int(x), int(y), int(z) minescript.execute(f"setblock {x} {y-1} {z} yellow_concrete") # Print the type of block at a particular location: minescript.echo(minescript.getblock(x, y, z)) # Display the contents of your inventory: for item_stack in minescript.player_inventory(): minescript.echo(item_stack.item) # Display the names of nearby entities: for entity in minescript.entities(): minescript.echo(entity.name) ``` -------------------------------- ### Executing a Minescript Command from Minecraft Chat Source: https://minescript.net/example This demonstrates how to execute a previously defined Minescript Python script from within the Minecraft in-game chat console. The command format involves typing the script name followed by any necessary arguments. ```plaintext example 5 ``` -------------------------------- ### Implement Java Interfaces with Pyjinn Lambdas Source: https://minescript.net/pyjinn Illustrates how Pyjinn lambda expressions can be automatically converted into implementations of Java interfaces when passed to Java methods. This example uses lambdas for `Stream::map` and `Stream::filter` operations. ```Python java_list = JavaList([x for x in range(10)]) print( java_list.stream() .map(lambda x: x * x) .filter(lambda x: x % 2 == 0) .toList()) # prints: [0, 4, 16, 36, 64] ``` -------------------------------- ### Custom Command Execution Configuration Source: https://minescript.net/docs Explains how to configure Minescript to execute external scripts or executables using Minecraft commands. This includes defining file extensions, the command to run, and optional environment variables. An example for executing JAR files is provided. ```json command = { "extension": ".jar", "command": [ "/usr/bin/java", "-jar", "{command}", "{args}" ], "environment": [ "FIRST_ENV_VAR=1234", "SECOND_ENV_VAR=2468" ] } ``` -------------------------------- ### Python Script to Create a Dynamic Sign with Minescript Source: https://minescript.net/example This Python script utilizes the Minescript library to interact with Minecraft. It retrieves the player's coordinates, identifies the block directly beneath them, and then creates a sign at the player's location displaying this information. The script also handles an optional rotation parameter for the sign. ```python from minescript import (echo, execute, getblock, player) import sys # Get the player's position, rounded to the nearest integer: x, y, z = [round(p) for p in player().position] # Get the type of block directly beneath the player: block_type = getblock(x, y - 1, z) block_type = block_type.replace("minecraft:", "").split("[")[0] sign_text = ( """{Text1:'{\"text\":\"%s\"}',Text2:'{\"text\":\"at\"}',Text3:'{\"text\":\"%d %d %d\"}'} """ % (block_type, x, y - 1, z)) # Script argument, passed from Minecraft like "example 5" rotation = int(sys.argv[1]) if len(sys.argv) > 1 else 0 if rotation < 0 or rotation > 15: raise ValueError(f"Param not an integer between 0 and 15: {rotation}") # Create a sign then set text on it: execute(f"/setblock {x} {y} {z} minecraft:birch_sign[rotation={rotation}]") execute(f"/data merge block {x} {y} {z} {sign_text}") # Write a message to the chat that echo(f"Created sign at {x} {y} {z} over {block_type}") ``` -------------------------------- ### Parse BlockPack Data with Python Source: https://minescript.net/sdm_downloads/lib_blockpack_parser-v1 Demonstrates how to read blocks from a specified world region using BlockPack.read_world, parse the BlockPack data using BlockPackParser, and then iterate through the parsed tiles to generate 'fill' and 'setblock' commands. This example requires the 'minescript' and 'lib_blockpack_parser' libraries. ```python from minescript import BlockPack, echo from lib_blockpack_parser import BlockPackParser blockpack = BlockPack.read_world((0, 0, 0), (100, 100, 100)) parser = BlockPackParser.parse_blockpack(blockpack) for tile in parser.tiles: for pos1, pos2, block in tile.iter_fill_params(): echo(f"fill {pos1} {pos2} {parser.palette[block]}") for pos, block in tile.iter_setblock_params(): echo(f"setblock {pos} {parser.palette[block]}") ``` -------------------------------- ### Minescript Python Script Output Examples Source: https://minescript.net/docs Demonstrates various ways to output messages from a Python script within Minescript, including plain text to stdout/stderr, styled JSON messages, global chat messages, and logging. It utilizes Python's print function and the minescript module. ```python # Prints a plain-text message to the in-game chat that's # visible only to you (displayed as white text): print("Note to self...") # Same as the previous print(...) statement, except # that the output to stdout is explicit: print("Note to self...", file=sys.stdout) # Same output as the previous print(...) statements, # but using a Minescript function (behavior can be # different from above print(...) statements when # using "Script output redirection"; see below): import minescript minescript.echo("Note to self...") # Echo JSON-formatted text (for styled and colored text) # as a JSON string to the in-game chat only to yourself: minescript.echo_json('{"text":"hello!", "color":"green"}') # Or as a Python dict or list converted to JSON: minescript.echo_json({"text":"hello!", "color":"green"}) # Prints a plain-text message to the in-game chat that's # visible only to you, displayed as yellow text so that # it's visually distinguishable from text written to stdout: print("Note to self...", file=sys.stderr) # Send a chat message that's visible to all players # in the world: minescript.chat("hi, friends!") # Log a message to Minecrafts log file # (in minecraft/logs/latest.log): minescript.log("This is a debug message that does not appear in-game.") ``` -------------------------------- ### Access Minecraft FPS using Java Reflection in Python Source: https://minescript.net/sdm_downloads/lib_java-v1 Demonstrates how to use the lib_java library to access Minecraft's FPS count via Java reflection. This example requires a Minecraft version with unobfuscated symbols, such as those found in dev-mode launchers or NeoForge. It utilizes `JavaClass` to instantiate Java objects and call their methods. ```python from minescript import echo from lib_java import JavaClass # This example requires a version of Minecraft # with unobfuscated symbols, like dev-mode launchers # or NeoForge. Minecraft = JavaClass("net.minecraft.client.Minecraft") minecraft = Minecraft.getInstance() echo("fps:", minecraft.getFps()) ``` -------------------------------- ### Java Array Operations Source: https://minescript.net/docs Provides functions for interacting with Java arrays, including getting their length, accessing elements, and creating new arrays. ```APIDOC ## Java Array Functions ### Description Functions for manipulating Java arrays. ### Method N/A (Python functions) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Endpoints #### `java_array_length` Returns the length of a Java array. - **array** (JavaHandle) - Handle to the Java array object. #### `java_array_index` Gets an indexed element of a Java array handle. - **array** (JavaHandle) - Handle to the Java array object. - **i** (int) - Index into the array. Returns a handle to the object at `array[i]` or `None` if null. #### `java_new_array` Creates a new Java array. - **element_type** (JavaHandle) - Handle to the Java class for the new array's type. - **elements** (List[JavaHandle]) - Handles to Java objects to populate the new array. Returns a handle to the new Java array. ### Response #### Success Response (200) - **length** (int) - Length of the Java array (for `java_array_length`). - **element** (JavaHandle or None) - Handle to the indexed element (for `java_array_index`). - **new_array** (JavaHandle) - Handle to the newly created Java array (for `java_new_array`). #### Response Example ```json { "length": 10, "element": "handle_to_java_object", "new_array": "handle_to_new_java_array" } ``` ``` -------------------------------- ### BlockPacker.__init__ Source: https://minescript.net/docs Initializes a new, empty BlockPacker. ```APIDOC ## BlockPacker.__init__ ### Description Creates a new, empty blockpacker. ### Method `BlockPacker()` ### Compatibility Pyjinn only. ``` -------------------------------- ### Get Chat Input State (Python) Source: https://minescript.net/docs Retrieves the current text content of the chat input box and the cursor's position within that text. ```python text, position = chat_input() ``` -------------------------------- ### Python vs. Java String Methods in Pyjinn Source: https://minescript.net/pyjinn Illustrates calling string methods in Pyjinn, showing how Python-compatible methods (like str.startswith) and Java's String methods (like String.startsWith) can be invoked. Note the case sensitivity difference. ```python # Python-compatible call to str.startswith(): print("foo".startswith("o", 1)) # prints: True # Java call to String.startsWith() (note the different capitalization): print("foo".startsWith("f")) # prints: True ``` -------------------------------- ### Get Local Player Name Source: https://minescript.net/docs Retrieves the name of the local player in the Minescript environment. This function returns a string representing the player's name. ```python player_name() -> str ``` -------------------------------- ### Get Job Information Source: https://minescript.net/docs Retrieves information about active Minescript jobs. This function returns a list of JobInfo objects, where JobInfo.self is True for the enclosing job. ```python job_info() -> List[JobInfo] ``` -------------------------------- ### In-game Commands - Command Basics Source: https://minescript.net/docs Explains how to use Minescript commands in-game, including syntax, running Python scripts as commands, and handling parameters with tilde and dollar syntax. ```APIDOC ## In-game Commands - Command Basics ### Description Minescript commands are accessed via the in-game chat console. They are distinguished from standard Minecraft commands by a backslash (`\`) prefix instead of a forward slash (`/`). Python scripts located in the `minecraft/minescript/` directory can be executed as commands by prefixing their filename (without the `.py` extension) with a backslash. For instance, `minecraft/minescript/build_fortress.py` is invoked as `\build_fortress`. ### Command Syntax - **Script Execution**: `\` - **Parameter Passing**: Scripts can accept command-line parameters. See 'Script input' for details. - **Relative Coordinates**: Tilde syntax (`~ ~ ~`, `~-1 ~2 ~-3`) can be used for coordinates relative to the player. - **Absolute Player Coordinates**: `$x`, `$y`, and `$z` can represent the player's current X, Y, and Z coordinates, respectively. - **Optional Parameters**: Indicated by square brackets `[ ]` in documentation, but omitted during command entry. ``` -------------------------------- ### Python Statements: Class Definitions, Instance Creation, Field Access Source: https://minescript.net/pyjinn Explains how to define classes in Python, including constructors (`__init__`), class methods, static methods, and how to instantiate classes and access their fields. ```python # Class definitions: class CLASS_NAME: def __init__(self, ...): self.X = VALUE self.Y = VALUE ... @classmethod def METHOD(CLASS, ...): ... @staticmethod def METHOD(...): ... # Construct instance of a class: OBJECT = CLASS_NAME(...) # Reference field of object: print(OBJECT.X) ``` -------------------------------- ### Execute lib_nbt from Command Line (Shell) Source: https://minescript.net/sdm_downloads/lib_nbt Demonstrates how to run the lib_nbt library directly from the command line or chat box. This is useful for quick parsing of NBT strings without writing a full Python script. It takes the NBT string as a command-line argument. ```shell \lib_nbt ``` -------------------------------- ### Python Dictionary Literals in Pyjinn Source: https://minescript.net/pyjinn Demonstrates the syntax for creating dictionary literals in Pyjinn, including key-value pairs. ```python # Dict literal: {K1: V1, K2: V2, ...} ``` -------------------------------- ### Get Items from Open Container (Python) Source: https://minescript.net/docs Retrieves a list of all items currently present in an open container GUI, such as a chest or furnace. Returns None if no container is open. ```python items = container_get_items() ``` -------------------------------- ### Configuration File Format Source: https://minescript.net/docs Describes the basic structure of the Minescript configuration file (config.txt). It explains how to define variables using the NAME=VALUE format, how to handle multi-line values using backslashes, and how comments and blank lines are ignored. ```plaintext # This is a comment line NAME=VALUE ANOTHER_VAR=some_value\ continued_on_next_line ``` -------------------------------- ### Get Block Type - Minescript Source: https://minescript.net/docs Retrieves the type of block at a specified 3D coordinate (x, y, z). Returns the block type as a string. An alias `get_block` is also available. ```python getblock(x: int, y: int, z: int) -> str ``` ```python get_block(x: int, y: int, z: int) -> str ``` -------------------------------- ### Python Indexing and Slicing in Pyjinn Source: https://minescript.net/pyjinn Explains the syntax for accessing elements and subsequences of sequences in Pyjinn using indexing and slicing notation. Includes support for negative indices and steps. ```python # Index/Slice operations: X[INDEX] X[FROM:] X[:TO] X[:] X[FROM:TO:STEP] X[:-1] # Negative indices are relative to the end of the sequence. ``` -------------------------------- ### Get Player Inventory Items Source: https://minescript.net/docs Retrieves all items present in the local player's inventory. The function returns a list of ItemStack objects. Asynchronous execution can be performed using .as_async(). ```python player_inventory() -> List[ItemStack] ``` -------------------------------- ### Minecraft Class Mapping (Java) Source: https://minescript.net/downloads Maps Minecraft class names to their obfuscated equivalents for use with Minescript. This is typically done once at the start of a script to ensure compatibility across different Minecraft versions. ```java mc_class_name = version_info().minecraft_class_name if mc_class_name == "net.minecraft.class_310": java_class_map.update({ "net.minecraft.client.Minecraft": "net.minecraft.class_310", }) java_member_map.update({ "getInstance": "method_1551", "getFps": "method_47599", }) Minecraft = JavaClass("net.minecraft.client.Minecraft") minecraft = Minecraft.getInstance() echo("fps:", minecraft.getFps()) ``` -------------------------------- ### Get Version Information - Minescript Source: https://minescript.net/docs Retrieves detailed version information for Minecraft, Minescript, the mod loader, launcher, operating system, and the main Minecraft class name. Returns a VersionInfo object. ```python version_info() -> VersionInfo ``` -------------------------------- ### Call Static and Non-Static Java Methods Source: https://minescript.net/pyjinn Demonstrates how to invoke static methods on Java classes and non-static methods on Java objects within Pyjinn. It shows the creation of a Java List and calling its `of` method, followed by calling the `size` method on the created object. ```Python List = JavaClass("java.util.List") java_list = List.of(1, 2, 3) print(java_list.size()) ``` -------------------------------- ### Draw Text Command Line Usage Source: https://minescript.net/sdm_downloads/draw_text-v1 Demonstrates the command-line interface for the draw_text script, showing how to specify text, position, color, and scale. ```bash draw_text TEXT [X Y [HEX_COLOR [SCALE]]] ``` ```bash draw_text "some text" draw_text "Hello, world!" 10 10 draw_text "green text" 360 10 0x00ff00 draw_text "hello yellow" 190 100 0xffff00 draw_text "big red" 200 100 0xff0000 32 ``` -------------------------------- ### Get Local Player Position Source: https://minescript.net/docs Retrieves the current position of the local player. The position is returned as a list of three floats representing the x, y, and z coordinates. Asynchronous execution can be achieved using .as_async(). ```python player_position() -> List[float] ``` -------------------------------- ### Performance Tuning Configuration Source: https://minescript.net/docs Details configuration options for tuning Minescript's performance, including `max_commands_per_cycle`, `command_cycle_deadline_usecs`, and `ticks_per_cycle`. It warns about potential instability with high command execution rates. ```plaintext max_commands_per_cycle=15 command_cycle_deadline_usecs=10000 ticks_per_cycle=1 ``` -------------------------------- ### Manage Callbacks with ManagedCallback (Python) Source: https://minescript.net/docs Introduces `ManagedCallback` as a wrapper for managing callbacks passed to Java APIs within Pyjinn. It provides a mechanism to register callbacks, for example, with `HudRenderCallback`, and allows for cancellation using `set_timeout`. ```python """Example: callback = ManagedCallback(on_hud_render) HudRenderCallback.EVENT.register(HudRenderCallback(callback)) # Cancel after 1 second (1000 milliseconds): set_timeout(callback.cancel, 1000)""" ``` -------------------------------- ### BlockPackParser Initialization and Data Parsing (Python) Source: https://minescript.net/sdm_downloads/lib_blockpack_parser Demonstrates how to initialize the BlockPackParser by parsing BlockPack data from different sources. It supports parsing directly from a BlockPack object, base64 encoded data, or raw binary data. ```Python from lib_blockpack_parser import BlockPackParser # Assuming blockpack is a BlockPack object parser_from_blockpack = BlockPackParser.parse_blockpack(blockpack) # Assuming base64_data is a string parser_from_base64 = BlockPackParser.parse_base64_data(base64_data) # Assuming binary_data is bytes parser_from_binary = BlockPackParser.parse_binary_data(binary_data) ``` -------------------------------- ### Usage of image_to_blocks command (Minescript) Source: https://minescript.net/sdm_downloads/image_to_blocks-v1 Demonstrates the command-line usage for the image_to_blocks plugin in Minescript. It shows how to specify coordinates, image files (PNG or JSON), optional depth files with scaling, and block orientation. The plugin interprets pixel data to place blocks in the game world. ```plaintext \image_to_blocks \ [ [dscale=]] \image_to_blocks \ [] [ [dscale=]] \ [] ``` -------------------------------- ### Get Next Event from Queue (Python) Source: https://minescript.net/docs Retrieves the next event from the event queue. It can optionally block until an event is available or time out after a specified duration. Raises queue.Empty if no event is found under non-blocking conditions or if the timeout expires. ```python event = event_queue.get(block=True, timeout=5.0) ``` -------------------------------- ### Get World Information - Minescript Source: https://minescript.net/docs Retrieves properties of the current world, including game ticks, day ticks, weather status, spawn point, hardcore mode, difficulty, name, and address. Returns a WorldInfo object. ```python world_info() -> WorldInfo ``` -------------------------------- ### Get Nearby Players - Minescript Source: https://minescript.net/docs Retrieves a list of nearby players with optional filtering and sorting. Supports NBT data and various criteria like UUID, name, distance, and limit. Returns a list of EntityData objects. ```python players(*, nbt: bool = False, uuid: str = None, name: str = None, position: Vector3f = None, offset: Vector3f = None, min_distance: float = None, max_distance: float = None, sort: str = None, limit: int = None) -> List[EntityData] ``` -------------------------------- ### Python Binary Operators in Pyjinn Source: https://minescript.net/pyjinn Lists the supported binary operators in Pyjinn, covering identity, comparison, and membership testing. ```python # Binary operators: X is Y X is not Y X == Y X < Y X <= Y X > Y X >= Y X != Y X in Y X not in Y ``` -------------------------------- ### Get Nearby Entities - Minescript Source: https://minescript.net/docs Retrieves a list of nearby entities with optional filtering and sorting. Supports NBT data and various criteria like UUID, name, type, distance, and limit. Returns a list of EntityData objects. ```python entities(*, nbt: bool = False, uuid: str = None, name: str = None, type: str = None, position: Vector3f = None, offset: Vector3f = None, min_distance: float = None, max_distance: float = None, sort: str = None, limit: int = None) -> List[EntityData] ``` -------------------------------- ### Command Path Configuration Source: https://minescript.net/docs Describes the `command_path` setting, which defines where Minescript looks for executable scripts. It explains how paths are interpreted (absolute vs. relative to the minescript directory) and how multiple paths are separated on different operating systems. ```plaintext # Windows: command_path=path1;path2 # Other OS: command_path=path1:path2 ``` -------------------------------- ### AI Chatbot Integration (Minescript) Source: https://minescript.net/downloads Integrates an AI chatbot that is aware of Minecraft surroundings. Requires Minescript v3.1+ and lib_nbt v1+. An OpenAI API key is needed for setup. Supports single prompts or interactive mode with pattern matching. ```minescript # Single response mode: \chatbot PROMPT # Interactive mode: \chatbot -i PATTERN [ignorecase] [name=NAME] # Example (single response): \chatbot "What am I looking at? And how long until sunrise?" # Example (interactive mode): \chatbot -i ".*\bbot,\s" ignorecase ``` -------------------------------- ### Create JavaList from Pyjinn List Source: https://minescript.net/pyjinn Shows how to convert a Pyjinn list into a Java List using the `JavaList` constructor. Changes made to the Pyjinn list are reflected in the Java List and vice versa due to shared internal representation. ```Python java_list = JavaList([1, 2, 3]) ``` -------------------------------- ### Get Player's Hand Items Source: https://minescript.net/docs Retrieves the items currently held in the local player's main and off-hands. The function returns a HandItems object containing ItemStack details for each hand. Asynchronous execution is available via .as_async(). ```python player_hand_items() -> HandItems ``` -------------------------------- ### Java Reflection Library for Minescript Source: https://minescript.net/sdm_categories/featured-scripts A library for using Java reflection from Python within Minescript, wrapping low-level Java API functions. Requires minescript v4.0. Includes example for handling obfuscated symbols in different Minecraft versions. ```python from minescript import (echo, version_info) from lib_java import ( JavaClass, java_class_map, java_member_map) # If using a version of Minecraft with obfuscated # symbols, populate these dictionaries with the # appropriate mappings, for example: mc_class_name = version_info().minecraft_class_name if mc_class_name == "net.minecraft.class_310": java_class_map.update({ "net.minecraft.client.Minecraft": "net.minecraft.class_310", }) java_member_map.update({ "getInstance": "method_1551", "getFps": "method_47599", }) Minecraft = JavaClass("net.minecraft.client.Minecraft") minecraft = Minecraft.getInstance() echo("fps:", minecraft.getFps()) ``` -------------------------------- ### Accessing Java Classes with JavaClass Source: https://minescript.net/pyjinn Demonstrates how to import and use Java classes within Pyjinn using the `JavaClass()` wrapper. It shows accessing static methods, class constructors, and obtaining the Java metaclass for primitive types and objects. ```python List = JavaClass("java.util.List") print(JavaClass("java.lang.String")) # prints: JavaClass("java.lang.String") print(type("This is a string")) # prints: JavaClass("java.lang.String") print("This is a string".getClass()) # prints Class: class java.lang.String print(type(42)) # prints: JavaClass("java.lang.Integer") print(type(42).MAX_VALUE) # prints equivalent of `Integer.MAX_VALUE`: 2147483647 print(type(42)(99)) # prints equivalent of `new Integer(99)`: 99 print(type(Integer)) # prints the metaclass Integer.class: class java.lang.Integer print(Integer.TYPE) # prints the int.class primitive type: int ``` -------------------------------- ### Manage Game Events with EventQueue Source: https://minescript.net/docs Provides a queue for managing game events, supporting context management for automatic listener unregistration. An example demonstrates registering a chat listener and processing incoming chat messages. This functionality is Python-only and was introduced in v4.0. ```python class EventQueue: def __init__(self): """Creates an event registration handler.""" pass def register_chat_listener(self): pass def get(self): pass # Example usage: # with EventQueue() as event_queue: # event_queue.register_chat_listener() # while True: # event = event_queue.get() # if event.type == EventType.CHAT and "knock knock" in event.message.lower(): # echo("Who's there?") ``` -------------------------------- ### show_chat_screen Source: https://minescript.net/docs Controls the visibility of the chat screen and can pre-fill the input prompt. ```APIDOC ## show_chat_screen ### Description Shows or hides the chat screen. When showing the screen, an optional prompt can be provided to pre-fill the chat input box. ### Method `show_chat_screen(show: bool, prompt: str = None) -> bool` ### Endpoint N/A (Client-side API) ### Parameters #### Path Parameters - **show** (bool) - Required - If `True`, show the chat screen; otherwise, hide it. - **prompt** (str) - Optional - If `show` is `True`, this string will be inserted into the chat input box upon showing the screen. ### Request Example ```python # Show the chat screen show_chat_screen(show=True) # Show the chat screen with a pre-filled prompt show_chat_screen(show=True, prompt="/say Hello!") # Hide the chat screen show_chat_screen(show=False) ``` ### Response #### Success Response - **success** (bool) - `True` if the chat screen was successfully shown (`show=True`) or hidden (`show=False`), `False` otherwise. #### Response Example ```json true ``` Since: v4.0 ``` -------------------------------- ### Get Block Types by Positions Source: https://minescript.net/docs Retrieves the block types at specified [x, y, z] coordinates. It accepts a list of positions and returns a list of corresponding block type strings. An alias `get_block_list` is available. Asynchronous execution can be achieved using `getblocklist.as_async(...)`. ```python def getblocklist(positions: List[List[int]]) -> List[str]: """Gets the types of block at the specified [x, y, z] positions.""" pass # Alias for getblocklist def get_block_list(positions: List[List[int]]) -> List[str]: """Alias for getblocklist(...).""" pass ``` -------------------------------- ### Manipulate Java Arrays (Python) Source: https://minescript.net/docs Provides functions for interacting with Java arrays from Python. This includes getting the length of an array, accessing elements by index, and creating new arrays. These functions require Java handles as input and return Python integers or Java handles. ```python def java_array_length(array: JavaHandle) -> int: """Returns length of Java array as Python integer.""" pass ``` ```python def java_array_index(array: JavaHandle, i: int) -> Union[JavaHandle, None]: """Gets indexed element of Java array handle.""" pass ``` ```python def java_new_array(element_type: JavaHandle, *elements: List[JavaHandle]) -> JavaHandle: """Creates a new Java array of the given element type with the given elements.""" pass ``` -------------------------------- ### Python List Comprehensions Source: https://minescript.net/pyjinn Demonstrates the use of list comprehensions for creating lists based on existing iterables. Supports basic transformations and filtering. ```python [X * 2 for X in range(5)] # evaluates to: [0, 2, 4, 6, 8] [C for C in "hello"] # evaluates to: ["h", "e", "l", "l", "o"] ``` -------------------------------- ### Embed Pyjinn Script in Python Source: https://minescript.net/pyjinn Embeds a Pyjinn script within a Python script using `java.eval_pyjinn_script`. This allows Python to access and manipulate global variables and functions defined in the Pyjinn script. It demonstrates setting and getting global variables and calling functions from the embedded script. ```python # pyjinn_in_python_example.py import java # or: import system.lib.java as java script = java.eval_pyjinn_script(r""" x = 42 def print_x(): print(f"x from Pyjinn = {x}") Minecraft = JavaClass("net.minecraft.client.Minecraft") def get_fps(units: str) -> str: return f"{Minecraft.getInstance().getFps()} {units}" """) get_fps = script.get("get_fps") print("fps:", get_fps("frames per second")) print(f"x from Python = {script.get('x')}") print_x = script.get("print_x") print_x() script.set("x", 99) print_x() ``` -------------------------------- ### Pyjinn Event Handling with Async/Await in Minescript Source: https://minescript.net/pyjinn Demonstrates how to handle events asynchronously in Pyjinn scripts within Minescript 5.0 using the EventLoop class. It shows how to await events, set timeouts, and process different event types. ```python async def handle_events(event_loop: EventLoop): while True: # Await an event for 3 seconds (omit param to wait indefinitely): event = await event_loop.event(timeout_seconds=3) if event is None: print("No events in last 3 seconds. Awaiting more events...") elif event.type == "mouse": if event.button == 1 and event.action == 0: print("Got right-click release. Quitting.") break else: print("Got mouse event.") event_loop = EventLoop() event_loop.add_listener("mouse") event_loop.run(handle_events) ``` -------------------------------- ### Set Class Methods Source: https://minescript.net/pyjinn Details the methods available for the 'set' class in Minescript.net. ```APIDOC ## Set Class Methods ### Description Provides a comprehensive list of methods and their functionalities for the `set` class. ### Methods - `__contains__(element) -> bool`: Checks if an element is present in the set. - `__len__() -> int`: Returns the number of elements in the set. - `__lt__(self, rhs) -> bool`: Checks if the set is less than another set. - `__le__(self, rhs) -> bool`: Checks if the set is less than or equal to another set. - `__gt__(self, rhs) -> bool`: Checks if the set is greater than another set. - `__ge__(self, rhs) -> bool`: Checks if the set is greater than or equal to another set. - `add(element)`: Adds an element to the set. - `clear()`: Removes all elements from the set. - `discard(element)`: Removes an element if it is present, otherwise does nothing. - `pop() -> Any`: Removes and returns an arbitrary element from the set. - `update(iterable)`: Adds elements from an iterable to the set. - `difference(iterable) -> set`: Returns a new set with elements in the set that are not in the iterable. - `difference_update(iterable)`: Removes elements found in the iterable from the set. - `intersection(iterable) -> set`: Returns a new set with elements common to the set and the iterable. - `intersection_update(iterable)`: Updates the set with elements common to it and the iterable. - `symmetric_difference(iterable) -> set`: Returns a new set with elements in either the set or the iterable but not both. - `symmetric_difference_update(iterable)`: Updates the set with the symmetric difference. - `union(iterable) -> set`: Returns a new set with elements from the set and all others. - `copy() -> set`: Returns a shallow copy of the set. - `isdisjoint(iterable) -> bool`: Checks if the set has no elements in common with the iterable. - `issubset(iterable) -> bool`: Checks if all elements of the set are in the iterable. - `issuperset(iterable) -> bool`: Checks if all elements of the iterable are in the set. ``` -------------------------------- ### Python Lambda Expressions Source: https://minescript.net/pyjinn Illustrates the creation and usage of anonymous lambda functions in Python. Supports functions with zero, one, or multiple arguments. ```python lambda: print("no args") lambda X: print("1 arg:", X) lambda X, Y: print("2 args:", X, Y) ```