Minecraft Script API Documentation

website·Indexed 29 days ago

https://sapi-doc.pling.top

A comprehensive guide to developing for Minecraft using the @minecraft/server Script API. The documentation covers JavaScript fundamentals, environment setup, script lifecycles, and core API concepts including the world object, player management, and the component system for managing entity attributes and survival states.

Tokens
49.1K
Snippets
240
Records
273
Agent score
50%

What's inside Minecraft Script API

  1. Overview of the world object

    The world object is a global singleton in the @minecraft/server API that represents the currently running Minecraft world. It acts as the central entry point for accessing players, entities, blocks, dimensions, events, and game rules.
    import { world } from "@minecraft/server";
  2. Introduction to Minecraft Script API (SAPI)

    The Script API (SAPI) allows developers to control Minecraft game logic using JavaScript. It is designed to overcome the limitations of command blocks, such as inflexible variable handling, difficult maintenance of long logic chains, and performance degradation caused by excessive command block usage. SAPI enables the use of variables, event listeners, and custom functions to implement complex gameplay mechanics.
  3. Track player location and movement state

    The Player object provides real-time data about the player's position and physical state. location returns an object with x, y, and z coordinates. Various boolean properties like isSneaking, isFlying, isOnGround, isInWater, isInLava, isSleeping, isSwimming, isCrawling, and isFalling can be used to trigger game logic based on the player's environment.
    import { world } from "@minecraft/server";
    
    world.afterEvents.playerSpawn.subscribe(({ player }) => {
        // Get coordinates
        const { x, y, z } = player.location;
        
        // Check states
        if (player.isSneaking) player.sendMessage("You are sneaking!");
        if (player.isInWater) console.log("Player is in water");
        if (player.isFlying) console.log("Player is flying");
    });
  4. Understand the Minecraft Component System

    The Minecraft Script API uses a Component System rather than a traditional class-based inheritance model to manage entity attributes. Instead of every entity having a fixed set of properties, entities 'mount' specific components (capabilities). For example, while players, zombies, and minecarts all have a health component, only players have an inventory component. This allows for flexible, modular attribute management across hundreds of different entity types.
  5. Understand the Minecraft script lifecycle stages

    The script lifecycle in Minecraft (version 2.0.0+) consists of three primary stages. Understanding these stages is critical to avoid errors caused by attempting to access world state before it is initialized.

    1. Module Top-Level Execution: Occurs when the behavior pack loads the entry file (e.g., main.js). Only code outside of functions or event callbacks is executed immediately.
    2. worldLoad Event: Triggered after the script is loaded and world data is ready, but before players join. This is the earliest safe point for world-level initialization.
    3. Player Joining and Gameplay: The event-driven phase where scripts respond to game events (e.g., playerSpawn) or run periodic tasks.
  6. Understand the Minecraft Coordinate System

    Minecraft uses a 3D Cartesian coordinate system where positions are represented by a Vector3 object containing x (East/West), y (Height), and z (North/South) properties.
    import { world } from "@minecraft/server";
    
    world.afterEvents.playerSpawn.subscribe(({ player }) => {
        const location = player.location; // Returns a Vector3 {x, y, z}
        console.log(`Coordinates: (${location.x}, ${location.y}, ${location.z})`);
    });
  7. Manage world game rules via world.gameRules

    The world.gameRules object allows reading and modifying fundamental world behaviors. Changes affect the entire world and all players. Caution is advised with randomTickSpeed, as excessively high values can cause severe lag.
    import { world } from "@minecraft/server";
    
    // Read game rules
    const isPvpEnabled = world.gameRules.pvp;
    const keepInventory = world.gameRules.keepInventory;
    
    // Modify game rules
    world.gameRules.keepInventory = true;    // Enable keep inventory
    world.gameRules.doDaylightCycle = false; // Disable day/night cycle
    world.gameRules.pvp = false;             // Disable PvP
  8. Manage data with JavaScript Objects and Arrays

    JavaScript objects and arrays are fundamental for storing and manipulating data in Minecraft scripts. Key operations include using dot notation and bracket notation for object properties, managing nested objects, and using the delete operator. For arrays, common operations include index-based access, length checking, and modifying the array via push, pop, shift, and unshift.
  9. Implement a modular scoring and event system

    This example demonstrates how to split a script into a data module (scores.js), a utility module (welcome.js), an event coordinator (events.js), and an entry point (main.js).
    // scripts/scores.js
    const playerScores = new Map();
    export function getScore(name) { return playerScores.get(name) ?? 0; }
    export function addScore(name, points) {
        const newScore = getScore(name) + points;
        playerScores.set(name, newScore);
        return newScore;
    }
    
    // scripts/welcome.js
    import { getScore } from "./scores.js";
    export function buildWelcomeMessage(name, isNewPlayer) {
        return isNewPlayer ? `Welcome ${name}!` : `Welcome back ${name}! Score: ${getScore(name)}`;
    }
    
    // scripts/events.js
    import { world, system } from "@minecraft/server";
    import { addScore } from "./scores.js";
    import { buildWelcomeMessage } from "./welcome.js";
    
    export function registerEvents() {
        world.afterEvents.playerSpawn.subscribe(({ player, initialSpawn }) => {
            if (!initialSpawn) return;
            player.sendMessage(buildWelcomeMessage(player.name, true));
        });
        system.runInterval(() => {
            for (const player of world.getPlayers()) { addScore(player.name, 1); }
        }, 20);
    }
    
    // scripts/main.js
    import { registerEvents } from "./events.js";
    registerEvents();
  10. Use while loops for conditional repetition

    The while loop repeatedly executes a block of code as long as a specified condition remains true. It is used when the number of iterations is not known in advance.

    Warning: Ensure the loop body contains an operation that eventually makes the condition false to avoid infinite loops, which can cause applications (or the Minecraft game engine) to crash.

    let countdown = 5;
    
    while (countdown > 0) {
        console.log(`Server will restart in ${countdown} seconds...`);
        countdown--; // Decrement to eventually break the loop
    }
    
    console.log("Server is restarting!");
  11. Work with Strings and Template Literals

    Strings are sequences of characters wrapped in single quotes ('), double quotes ("), or backticks (`). While the + operator can concatenate strings, Template Literals (using backticks) are recommended for embedding variables and expressions directly into strings using the ${} syntax.
    let playerName = "Steve";
    
    // Basic concatenation
    let greeting = "Hello, " + playerName + "!";
    
    // Template Literal (Recommended)
    let playerHealth = 20;
    let statusMsg = `Player ${playerName} current health is ${playerHealth} points`;
    
    // Expressions inside template literals
    let price = 5;
    let amount = 3;
    let receipt = `You bought ${amount} items for a total of ${price * amount} emeralds`;
  12. Manage ordered lists with Arrays

    Arrays store ordered elements identified by a zero-based index. They are defined using square brackets []. Accessing an index that does not exist returns undefined rather than throwing an error. The .length property provides the total number of elements; the last element is always at index length - 1.
    const playerNames = ["Steve", "Alex", "Herobrine", "Notch"];
    
    // Access by index (0-based)
    console.log(playerNames[0]); // Steve
    console.log(playerNames[1]); // Alex
    
    // Get array length
    console.log(playerNames.length); // 4
    
    // Access out-of-bounds
    console.log(playerNames[10]); // undefined