Play Strawberry Docs
Scripts

Inventory menus

Build an inventory menu, open it for a player and handle its clicks safely.

Build and open a menu

gui::Gui::new(Screen, title) creates a menu; set_item(slot, item), get_item, clear_items and get_inventory work on its slots. For a menu of buttons, turn off taking and putting items with set_allow_grab_items(false) and set_allow_put_items(false). player.open_gui(menu) opens it.

rust
fn open_menu(player: &Player) {
    let menu = Gui::new(Screen::Generic9x3, TextComponent::text("Help menu"));
    let icon = ItemStack::new("minecraft:golden_apple", 1);
    icon.set_custom_name(Some(TextComponent::text("Heal me")));
    menu.set_item(HEAL_SLOT as u32, icon);
    // A decorative menu: nobody takes items out or puts items in.
    menu.set_allow_grab_items(false);
    menu.set_allow_put_items(false);

    // Remember who has the menu open before opening it: the click event names the
    // player and the slot, not the menu.
    open_set(|open| open.insert(player.get_id().to_string()));
    player.open_gui(menu);
}

Handle clicks

InventoryClickEvent carries the player, the window type, the click type, the slot and raw slot, the clicked item and the cursor. It does not say which script's menu was clicked, so remember who has your menu open (by player UUID) and forget it on InventoryCloseEvent and when the player leaves.

rust
struct MenuClick;

impl EventHandler<InventoryClickEvent> for MenuClick {
    fn handle(&self, _server: Server, mut event: InventoryClickEventData) -> InventoryClickEventData {
        let uuid = event.player.get_id().to_string();
        if !open_set(|open| open.contains(&uuid)) {
            return event; // not our menu
        }
        event.cancelled = true;
        if event.slot == HEAL_SLOT {
            event.player.send_system_message(TextComponent::text("You feel better."), false);
        }
        event
    }
}

/// Forgets the menu when it closes or the player leaves.
struct MenuClose;

impl EventHandler<InventoryCloseEvent> for MenuClose {
    fn handle(&self, _server: Server, event: InventoryCloseEventData) -> InventoryCloseEventData {
        let uuid = event.player.get_id().to_string();
        open_set(|open| open.remove(&uuid));
        event
    }
}

struct MenuLeave;

impl EventHandler<PlayerLeaveEvent> for MenuLeave {
    fn handle(&self, _server: Server, event: PlayerLeaveEventData) -> PlayerLeaveEventData {
        let uuid = event.player.get_id().to_string();
        open_set(|open| open.remove(&uuid));
        event
    }
}
rust
context.register_event_handler_with_options::<InventoryClickEvent, _>(
    MenuClick,
    blocking(HandlerPriority::Normal),
)?;
context.register_event_handler_with_options::<InventoryCloseEvent, _>(
    MenuClose,
    blocking(HandlerPriority::Monitor),
)?;
context.register_event_handler_with_options::<PlayerLeaveEvent, _>(
    MenuLeave,
    blocking(HandlerPriority::Monitor),
)?;

Never identify your menu by its title or screen type alone: another script can open a menu with the same title.

The player's inventory under a menu

A menu shows the player's own inventory working under it, as on Paper: the player can move items in their own inventory and shift-click between the two parts. A menu that forbids taking or putting items still refuses every move into or out of its own slots.

  • raw_slot below the menu's size is a click on the menu; from the menu's size up it is a click on the player's inventory.
  • Each window type has the slot count of Paper's InventoryType: a 9x1 menu 9, a furnace 3, an anvil 3, a crafting table 10.

Draw your own slots under a menu

A menu can show nothing, or your own pictures and buttons, in the slots under the window where the player's inventory is, so the menu can be one picture over the whole window.

  • Set it with gui.set_player_part(part) before open_gui, or with player.set_open_window_player_part(part, showing) while the window is open.
  • Slot i of that part is the window's slot size + i. The click event reports clicks on it, and the server refuses any real move.
  • The player's real items are never touched and show again when the window closes. Bedrock players see the same part.

Change the title of an open window

player.set_open_window_title(title, showing) changes the title of the window the player has open (Paper's InventoryView#setTitle). It stays the same window: its items and the item on the cursor stay, and neither the close nor the open event fires. Use it for a menu that shows live values in its title, such as a balance, instead of opening a new window over the old one.

open_gui takes your Gui, so keep gui.get_inventory() from before you open it and pass it as showing: the title then changes only while that window is still the one open. The call returns false, changing nothing, when the player has no window open or another one.

Bedrock players

  • A window your script opens is shown to a Bedrock player too, with its title and all its rows.
  • A window of 1, 2, 4 or 5 rows is drawn as a chest of 3 or 6 rows. The extra slots hold a barrier named "Unusable inventory space" and take nothing.
  • With set_open_window_title their window closes and opens again under the new title with the same items, and no close or open event fires.
  • A menu that closes one window and opens the next right away (turning a page) works.

The window a player has open

These Player methods answer for the window open at the moment of the call, like Paper's getOpenInventory():

  • open_window_type(): OwnInventory (the player's own inventory), Screen(..), Mount or Other.
  • open_window_slot_count() and open_window_top_slot_count(): the slots of the whole window and of its top part.
  • open_window_slot(raw): where a raw slot (the click events' raw_slot) lies, in the window or in the player's inventory, with its number there; none outside the window. A slot of the player's inventory has the number get_inventory_item takes (hotbar 0-8, main 9-35, boots to helmet 36-39, off hand 40).
  • open_window_item(raw) and set_open_window_item(raw, item): read and replace the item in a raw slot. Writing returns false outside the window and for a slot that keeps its own contents. Writing a crafting result shows your item until the grid changes.
  • cursor_item() and set_cursor_item(item): read and replace the item on the cursor.

Drags and prepared results

During a handler, these functions answer for the inventory event being handled, as on Paper:

  • InventoryDragEvent: events::drag_slots() lists the slots the drag fills, each with the stack it will hold; events::drag_old_cursor() and events::drag_cursor() give the cursor before and after; events::drag_type() is "even", "single" or "clone".
  • The prepare events (crafting, anvil, grindstone, smithing): events::prepared_result() is the result the window shows, and events::set_prepared_result(item) replaces it. The window shows your result until its contents change.
  • events::event_recipe() names the recipe a crafting result comes from.
  • The anvil's prepare event also fires after a rename, with the new name and the real cost. Bedrock players can rename items in an anvil too, with the same 50-character limit and cost as Java players, and the prepare event carries the name they typed.
  • When your script changes the items a crafting grid, anvil, grindstone, smithing table, stonecutter, loom, cartography table or trade is made of, the result follows at once, as on Paper: the old result cannot be taken, and the window shows the result of the new items.

The prepare events (PrepareItemCraftEvent, PrepareAnvilEvent, PrepareGrindstoneEvent, PrepareSmithingEvent and PrepareInventoryResultEvent) also fire when a window's result changes without a click, for example when a script writes into the inputs of an open window. The server asks them a moment after the write, before the player can take the result, and what the last handler leaves is what the window shows. A write that leaves the same result asks nothing.

One inventory for several players

Make the inventory with a Gui, keep its handle and call player.open_inventory for each viewer (Paper's openInventory(Inventory)).

  • All windows share the items, and a change reaches every viewer.
  • Two viewers clicking one slot at the same time never both take the item.
  • Closing one window leaves the others open.
  • InventoryCloseEvent::inventory() says which inventory closed, and inventory.get_id() tells inventories apart.

player.set_open_window_item waits briefly for other players who have the same chest or container open to finish their click before it writes the slot, so an item is never lost or doubled. If the windows stay busy, the call returns false and changes nothing.

Trading windows

merchant::open_merchant(&player, title, offers) opens your own trading window with up to 64 offers and returns the window's id (Paper's Bukkit.createMerchant and Player#openMerchant). Each MerchantOffer has vanilla's fields: first_cost, an optional second_cost, result, uses, max_uses, reward_experience, villager_experience, price_multiplier, demand and special_price. The window shows no level and no experience bar, and an offer that reached max_uses is out of stock.

  • The server carries out each trade: it checks the costs in the payment slots and moves the items. The client decides nothing.
  • Before any item moves, the extension event MERCHANT_TRADE ("merchant-trade") asks the scripts (Paper's PlayerPurchaseEvent). event.merchant_trade() gives the window id and the offer_index. Register it blocking and cancel it to refuse the trade. A shift-click repeats the trade as in vanilla, asking each time and stopping at the first refusal. Villagers' and wandering traders' own trades do not fire it.
  • merchant::offers(&entity) reads the offers of a villager or a wandering trader and merchant::set_offers(&entity, offers) replaces them (Paper's Merchant#getRecipes and setRecipes). Replacing is refused while a player is trading with it.
  • A refusal is a MerchantError: TooManyOffers, InvalidOffer (an unknown item, an empty or oversized stack, a number out of range), NotAMerchant, Trading or NotOpened (the player left, or a script cancelled the open).

Loot and trades

  • LootGenerateEvent fires when a container's loot table fills it, the first time anything looks into it: a chest, trapped chest, barrel, shulker box, dispenser, dropper, hopper, crafter or decorated pot with a loot table, and a minecart with a chest or a hopper. Cancelled, the container stays empty.
  • In its handler, events::loot_items() gives the stacks the container gets and events::set_loot_items(list) replaces them (Paper's getLoot() and setLoot()). The server places them the way vanilla places loot, in free slots at random. The call returns false and changes nothing for more stacks than events::loot_slots(), or a stack that is no known item or holds more than its stack size. events::loot_origin() is where the loot is made and events::loot_entity() the entity id of the player who opened the container, none when a hopper, a break or an explosion filled it. The event type has them as LootGenerateEvent::loot(), set_loot(), slots(), origin() and entity().
  • VillagerAcquireTradeEvent fires for each offer a villager gains on a new level and for each offer a wandering trader brings. events::acquired_offer() reads the offer and events::set_acquired_offer(offer) replaces it (Paper's getRecipe() and setRecipe()); cancel the event to drop the offer.

Before you give or take items

The grab and put flags and a cancelled click are not a transaction. Check the slot contents, the player and your own state again before you give or charge anything, and make one-off rewards safe against repeated clicks.

On this page