#Script API General

1 messages Β· Page 54 of 1

thorn flicker
#

read it.

hybrid island
#
const durabilityComp = item.getComponent("minecraft:durability");
durabilityComp.damage = 0; // Fully repair the item

this is what i am trying to do

#

oh so how to change it to write mode?

#

this is line 42
durabilityComp.damage = 0;

hybrid island
granite badger
#

I'm so tempted to add an article about readonly and early execution mode on my docs

hybrid island
#

you should add

granite badger
#

is that my docs or someone elses

hybrid island
#

ur docs

#

im still cofused xd

sterile epoch
#

r u setting it back 2 the inventory after u do the damage

hybrid island
#

wdym

sterile epoch
#

i think like

granite badger
#
const item = container.getItem() // gets the item
const component = item.getComponent(...) // get component
container.setItem(slot, item) // set it back

You have to set the item back

sterile epoch
#

yeah

hybrid island
#

ohh

sterile epoch
#

cuz I think it just makes a copied edited version of the item and doesn't actually edit the original

hybrid island
#

do i do slot or the item

#

bruh

#

im stupid

sterile epoch
#

that returns a copy of the itemStack

#

so then you edit that and set it back

hybrid island
#
    const inventory = player.getComponent("minecraft:inventory").container;
    const itemx = inventory.getSlot(player.selectedSlotIndex);
    const item = itemx.getItem()
                durabilityComp.damage = 0; // Fully repair the item
                inventory.setItem(itemx, item)
``` this is what i did
#

not working

sterile epoch
#

where the getComponent

granite badger
#

inventory.setItem(player.selectedSlotIndex, item)

hybrid island
#

oh ok

#

thanks!!

sterile epoch
#

what happens if u do inventory.addItem() but the inventory is full?

hybrid island
#

it erros?

#

i think so

sterile epoch
#

can u try it for me and see I cba

#

I'm kidding btw

hybrid island
#

i would but im playing tho

sterile epoch
#

fair

hybrid island
#

ya if i was playing alone then i would creeate new world and test but

sterile epoch
#

is it a realm or smthn?

hybrid island
#

nah normal

#

world

#

im the owner

#

im dying with reading chat

distant tulip
#

let say you have half a stack empty, and you tried to add a stack of the same item.
the function will add half a stack and return the rest

#

so you will ideally do
const item = container.addItem(...)
if(item) dimension.spawnItem(item, loc)

bright dove
#

Is there an event listener to listen to gamerule change ?

distant tulip
dim tusk
distant tulip
thorn flicker
distant tulip
#

i see someone changed his Docs preferences

thorn flicker
thorn flicker
#

just create an if statement

distant tulip
#

thought you are using jaylys

bright dove
#

Ah i see

thorn flicker
untold magnet
#

d u have the latest beta version? so i can test it out on multiplayer.

distant tulip
#

give me a sec to update

chilly fractal
#

E

dim tusk
#
const inventory = Block.getComponent('inventory').container;
const item = inventory.getItem(2)```

Doesn't work?
chilly fractal
#

I dont know how to possibly come up with a master plan to detect when someone falls

chilly fractal
#

Unless the block is unloaded

distant tulip
chilly fractal
untold magnet
dim tusk
untold magnet
chilly fractal
#

I have absolutely no idea what to do because .isJumping flags even if they are holding jump in mid air

#

So then I'd kill the player if i assume they landed

#

And .getVelocity() is very helpful but i can't really decide how to use it

dim tusk
chilly fractal
#

.isOnGround doesn't flag

#

If you hold the jump button

untold magnet
#

something went wrong, why is this so freaking HUGE

dim tusk
chilly fractal
chilly fractal
#

Ima test out later again

#

I kinda revamped everything

#

And split the functionality upon 2 addons

untold magnet
untold magnet
chilly fractal
#

Reopen mc?

untold magnet
#

this onejs system.runInterval(() => { for (const player of world.getAllPlayers()) { const itemStack = player.getComponent('equippable')?.getEquipment('Head'); if (itemStack?.typeId === 'exe_heads:fisherman_hat') fisherman_hat = true; else fisherman_hat = false; } })

#

it will set that 'fisherman_hat' into true, when one of the players equips it,
and this works only when one of those players is equipped it if (fisherman_hat === true) if (Math.random() <= 0.1) dimension.runCommandAsync(loot spawn ${x} ${y} ${z} loot "gameplay/fishing") so it will work for anyone who dont equip that fisherman hat

#

so, the system has to be changed.

#

specifically this:

world.beforeEvents.entityRemove.subscribe((event) => {
  const hook = event.removedEntity;
    if (hook.typeId === "minecraft:fishing_hook") {
        const loc = hook.location;
        const date = Date.now()
        const dimension = hook.dimension
        const { x, y, z } = hook.location
        const id = system.runInterval(() => {
          const id2 = system.runTimeout(()=>system.clearRun(id),20)

          const items = dimension.getEntities({type:"minecraft:item", location: loc, maxDistance: 2})
          for(const item of items){
            if(date - (itemSpawnDate.get(item)??0) < 100){
              if (fisherman_hat === true) if (Math.random() <= 0.1) dimension.runCommandAsync(`loot spawn ${x} ${y} ${z} loot "gameplay/fishing"`)
              system.clearRun(id)
              system.clearRun(id2)
              return
            }
          }
        });
    }
})```@distant tulip this system should detect the owner's equipment, drop the new loot tables when the owner is equipping a fisherman hat.
dim tusk
# chilly fractal Yeah idk i guess my addon isn't very optimized or smth
system.runInterval(() => {
    const playerStates = JSON.parse(world.getDynamicProperty('playerStates') || '{}');
    
    for (const player of world.getPlayers()) {
        const movementPermission = player.inputPermissions.movementEnabled;

        if (!playerStates[player.id]) playerStates[player.id] = { isOnGround: true };

        if (movementPermission) {
            if (player.isJumping && playerStates[player.id].isOnGround) {
                console.error('Jumped');
                playerStates[player.id].isOnGround = false;
            }
            if (player.isOnGround && !playerStates[player.id].isOnGround) playerStates[player.id].isOnGround = true;
        }
    }
});```
#

I have this, I'm too lazy to fix some parts

untold magnet
distant tulip
#

@untold magnet

import {system, world} from "@minecraft/server";

const hookOwners = new WeakMap();

world.afterEvents.entitySpawn.subscribe((event) => {
    const entity = event.entity;
    if (entity.typeId !== "minecraft:fishing_hook") return;

    const dimension = entity.dimension;
    const hRot = entity.getRotation();
    const nearbyPlayers = dimension.getEntities({ location: entity.location, maxDistance: 5, type: "minecraft:player" });
    
    for (const player of nearbyPlayers) {
      const pRot = player.getRotation();
        if (Math.abs(pRot.x + hRot.x)<2 && Math.abs(pRot.y + hRot.y) < 1) {
            hookOwners.set(entity, player);
            console.warn(player.nameTag);
            
            
            break;
        }
    }
});

world.beforeEvents.entityRemove.subscribe((event) => {
    const hook = event.removedEntity;
    if (hook.typeId !== "minecraft:fishing_hook") return;

    const owner = hookOwners.get(hook);
    hookOwners.delete(hook);
    
    if (!owner) return;

    const { x, y, z } = hook.location;
    const hasHat = owner.getComponent("equippable")?.getEquipment("Head")?.typeId === "exe_heads:fisherman_hat"

    system.run(()=>{
      let found = false
      const itemSpawnHandler = world.afterEvents.entitySpawn.subscribe((spawnEvent) => {
        const entity = spawnEvent.entity;
        if (entity.typeId !== "minecraft:item") return;
        const distance = Math.hypot(entity.location.x - x, entity.location.y - y, entity.location.z - z);
        if (distance > 3 && !found) return;
        found = true
        if (hasHat) owner.runCommand(`loot spawn ${x} ${y} ${z} loot "gameplay/fishing"`);
        world.afterEvents.entitySpawn.unsubscribe(itemSpawnHandler);
      });
      system.runTimeout(() => {
        world.afterEvents.entitySpawn.unsubscribe(itemSpawnHandler);
      },20)
    })
});
untold magnet
#

that looks sick

#

will it drop the extra loot 100%?

#

lets test it out and see.

untold magnet
distant tulip
#

but maybe...

distant tulip
untold magnet
wintry bane
#

How do I use getViewDirection() and getHeadLocation() to convert tp @s ^2 ^5 ^-9 dynamically?

distant tulip
# untold magnet same log

const distance = entity.isValid()?Math.hypot(entity.location.x - x, entity.location.y - y, entity.location.z - z):0;

distant tulip
prisma shard
#

wow minato be helping out everyone

woven loom
#

that's not how it qorks

#

you need to get all the local axis

distant tulip
woven loom
#

view direction is z axis if u flip x and y comp of z axis and make one of the comp negative it gives u x axis then z axis cross product x axis gives u y axis

after that u can do this for ^vx ^vy ^vz

location += xaxis * vx + yaxis * vy + zaxis * vz

#

i created a non cross product method some time ago

distant tulip
scarlet sable
#

is there a way to detect player input?

#

like right clicking

#

a stable way of course

subtle cove
#

itemUse with item

#

no event triggers for now when no item on hand

scarlet sable
#

damn

#

what about player interact with block?

#

can it be used with any block?

subtle cove
#

as long as the block is tangible, yes...

scarlet sable
#

tangible?

subtle cove
#

like excluding water/lava

scarlet sable
#

damn xD

#

the exact block I need

scarlet sable
subtle cove
#

u can use this one if u like, just to see what events triggers simultaneously

scarlet sable
#

this is like an even detector?

subtle cove
#

sorta, ye

scarlet sable
#

ye nothing get's detected

#

mhm

#

I wonder if some found a way around it

#

how do I know the block I'm looking at?

valid ice
#

getBlockFromViewDirection

subtle cove
#

system.runInterval(()=>{
    for (const p of world.getAllPlayers()) {
        console.warn(p.getBlockFromViewDirection()?.block?.typeId);
    }
})
scarlet sable
#

ty bao_ext_toldyouso

#

bruh

valid ice
#

Doesn't detect water

scarlet sable
#

what does?

valid ice
#

Gotta use the parameters for the function

scarlet sable
#

wdym?

#

includeLiquidBlocks?: boolean

#

this one?

scarlet sable
#

ah I see

valid ice
scarlet sable
#

why does mc do that?

subtle cove
#

from player's eyes to where ur lookin at, plus includeLiquid, then itll get the 1st block

scarlet sable
#

,

#

?*

#
for(const player of world.getAllPlayers()){
 world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
  const {player , block} = event;
  if(!player || !block) return;
  let blocktype = player.getBlockFromViewDirection({includeLiquidBlocks : true}).block.typeId;
if (blocktype === "minecraft:water"){
  player.sendMessage("water");
}

 })
}
subtle cove
#

u touched a block not a water

scarlet sable
#

wdym?

#

I wonna detect water

subtle cove
#

when...

scarlet sable
#

my problem is the spam that happens

subtle cove
#

oh

scarlet sable
#

I want 1 detction

#

not 10

subtle cove
#
if (!event.isFirstEvent || !player || !block) return;
scarlet sable
#

oh firstEvent

subtle cove
#

ye, they just added that few updates ago

scarlet sable
#

yep ty it's working bao_ext_toldyouso

scarlet sable
weary umbra
scarlet sable
#

btw what's Ts?

valid ice
#

typescript

scarlet sable
distant tulip
#

typing scripts bao_foxxo_smug

valid ice
#

Like javascript, but with stricter rules on what you can type- stops stupid mistakes and helps guide the creator better

scarlet sable
#

mhm

#

you recommend it?

valid ice
#

Very much so

#

It's pretty easy to set up and allows for a lot better experience writing code, imo

deep arrow
scarlet sable
#

mhm

#

is it possible to mix it with js?

#

I have at least 100 lines so far and I'm not sure I have the time to rewrite them

valid ice
#

All JavaScript is valid typescript (you just get warnings for type mismatches)

scarlet sable
#

Mhm ok then

#

I'll try at least lol

dawn zealot
#

is there a block interact event?

wary edge
dawn zealot
wary edge
#

Read the docs.

dawn zealot
#

jesus why do i even ask you

wary edge
scarlet sable
#

I just was talking about it

dawn zealot
#

i found another way

simple zodiac
scarlet sable
#

wtf

#

the script randomly stopped working

#

no errors either

#
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
   const {player , block} = event;
   if(!event.isFirstEvent ||!player || !block) return;
   let blocktype = player.getBlockFromViewDirection({includeLiquidBlocks : true}).block.typeId;
   let thirst = JSON.parse(player.getDynamicProperty('thirst') || '{}')
 if (blocktype === "minecraft:water"){
   thirst.hydration = Math.min(100, thirst.hydration +40);
 }
 player.setDynamicProperty('thirst', JSON.stringify(thirst));
  })```
dawn zealot
#

so i have buttons here, but how can i make them only appear if a certain condition is met? using @valid ice's chestforms also

distant tulip
dim tusk
dawn zealot
scarlet sable
#

It worked like 6 times

#

But suddenly broke

dim tusk
scarlet sable
#

I want it to work with anything tho

dim tusk
#

tho I'm not 100% sure

scarlet sable
#

It actually worked

#

I just don't know why it's broken

dim tusk
scarlet sable
dim tusk
#

try without block behind

scarlet sable
#

No it won't work lmao

#

That's the whole idea

dim tusk
scarlet sable
#

I'm using a detection of interacting with the block behind the water and detecting that the water is infront of you

dim tusk
#

water I mean

scarlet sable
#

Ye you're right

scarlet sable
#

Why is it broken now tho

dim tusk
#
world.beforeEvents.playerInteractWithBlock.subscribe(ev => {
   const { block, player, itemStack } = ev;
   const raycast = player.getBlockFromViewDirection({ includeLiquidBlocks: true })?.block;
   console.error(raycast?.typeId);
});```
scarlet sable
#

Ain't that the same?

dim tusk
scarlet sable
#

Ok gemme a min

dim tusk
#

I missed an s in the includeLiquidBlock

scarlet sable
#

what's your point? lol

#

nvm my script is working lol

fallow rivet
#

Why are you doing this?

scarlet sable
#

I think there's a problem with the dynamic property

scarlet sable
fallow rivet
scarlet sable
#

it's kinda obvious lol

#

making a thirst system

#

I thought it would be could to have the ability to directly drink water

fallow rivet
#

Hmm

scarlet sable
#

hmm what?

#

sus

fallow rivet
#

It looks nice

scarlet sable
#

ty

fallow rivet
#

πŸ˜‰

#

I love looking at what people do with scripts.

scarlet sable
#

ahh I see

#

fair

distant gulch
scarlet sable
distant gulch
#

Little "turrets" with mobs on it

#

Ice Bear is* like a freeze-tower

scarlet sable
#

that's interesting

scarlet sable
distant gulch
#

"ss" ?

distant gulch
subtle cove
#

ScreenShot...

distant gulch
#

ohhh

distant gulch
#

I need a good sytem for the Enemies path system...

#

Anyone good ideas?

timber frigate
#

Hello guys. When I add "minecraft/server-ui" module, it gives me that error: [Scripting][verbose]-Plugin [BEHAVIOR PACK NAME] - promoted [@minecraft/server] from [1.3.0] to [1.16.0] requested by [@minecraft/server-ui - 1.3.0].

scarlet sable
distant gulch
#

Like code, not visuals

scarlet sable
#

mhm

#

no idea what you mean bao_bee_happy

distant gulch
#

The Calculation of it

#

Image you have 1000 Enemies, somehow it needs to be perfomant

#

so i need a good system

#

Every enemy follows a path, so they need to walk to the current path-point, and this needs to be perfomant

scarlet sable
#

neither can my pc lmao

distant gulch
#

yep..

#

i need to model my own entity so it will be more perfomant

drowsy scaffold
#

t

#

YES i finally got space

dawn zealot
#

anyone know how i would apply knockback to entities?

drowsy scaffold
dawn zealot
#

well nvm now it wants to work lmao

#

ty

drowsy scaffold
#

ope okay

#

yep

#

the way this game stores cooldowns for damage is SO weird

drowsy scaffold
#

like when doing damage to something

dawn zealot
#

o

#

i have my own damage system

drowsy scaffold
#

same

dawn zealot
drowsy scaffold
#

I was in the proccess of making one without using scoreboards or anything like that via API calls and turns out damage is stored per-value, meaning Math.random() damage on a entityHitEntity event gives no hit cooldown time lmao

#

it's so stupid

dawn zealot
#

my system is just hella scalable

#

good for my rpg style stuff

drowsy scaffold
#

someone wanted to be able to multiply/divide damage as needed but didn't wanna do scoreboard / rpg style and I was messing with that and discovered it

dawn zealot
#

yeah my code is a mess lmao

#

for example 😭

#

that passive mode shit idek how it works i just made it

remote oyster
# dawn zealot

You should try to stick with let and const when declaring variables and avoid using var. It's basically legacy code and mostly kept around for backward compatibility.

dawn zealot
#

otherwise it errors

remote oyster
# dawn zealot otherwise it errors

Because you have to declare the variable before the statement with let then use the variable to define it so it's accessible outside the if statement.

let example = false;
if (player.hasTag("idk") {
    example = true;
}
console.log(example);
cold grove
#

why

#

const hasThisTag = player.hasTag('thisTag')

dawn zealot
remote oyster
misty pivot
#

what's a job?

#

i mean like in system

#

system.runJob

drowsy scaffold
#

it's a part of generator functions, used most commonly for filling large areas of blocks at once

misty pivot
#

ohh, i see

#

i've used runInterval for generating small terrain, it lags a lot

#

does job do a better... job?

valid ice
#

It splits up the work over multiple ticks, lightening the load on the server

drowsy scaffold
#

and supports yeild statements so you can choose to split it up as you please

timber frigate
# dim tusk send bp manifest
{
    "format_version": 2,
    "header": {
        "name": "PACK NAME",
        "description": "This scripts is for practicing",
        "uuid": "uuid",
        "version": [1, 0, 0],
        "min_engine_version": [1, 21, 50]
    },
    "modules": [
        {
            "description": "",
            "language": "javascript",
            "type": "script",
            "uuid": "uuid",
            "version": [1, 0, 0],
            "entry": "scripts/Main.js"
        }
    ],
    "dependencies": [
        {
            "module_name": "@minecraft/server",
            "version": "1.16.0"
        },
        {
            "module_name": "@minecraft/server-ui",
            "version": "1.3.0"
        },
        {
            "uuid": "uuid",
            "version": [1, 0, 0]
        }
    ],
    "metadata": {
        "generated_with": {
            "blockbench_block_wizard": ["1.2.2"]
        }
    }
}
dim tusk
#

like success thingy

timber frigate
dim tusk
timber frigate
dim tusk
distant gulch
dim tusk
#

ngl. That's looks funny

dim tusk
true isle
#

is their any way to interact with a dispensor and get if the item being dispensed is bonemeal? im not finding anything yet

knotty plaza
#

If the block in that direction is a dispenser then thats it

edgy elm
#

hi here. Is it possible to detect the player spawnpoint? like the bed spawn

dim tusk
edgy elm
glacial widget
#

anyone know anti horion crash for bds servers?

untold magnet
#
world.afterEvents.itemReleaseUse.subscribe(({source: player, itemStack, useDuration}) => {
  const hat = player.getComponent('equippable')?.getEquipment('Head')?.typeId === 'exe_heads:fletcher_hat';
  if (!hat) return;
  if (hat && itemStack?.typeId === 'minecraft:bow' && useDuration <= 0.1) world.sendMessage('Works?');
})```isnt working?
untold magnet
#

i will.

untold magnet
stark kestrel
#

which server hosting has BDS softwares?

#

any ideas?

untold magnet
#

71997 is 0.1s
so i should make it like so: if (useDuration <= 71997) {***}

dim tusk
#

i guess so?

untold magnet
#

I'll do 71995

dim tusk
#

kinda confusing since iirc the docs say that it's based on ticks but 71997 is an hour if my math is correct

untold magnet
#

tick-72000 is the start, bows can shoot arrows from tick-71997, so i will use tick-71995

#

anyways

dim tusk
untold magnet
#

player.addEffect('speed', TicksPerSecond * Math(thing), {amplifier: 1})

untold magnet
#

( showcasing my Math skills )

dim tusk
#

you used && if I'm correct it will get the second, so the value returns is 7

dim tusk
untold magnet
dim tusk
untold magnet
#

it should at least give u 3s of speed,

#

not 0.1s

#

player.addEffect('speed', TicksPerSecond * Math.floor(Math.random() * (7 - 4 + 1)) + 4, {amplifier: 1})

dim tusk
untold magnet
#

its giving me from 0.1s up to 4s as the max value

dim tusk
# untold magnet Min time: 3 Max time: 7

player.addEffect('speed', 20 * (Math.floor(Math.random() * (7 - 4 + 1)) + 4), { amplifier: 1 });
Not a big difference (I think) since I just added () also make sure you are not looping it since it will obviously generate a new value each time

dim tusk
#

TU TU TU TU TU

chilly fractal
#

Fr, I'm vibing to it

distant tulip
# chilly fractal A* maybe?

there is some components that might help
make the entity target an invisible one either by making it hostile towards it or taming it to it
you can also use go to block thing

chilly fractal
#

Yeah i guess

#

I'm just suggesting a good pathfinding algorithm

dim tusk
#

guys, I'm starting to be old

distant gulch
distant tulip
#

A* algorithm

distant gulch
#

Oh my bad, does some exists like Minato said entity.goToBlock ?

#

Wait that wouldnt be a good solution because the enemies arent a constant speed (due some slowned by an Ice Tower)

distant tulip
#

nox have an example in his github for A* algo

distant gulch
#

Can you send me the Link? Im on phone rn

distant tulip
distant gulch
#

Thanks

grim raft
#

yo

dawn zealot
grim raft
#
world.afterEvents.entityHitEntity.subscribe((damagingEntity) => {
    const itemStack = damagingEntity.getComponent('equippable').getEquipment("Mainhand")
    const itemUsing = itemStack?.typeId == 'bleach:zanpakuto_2'
    const score = world.scoreboard.getObjective('z2_charge')

for some reason the 1st line says its not a function

#

the itemStack one

dawn zealot
#

isnt it mainhand or main_hand

#

I might be trippin tho

dim tusk
dim tusk
dawn zealot
dim tusk
dawn zealot
dim tusk
#

And why?

dawn zealot
# dim tusk And why?

i mean wouldnt mind showing the server off + you obv know how to optimize code better so wouldnt mind some tips

dim tusk
dawn zealot
dawn zealot
dim tusk
#

that's how you destruct

dim tusk
alpine ibex
#

Crazy

dim tusk
grim raft
dawn zealot
dim tusk
#

damagingEntity.damagingEntity.getCompo...

grim raft
grim raft
#

HUH

#

it worked

dawn zealot
#
world.afterEvents.entityHurt.subscribe((data) => {
    const hitEntity = data.hurtEntity
    const attacker = data.damageSource.damagingEntity
    const cause = data.damageSource.cause
    const { x, y, z } = hitEntity.location

})
``` i use this, use it if you want
dawn zealot
dawn zealot
#

?

grim raft
#

forgot to readd data

dawn zealot
#

uh

grim raft
#

it was working before but modified it

dim tusk
#

You got confused

dim tusk
#

that's why use short names like ev or e

dawn zealot
#

oh how i love errors

dim tusk
grim raft
drowsy scaffold
#

from what library can I import Vector3 from? I need the class itself to build prototypes on

grim raft
#

forgot why

open urchin
dim tusk
open urchin
#

if you're using ts you can do this for types

class Vector implements Vector3 {}
grim raft
#

then changed it to 2nd

drowsy scaffold
dim tusk
#

send your script in my dms

dawn zealot
dim tusk
#

-# or here just choose lmfao

dawn zealot
#

join vc so i can show

dim tusk
#

-# I don't vc... I'm scared 😟

dawn zealot
grim raft
dim tusk
#

I'll joined VC but I won't talk lol

dawn zealot
#

(its mainly cuz i wanna show off my realm cuz ye)

#

alr

dim tusk
#

Tho it always depends what you are doing

grim raft
drowsy scaffold
#

for an inventory shorthand like entity.inventory, should it return the container property or just the actual inventory component itself?

drowsy scaffold
#

I was thinking the same thing since the user may want other properties but I know that it's also most commonly used for getting items so that's why I wasn't sure

distant tulip
#

anyone have a function to turn vector3 to rotation

wary edge
distant tulip
#

thanks

true isle
untold magnet
#

hmm,

wheat condor
distant tulip
#

nah, i have a habit of trying to help even if i don't know shit

wheat condor
#

(Sorry for my bad English)

untold magnet
#

dimension.spawnItem(new ItemStack(wools.forEach(itemStack), 1), loc); this should spawn one item from the IDs in the index right?

untold magnet
#
const wools = ['id', 'id2'];
***
dimension.spawnItem(new ItemStack(wools.forEach(itemStack), 1), loc);```for a better view
wheat condor
#
Dimension.spawnItem(new ItemStack(wools[parseInt(Math.random * wools.lenght)]))
wary edge
#

parse int seems really unnecessary when you can just do math.round or floor.

untold magnet
wheat condor
wary edge
#

Preferences.

wheat condor
#

Math random returns a random number between 0-1

untold magnet
#

ik

wheat condor
#

Yeah I just forgot ()

warm drum
#

hi

#

is there a way to smoothly move the player from point A to point B

#

i tried teleport by a small distance but it locks the camera, also the whole journey is nothing but smooth

sharp elbow
#

If the player themselves must move, I would try having them ride an entity, then teleport/push that entity.

#

Otherwise I would look into using the /camera command or its API equivalent.

warm drum
#

Since its override the player camera

sharp elbow
#

Well yea, that's the idea. That solution would be ideal if you don't care about the player's camera (that is, you need the player's view to move smoothly, for e.g. a cutscene)

#

You were not very specific what this was for, so I'm only offering general solutions.

distant tulip
untold magnet
wheat condor
#

That’s up to you to edit wools

untold magnet
# wheat condor This means that wools isn’t an id of an item

const wools = ['minecraft:black_wool', 'minecraft:blue_wool', 'minecraft:brown_wool', 'minecraft:cyan_wool', 'minecraft:gray_wool', 'minecraft:green_wool', 'minecraft:light_blue_wool', 'minecraft:light_gray_wool', 'minecraft:lime_wool', 'minecraft:magenta_wool', 'minecraft:orange_wool', 'minecraft:pink_wool', 'minecraft:purple_wool', 'minecraft:red_wool', 'minecraft:white_wool', 'minecraft:yellow_wool'];

untold magnet
wary edge
untold magnet
wary edge
dull shell
#

can I make custom enchants? like with a book and stuff

dim tusk
#

guys why it throws an error can't getProperty on entity.

#

I'm using projectileHitEntity I have this
const type = projectile?.getProperty('coddy:type') ?? 'poke_ball'

dull shell
# dim tusk nope.

okay thank you! also is there anyway to make it where a block was broken another is placed?

#
import { world, ItemStack } from "@minecraft/server"

world.beforeEvents.playerBreakBlock.subscribe(event => {
    if (event.block.typeId == "minecraft:wheat") {
            event.player?.runCommandAsync("execute @s ~~~ execute @e[c=1,type=item,name=\"Wheat\"] ~~~ detect ~~~ air 0 setblock ~~~ wheat"); 
            event.player?.runCommandAsync("execute @s ~~~ execute @e[c=1,type=item,name=\"Wheat\"] ~~~ give @p wheat 1"); 
            event.player?.runCommandAsync("execute @s ~~~ execute @e[c=1,type=item,name=\"Wheat\"] ~~~ kill @s"); 
        }
    }
)``` 
I have this but it spawns wheat 1 block in the air and doesnt always replant
true isle
#

Check the location of the block broken and spawn it at that location

dull shell
#

thank you

#
import { world, ItemStack } from "@minecraft/server"

world.beforeEvents.playerBreakBlock.subscribe(event => {
    if (event.block.typeId == "minecraft:wheat") {
            let block = event.block;
            let player = event.player;
            let location = block.location;
        
            event.player?.runCommandAsync("execute @s ~~~ execute @e[c=1,type=item,name=\"Wheat\"] ~~~ setblock ${location.x} ${location.y} ${location.z} wheat"); 
            event.player?.runCommandAsync("execute @s ~~~ execute @e[c=1,type=item,name=\"Wheat\"] ~~~ give @p wheat 1"); 
            event.player?.runCommandAsync("execute @s ~~~ execute @e[c=1,type=item,name=\"Wheat\"] ~~~ kill @s"); 
        }
    }
)```
#

reason for this?

distant tulip
dull shell
#

my commands work with the "." its just the ${location.x}

#

etc

distant tulip
sweet seal
#
world.afterEvents.itemUse.subscribe(({ itemStack, source }) => {
  if (itemStack.typeId !== "minecraft:chest_minecart" || source.typeId !== "minecraft:player") return;

  const itemComp = itemStack.getComponent("minecraft:display_name");
  if (!itemComp) return;

  const itemName = itemComp.data;

  switch (itemName) {
    case "test":
      source.sendMessage("test");
      break;
  }
});

whats wrong

dim tusk
dim tusk
#

guys.

world.afterEvents.projectileHitEntity.subscribe(ev => {
   const { source, projectile } = ev
   cosnt hitEntity = ev.getEntityHit()?.entity;
   cosnt type = projectile?.getProperty('coddy:type') ?? 'poke_ball';
});```
#

it throws an error that I can't get the property

wary edge
dim tusk
#

oh yeah, I'm fuckin stupid. I'll just make that it doesn't destroy on hit

#

thanks smokey

umbral dune
#

Is it possible to add dynamic properties to blocks like chests, barrels and doors?

drowsy scaffold
umbral dune
#

How would I do this?

dim tusk
#

the object value will return x,y,z I'm just too lazy to manually show the seperation one

umbral dune
dim tusk
umbral dune
#

thank you, I was waiting for some method, but thank you!

umbral dune
#

how to show text above the hotbar, just like when you hold an item?

umbral dune
#

How do I check if the chest placed by the player has connected to another chest?

wheat condor
scarlet sable
#

Is it necessary to have all the functions in the entry file?

thorn flicker
#

why would it be

scarlet sable
#

Idk I just thought it was lol

#

So any .js file works fine?

thorn flicker
#

you can have functions in any file, just import it to the entry or a file thats imported to it already.

scarlet sable
#

Ahh

#

What scripts tho

#

Like world.afterEvents

thorn flicker
#

what?

scarlet sable
#

Like do they work in any file

#

Sorry if my communication skills are bad lol

thorn flicker
#

you just need to import it to the entry so it can work.

scarlet sable
#

It has to be imported

sterile epoch
#

where is the world initialise before event on the Microsoft docs

#

I can't find it

#

bruh I'm mad confused

sterile epoch
#

ok thanks but why was it removed from the Microsoft docs?

#

is it getting removed or sum

gaunt salmonBOT
#

Suggestion for @minor wren

Description
This script checks whether a player has the hack "Nuker" enabled through the use of block break event.

Credits
These scripts were written by iBlqzed

distant tulip
gaunt salmonBOT
#

Description
Gets chat ranks from a player and display in chat when player messages.

Credits
These scripts were written by Smell of curry

#

Description
Gets chat ranks from a player and display in chat when player messages.

Credits
These scripts were written by Smell of curry

distant tulip
umbral dune
fallow rivet
umbral dune
#

before events, playerInteractWithBlock

fallow rivet
#

Hmm

#

I guess you can't find a solution to this.

distant gulch
#

Minecraft needs Perfomance upates.. even Java run better on 120 FPS with 80+ Mods

distant tulip
distant gulch
umbral dune
distant tulip
distant gulch
#

hmm okay

distant tulip
#

@inland merlin had the same thing, i thing he solved it with a tp away from the door

umbral dune
#

-# Will we have client-side scripting someday? 😒

distant tulip
distant gulch
distant tulip
distant gulch
#

smart

fast lark
#

someone here know how to use minecraft/server-net?

distant gulch
fast lark
#

i want to make an ip ban but idk how

#

and even with the docs idk how can i do that

distant gulch
#

I dont think that's possible

fast lark
#

ive seen server that do that

#

and a random here told me is possible

remote oyster
#

It's not possible to use only the API's. You need other resources beyond just the API.

umbral dune
#

exposing players IP is not a very good idea

distant gulch
honest spear
distant gulch
honest spear
#

ohh its using VSCode under the hood

fast lark
distant gulch
fast lark
honest spear
#

AI is dump asf, but it helps writing meanless documentations so its kind useful for that

#

or for searchnig and explaining things

distant gulch
#

he wrote me a working code

fast lark
#

but i appreciate it

distant gulch
#

He can search in the internet now

#

so he can take a look over the docs

#

and writing you working code

fast lark
#

oh nice

distant gulch
#

but i just use him for math

fast lark
#

wait i want to test deep seek

remote oyster
#

ChatGPT is a tool. Not a magic wand. How you communicate with it will determine the results it returns to you. It's also designed to learn about you as you communicate with it. So the more you use it the more it becomes familiarized with what your intentions are.

distant gulch
#

or for god code structures (because i write with OOP)

umbral dune
#

How to get a player's velocity?

fast lark
#

const velocity = player.getVelocity();

distant gulch
distant tulip
slow walrus
#

(which is the VSCode editor)

distant tulip
#

i know

#

idk why auto complete don't work with some stuff tho
like getComponent functions

granite badger
#

The mapping is not in stable

distant tulip
untold magnet
#

it is possible to detect when the player killed a mob, but i have no idea how,
i think by using the entityDie component, right?

solar dagger
proud saddle
#

limit of records dynamic properties per minute concerns only one entity or all

distant tulip
solar dagger
untold magnet
#

i think via getComponent('type_family')

solar dagger
#

uh im not sure if that's a thing

#

hold up

wary edge
untold magnet
solar dagger
untold magnet
#

ya i see

solar dagger
#

i didnt know that was a thing xD

untold magnet
#

but i have to use beforrEvent so i can detect it before it dies

distant tulip
#

maybe use entity remove event
it have a before event

solar dagger
untold magnet
solar dagger
#

Wouldn't you use the entityHit?

untold magnet
#

lemme see if it works first.

thorn flicker
distant tulip
thorn flicker
solar dagger
untold magnet
# solar dagger was that the death event?
world.afterEvents.entityDie.subscribe(({ deadEntity: eEntity, damageSource }) => {
  const source = damageSource.damagingEntity;
  if (source?.typeId !== 'minecraft:player') return;
  const hat = source.getComponent('equippable')?.getEquipment('Head')?.typeId === 'exe_heads:witch_hat';
  if (!hat) return;
  const monster = eEntity.getComponent('type_family')?.hasTypeFamily('monster');
  if (monster) world.sendMessage('Work?');
});;```
scarlet sable
amber granite
#

Question

#

Is there anyone here that knows little bit about roblox programming?

umbral dune
#

offtopic

amber granite
#

Nah i just wanted to know if it uses JavaScript

#

Or not :-:

#

That s all :-:

wary edge
#

That's still off topic lol.

random flint
umbral dune
#

Do you know the playerPlaceBlock event? How do I check if I placed a chest, and if that chest connected to another, forming a double chest?

amber granite
#

Hmm :
Idea 1 : i think there type id for connected chests

#

Idea 2 : using runTimeout

umbral dune
#

I don't think so

wary edge
amber granite
umbral dune
amber granite
#

Hmm , make worldDynmaic proprety then

#

Save chests location

drowsy scaffold
#

would the connecting chest increase the inventory slot size? depending on how that works and when the event fires you could use that

amber granite
#

Make a logic to detect if two chests places to each others

distant tulip
#

what does container.size return for double chest?

amber granite
#

In the same pov

umbral dune
drowsy scaffold
#

you wouldn't need the location of the second chest, if that's what your asking

#

if you're saying you need it to be returned though that's a different thing

distant tulip
#

a chest next to a chest don't mean they are connected

amber granite
#

Yeah make :-: dynamic proprety , and put inside it object like that :

let object =
{ location : block.location , direction : "east  or , west , north ,or  south" } ;
#

Then make ur logic compare between faces and location of two chests

#

And that s it...

#

If there was no easy way to do it...

drowsy scaffold
amber granite
#

And add logic to remove the detected ones

distant tulip
#

that is not enough
you can't check for connected chest, i looked into this for a while

amber granite
#

Did u try :-: the logic first ,_,

#

U didn't:-: so u won't know .___.

distant tulip
#

i even fired a ray in the middle of the two sides hoping to get a result but it passed through them

distant tulip
amber granite
#

._. code i mean

umbral dune
#

-# why?

amber granite
#

Like :-:

distant tulip
#

how

amber granite
#

Add a counter there ,_,

drowsy scaffold
drowsy scaffold
# drowsy scaffold

what's the plan if someone places a chest in the middle of the two like I did?

umbral dune
#

I can't understand kiro

open urchin
#

there is no way to check that a chest is connected since that is stored in the block entity which we don't have access to

amber granite
#

._. , i think i must write the code , to make my idea more clear

drowsy scaffold
#

uh sure you do you pal

distant tulip
#

yeah

amber granite
#

.__. maybe i m bad in explaing things

#

But i m sure i can write correct code the detect this

drowsy scaffold
#

container.size does work

#

well no it doesn't because you still could have cases where it false fires

#

how are we all getting stumped by connected chests lmao

sharp elbow
#

I imagine a double chest would still have a container size of 27 slots for both chests. Each chest holds its own inventory, it only merges the two in the UI

amber granite
#

Hmm :-: let's use our brains

#

What is the special thing about connected chests

#

That make it easy for us to detect it

umbral dune
drowsy scaffold
#
world.afterEvents.playerPlaceBlock.subscribe(({player, block})=>{
    if (block.typeId !== "minecraft:chest") return
    const inventory = block.getComponent(`inventory`).container
    console.log(inventory.size)
})
amber granite
#

So i can send the code here ._. but i can't try it

#

Who will try it ?

sharp elbow
#

Would you look at that, I was wrong

umbral dune
distant tulip
amber granite
#

Ok

drowsy scaffold
#

I'm pretty sure there's no way to 100% accurately detect it through API

#

like getting the secondary chests' location

drowsy scaffold
# distant tulip what are the cases?

if a player places the chests like I do in the video and the right side is checked first instead of the left it would "technically" be a double chest since they both have container sizes of 54 but aren't connected

#

actually maybe not if you stored them as a connected chest in a dynamic property

distant tulip
#

you mean marking that location as single chest?

drowsy scaffold
#

kinda, gimme a minute to make code for this because now I'm invested lmao

umbral dune
#

imagine creating a property for every placed chest...

distant tulip
#

kiro made a chunk loader that store location of every block that need to be loaded

amber granite
#

:-:

#

No

amber granite
amber granite
#

Anyways. I found a way

#

Hmm @umbral dune how do u want the detection to be ?

sterile epoch
#

how do i make a chat relay system

#

r there any tutorials

umbral dune
#

just stop, kiro

amber granite
#

._. - no , i ll send the code then stop

#

I already finish it

umbral dune
#

you have already helped a lot

umbral dune
sterile epoch
#

yes

#

I've seen people do it but idk how to start it

umbral dune
#

I like the idea, I'll research it

drowsy scaffold
sterile epoch
#

can you elaborate

#

Minecraft protocol bots?

umbral dune
sharp elbow
olive rapids
#

Does anyone know how to import this?

const r = 1; //radius to check for blocks, adjust it until it make sense
const targetBlock = "minecraft:gold_block"; //block to detect
const soundEffect = "random.orb"; //sound to play
const objective = "pacman" // Tu scoreboard


system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        const { x, y, z } = player.location;
        for (let dx = -r; dx <= r; dx++) {
            for (let dy = -r; dy <= r; dy++) {
                for (let dz = -r; dz <= r; dz++) {
                    const block = player.dimension.getBlock({ x: x + dx, y: y + dy, z: z + dz });

                    if (block && block.typeId == targetBlock) {
                        player.playSound(soundEffect)
                        world.scoreboard.getObjective(objective).addScore(player, 1)
                        player.runCommand(`setblock ${block.x} ${block.y} ${block.z} air destroy`)
                    }
                }
            }
        }
    }
}, 0);```
drowsy scaffold
#

but you could also do it the other way I was talking about

umbral dune
drowsy scaffold
#

it's a node.js project that someone made to allow actual bots that can read/write game packets to be loaded into realms/dedicated servers

umbral dune
#

may i see the github?

drowsy scaffold
#

anyway back to the chests

#

I found a solution

#
const connectedChests = new Map()
//using maps so I don't have to clear a bunch of dynamic properties after this

world.afterEvents.playerPlaceBlock.subscribe(({player, block})=>{
    if (block.typeId !== "minecraft:chest") return
    const inventorySize = block.getComponent(`inventory`).container.size
    const surroundingBlocks = [block.east(),block.west(),block.north(),block.south()]
    for (const otherBlock of surroundingBlocks){
        if (otherBlock?.typeId !== "minecraft:chest" || connectedChests.get(otherBlock) !== undefined) continue
        const blockSize = block.getComponent(`inventory`).container.size
        if (blockSize == 27 || blockSize !== inventorySize) continue
        connectedChests.set(otherBlock, block)
        connectedChests.set(block, otherBlock)
        break
    }
    const connectedChest = connectedChests.get(block)
    if (connectedChest !== undefined){
        console.log(`chest at ${JSON.stringify(block.location)} is connected to chest at ${JSON.stringify(connectedChest.location)}`)
    }
})
#

you could probably optimize that further but that seemed to work every time I used it

sharp elbow
#

Where is connectedChests defined?

drowsy scaffold
#

ah it's a map outside of it, hang on

#

there it is

distant tulip
drowsy scaffold
#

huh, we basically got the same code with different steps, yours is more thorough for visuals though by far

sharp elbow
#

I'm working on a solution that requires no storage

amber granite
#

:-:

drowsy scaffold
amber granite
#

I was working on it too

sharp elbow
#

It's gonna be chunky though

amber granite
#

._.

#

:-bruh i m dumb:

#

._. there is better logic for all of this

#

Ok ,
Let s detect the two block beside it from west and south and east and north

distant tulip
drowsy scaffold
#

that's a component? mannnn I wish I knew that

umbral dune
#

I can't just use npm modules in my addon, right?

distant tulip
amber granite
umbral dune
amber granite
#

._. and ?

umbral dune
#

I think you can check the value using <block>.permutation.getState("minecraft:cardinal_direction")

amber granite
#

:-: i mean i don't know what it used for

distant tulip
#

to check chest direction and avoiding another edge case

#

@drowsy scaffold
my approach

function getDoubleChest(block) {
    if (block.typeId !== "minecraft:chest") return undefined;
    
    const inventory = block.getComponent("minecraft:inventory")?.container;
    if (!inventory || inventory.size !== 54) return undefined;

    const direction = block.permutation.getState("minecraft:cardinal_direction");
    if (!direction) return undefined;

    const checkDirs = direction === "north" || direction === "south" 
        ? ["east", "west"] 
        : ["north", "south"];

    for (const dir of checkDirs) {
        const neighbor = block[dir]();
        if (neighbor?.typeId === "minecraft:chest") {
            const neighborDir = neighbor.permutation.getState("minecraft:cardinal_direction");
            const neighborInventory = neighbor.getComponent("minecraft:inventory")?.container;
            if (neighborDir === direction && neighborInventory?.size === 54) {
                return [block, neighbor];
            }
        }
    }

    return undefined;
}
sharp elbow
#

How does it perform in this situation, with placing the chest in the middle of these two?

#

Depends on orientation too, be sure to try all four cardinal directions

#

Unless, is that covered by north and east appearing first in checkDirs?

#

That is pretty straightforward. I was trying to perform the checks in BeforeEvent, before the placed chest could merge

amber granite
#

Here my approach< i m working on its code >

#

If finsih it

distant tulip
amber granite
#

Hmmm a question

distant tulip
#

ask

slow walrus
#

or a diff block

distant tulip
#

yeah, working on it
just have to visualize it for my brain lol

amber granite
#

Ok i found a way

#

It s pretty simple

#

And no one can guess it

#

._. let s count the number or east and west chests

distant tulip
amber granite
#

And if the number of continuative chests is odd or even

#

In both directions:-:

#

And we will know if it s connected or not

#

If number of west is even and number of east is even = there is chest

#

If one of them if false there is not

#

What do u think ? @distant tulip

sharp elbow
#

How do we set a Block to an ID again? I forget

distant tulip
amber granite
#

._.

distant tulip
amber granite
#

,_, the same direction

distant tulip
#

yeah?

amber granite
#

They face the same direction and must be chest type and continuative

#

If u mean commands :-: we cannot detect that , but better than nothing right ?

distant tulip
dawn zealot
distant tulip
#

kinda

amber granite
#

What is in the picture?

dawn zealot
sharp elbow
distant tulip
#

pistons

sharp elbow
#

Ah, I see

dawn zealot
amber granite
#

Yeah that s innormal

wary edge
#

I thought shifting place disabled connectedness on BE as well?

sharp elbow
#

I was, at one time

dawn zealot
amber granite
#

But i think my idea will work to detecting players

amber granite
open urchin
#

only on java

sharp elbow
amber granite
#

Oh god :-:

wary edge
#

Should update my parity site then.

distant tulip
sharp elbow
distant tulip
#

lol, just the tow gaps

#

try it in the other axes

sharp elbow
#

Seems to be good

#

@drowsy scaffold

#

Some of the JSDoc is a bit behind what I implemented ("left and right" became "first and second")

#

I got a bit lazy at the end and hardcoded the placeAbove conditions

#

@umbral dune got a potential solution for you

amber granite
#

:-:

#

What if we combine two of the scripts

#

Together?

distant tulip
drowsy scaffold
sharp elbow
#

Now the question is if someone can write it to be shorter 😎

distant tulip
#

what happen if only one side of the chest is loaded πŸ˜…

sharp elbow
#

Not sure. I did not account for LocationInUnloadedChunkErrors

amber granite
#

That s great

distant tulip
#

that
throw Error("Sanity condition");
lol

sharp elbow
#

Theoretically that error should never be thrown, but you never know

amber granite
#

Explain me how ur logic works :-:

distant tulip
#

unless you look into the 4th dimension

distant tulip
amber granite
#

._. it looks like he uses probabilties

#

Inside his code

#

Somehow

sharp elbow
# distant tulip yeah that player rotation is confusing me

It maps the player's y-rotation to the corresponding facing_direction of the chest.
2 means the chest faces north; thus the player must be facing somewhere south (-45..45)
3 means the chest faces south; thus the player must be facing somewhere north (-180..-135, or 135..180)
4 means the chest faces west; thus the player must be facing somewhere east (-135..-45)
5 means the chest faces east; thus the player must be facing somewhere west (45..135)

amber granite
#

._.

distant tulip
#

i mean yeah, but how that help, and why not just get chest dir

sharp elbow
#

The chest does not exist at this time. All of this logic is performed before the chest is placed

#

rotationToFacing determines what the to-be-placed chest's rotation will be

amber granite
#

.____. my brain hurts

sharp elbow
#

Ah, that's a thing? My typings did not suggest that

distant tulip
#

yeah, also permutation == permutation2, work so no need for get state

#

nvm, you are using get state for other things

amber granite
#

Hmmm

distant tulip
#

it is beta πŸ€¦β€β™‚οΈ

#

damn, even in the latest preview

sharp elbow
# amber granite .____. my brain hurts

Before the chest is placed:

  1. Find the Block where the chest will be (119).
    const ToBeChest = arg.block[DirMap[arg.blockFace]]();
  • This uses a mapping of BlockFace types to a method that grabs the adjacent face, then performs that method on the block.
  • The result is essentially the space where the chest will be after this function ends.
  1. Find the facing_direction state of the chest that will be placed (120).
    const FacingDir = rotationToFacing(arg.player.getRotation().y);
  • This uses a function that returns either 2, 3, 4, or 5 depending on the rotations specified earlier. This matches the values that a chest's facing_direction state can take on.
  1. Find the blocks to the left and to the right of the chest (121).
    const {First, Second} = getFirstAndSecond(ToBeChest, FacingDir);
  • Based on the facing_direction state of the chest, grab the Blocks to the "left" and "right" of the chest. North is prioritized over South, and East is prioritized over West.
  1. Determine if the blocks to the left and right are chests that have not yet been connected (123, 124).
    const FirstValid = isConnectableChest(First, FacingDir);
    const SecondValid = isConnectableChest(Second, FacingDir);
  • A block is considered to be a connectable chest if: The block is a chest; it faces the same direction as the first chest; and it has an inventory, and its inventory has 27 slots.
  1. Determine which of the blocks to the side the original chest will connect to.
if(FirstValid && !SecondValid) {
    placeAbove(ToBeChest), placeAbove(First);
}
if(SecondValid && !FirstValid) {
    placeAbove(ToBeChest), placeAbove(Second);
}
if(FirstValid && SecondValid) {
    placeAbove(ToBeChest), placeAbove(First);
}
  • If both the left and right blocks are valid, then we pick the first, which will be the North or East block.
amber granite
#

Elisah , just put a bomb here and left :-:

#

Wait a min

#

Double chest

#

Inventory = ?

#

I mena double chest slots

distant tulip
#

54

sharp elbow
#

Both chests in a Double Chest arrangement have an inventory size of 54

amber granite
#

I mena in script

#

I mean in script api

sharp elbow
#

Same there. If you grabbed the "inventory" component of one block in a Double Chest arrangement, it would report 54 slots

amber granite
#

Nice

#

What about one chest ?

sharp elbow
#

A single chest on its own would be 27 slots

amber granite
#

Sure ?

#

Ok i think i find the solution._.

#

._.

#

I ll make a code smaller than yr .___.

#

Hihihi

sharp elbow
#

What makes this challenging is Bedrock does not expose its connection type as a block state. If we could read this, it would be much simpler

amber granite
#

I see

sharp elbow
#

And I just realized my typing in JSDoc on CardinalLeft was obtuse

#

could have just done this haha

amber granite
#

Question

sharp elbow
#

Shoot

amber granite
#

When u wrote it

#

U need to detect or knoe the specific place of connection ?

sharp elbow
#

It is predictive. Based on what we know of chest connection rules, I wrote functions to predict what would happen

amber granite
#

._.

#

Wasn't the goal , to only detect?

sharp elbow
#

It may have been. In a sense, this does detect it, but through prediction

amber granite
#

,_,

#

._. wow

sharp elbow
#

I might not be understanding your question fully either

amber granite
#

:-: i mean what they ll use ur code for

#

To make another event of detecting if chest connected

#

Or ._.

#

Another thing

sharp elbow
#

Oh, that I have no idea. I tried to write it generically enough so anyone could adapt it

amber granite
#

Oh

sharp elbow
#

For example, this could be used to prevent players from making double-chests

amber granite
#

That s nice

sharp elbow
amber granite
#

._.

#

Nah that s good

sharp elbow
amber granite
#

._.

#

Ok i think i finished my code

amber granite
#

@distant tulip can u try it ?

distant tulip
distant tulip
amber granite
#

Ok one min

#
import { world } from "@minecraft/server";

world.afterEvents.playerPlaceBlock.subscribe(({ block }) => { 
    let current_b = block;
    if (block.type !== "minecraft:chest") return;

    let EastConnected = (
        current_b.east().permutation.getState("facing_direction") == current_b.permutation.getState("facing_direction") &&
        current_b.east().getComponent("inventory").container.size == 27 &&
        current_b.east().type == "minecraft:chest"
    ) ? true : false;

    let WestConnected = (
        current_b.west().permutation.getState("facing_direction") == current_b.permutation.getState("facing_direction") &&
        current_b.west().getComponent("inventory").container.size == 27 &&
        current_b.west().type == "minecraft:chest"
    ) ? true : false;

    if (EastConnected || WestConnected) { 
        world.sendMessage("there is a connected chest"); 
    }
});
#

._. what do u think :-:

distant tulip
#

size() to size

amber granite
#

._.

#

Put !==

#

Instead of ==

#

And remove ! From !block

#

._.

sharp elbow
#

If the container size comparison is !== 27 (i.e. == 54) then I suppose it would return true.

distant tulip
#

changed that and nothing

drowsy scaffold
#

😭the double chest problem optimization is incredible

amber granite
#

._.

#

Idk :-: if the problem is detecting if chest is connected anymore or not

#

:-: i can't even debug my code .___.

sharp elbow
#

If the facing direction of both the block and its adjacent block matches, the adjacent block has 54 slots, and the adjacent block is a chest, that is technically the criteria for a chest connecting.

distant tulip
amber granite
#

._.

sharp elbow
amber granite
#

._. u told me single chest slots are 27

#

And if we get Inventory components of that double chest we will get 54

#

Yep ?

#

Logically, if everything is same direction and the east or west blocks are chests

#

And slots ._. are 27 , it forces it to be connected

sharp elbow
amber granite
#

Only if.... ,_, there are commands that makes no chest sticks to another

amber granite
#

That needs before event then

#

Lol ._.

sharp elbow
#

I thought so too

amber granite
#

Yay :-: i breaked the rule i made the best chest detector ;-; yay

sharp elbow
#

You gave it a fair shot. Now try with BeforeEvent!

amber granite
#

._. i truly don't have debug tools

#

I can't test it