#Script API General

1 messages · Page 5 of 1

glacial widget
#

i need a tester first

remote oyster
amber granite
#

It will work

glacial widget
glacial widget
neat hound
# glacial widget alr

Unless you are working in collaboration with someone else who is designated the tester, you will need to test practically everything yourself. I would suggest, building in the infrastructure to do so.
For myself, I have a whole class module and when I do not want to use it, I use ```JS
export const debug = true;
export const debugMsg = function (msg = "", preFormatting = "") { if (debug && msg) world.sendMessage(${preFormatting}@${system.currentTick}: §cDebug Log:§r ${msg}); };


So for your case, you could list out the tags of a player that spawned in, then add a message in where the tag was found, so that you know your matching is okay.  I remember you were concerned about the double quotes in the tag.
glacial widget
neat hound
dusky cipher
#

How many drop down options can a ModalFormData handle?

#

I need to make the player select from a few hundred options

neat hound
# glacial widget yeah i was because for that callback function you would need it however for the ...

Don't always give up because someone says something is not possible, unless you know them to be a JS God. yes you can have double-quotes in your tags** and yes you can search and display**

Use this chat command example to extrapolate how you may achieve your goal ```JS
world.beforeEvents.chatSend.subscribe(
(event) => {
const player = event.sender;
if (!(player instanceof Player)) return;

    if (player.isOp()) {

        if (event.message.toLowerCase() === ":tags") {
            event.cancel;
            const tags = player.getTags();
            player.sendMessage(`\n\nPlayer Tags: ${tags.length}`);
            const vipTag = `"rank:§a§lVIP"`;
            tags.forEach((tag) => player.sendMessage(`===> ${tag}`));
            tags.forEach(tag => { if (tag === vipTag) player.sendMessage(`\n\nSpecial VIP Tag ${tag}§r found`); });
        }

        if (event.message.toLowerCase() === ":cls") { event.cancel; player.sendMessage("\n".repeat(40)); }
    }

}

);``` you can add this, if using beta to test tags. I would suggest if showing this tag to players, that you add §r to the end of VIP, so the last double-quote is not green. Note: test for includes() will not work for some reason. I had another way around it if the === did not work, but it did. Where there is a will, there is a way... remember that, as a programmer. And if it does not exist, create it... (hardcore programmers)

glacial widget
#

thank you alot

spring dove
burnt remnant
#

just googled it and || means or? is that true will it work for this

valid ice
#

Yep

#

&& is AND, || is OR, ! is NOT

burnt remnant
neat hound
#

Exploring the API Classes is a worthwhile activity to help you discover the possiblilites

spring dove
#

ItemStack i know how to do somn

#

but SetLore its new for me

#

ty

wary geode
#

Also anyone know what to do if when you try loading a gametest it says that it can't find the game test. I have no idea what the issue it.

glacial widget
#
import { system, world, Player, ItemStack } from '@minecraft/server';
import { ChestFormData } from './extensions/forms.js';

export function removeScore(amount, target, objective) {
    if (!(target instanceof Player)) return;
    target.runCommand(`scoreboard players remove @s ${objective} ${amount}`);
  }
  export function getScore(target, objective) {
    try {
      target.runCommand(`scoreboard players add @s ${objective} 0`);
      return world.scoreboard.getObjective(objective).getScore(target);
    } catch {
      return 0;
    }
  }
  
function ChestTest(player) {
    const chestui = new ChestFormData('27')
    .title('§l§d      Pickaxe shop V2')
    .button(10, '§l§3Tier 6', ['$50,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/netherite_pickaxe')
    .button(11, '§l§bTier 7', ['$55,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/amethyst_pickaxe', true)
    .button(12, '§l§9Tier 8', ['$55,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/amethyst_pickaxe', true)
    .button(13, '§l§5Tier 9', ['$65,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/emerald_pickaxe')
    .button(14, '§l§5Tier 10', ['$65,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/emerald_pickaxe')
    .button(15, '§l§dTier 11', ['100,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/echo_pickaxe')
    .button(16, '§l§dTier 12', ['100,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/echo_pickaxe')
    .show(player).then(response => {
        if (response.canceled) return;
        switch(response.selection) {

             case 10:
                for (const player of world.getAllPlayers()) {
                    const inv = player.getComponent("inventory").container;

                        const item = new ItemStack("minecraft:netherite_pickaxe", 1)
                        const Money = getScore(player, "Money")
                        

                        if (Money >= 50000) {
                            removeScore(50000, player, "Money")
                            item.setLore("Tier 6")
                            inv.addItem(item)

                        } else if (Money < 50000) {
                            player.sendMessage("§l§d HCV KitPvP >> §l§4You do not have enough for a Tier 6 pickaxe")

                        }
                }
                   break;
glacial widget
wary geode
#

I'm prob not the best person for this. But what type of error are you getting? Or what is the error message?

dawn zealot
#

how me summon item

wary geode
#

With commands? I think you can only summon entities. But you can give yourself items with /give.

dawn zealot
#

so custom loottable

dusky cipher
#

How do I cancel a callback like a beforeevent? Can I just set a variable equal to the beforeevent?

glacial widget
dusky cipher
#

oh nvm i figured it out lol

amber granite
#

Line !

glacial widget
amber granite
#

Yes

remote oyster
frozen vine
#

Is it possible to trigger a script file that is outside the script folder?

turbid oriole
#

What is a dynamic property of the Minecraft server world object?

simple zodiac
#

its a property that last over world loads

wary edge
#

Property thag is dynamically saved and persistent across sessions

turbid oriole
turbid oriole
wary edge
#

You cant read anything outside the scripts folder

wary edge
remote oyster
#

^

amber granite
#

It s better to save tags on player's dynamic proprety yep ?

turbid oriole
amber granite
#

Or they are saved ?

simple zodiac
#

? does a lot of things

turbid oriole
amber granite
#

Means , optional parameter

turbid oriole
turbid oriole
remote oyster
simple zodiac
#

? can be used as the ternary operator, an option or null coalescing

frozen vine
turbid oriole
amber granite
#

U can with double dots

turbid oriole
#

What ecmascript version is Minecraft Javascript in?

remote oyster
simple zodiac
#

they updated it recently

amber granite
#

Es6

simple zodiac
#

ofc es6

turbid oriole
amber granite
#

XD

simple zodiac
#

but the module target is es2023

#

it was 2020 before that

turbid oriole
#

:b

#

I can use external libraries, right? Of physics for example.

amber granite
#

Yes

#

If it supports Math object

turbid oriole
#

:3

turbid oriole
remote oyster
turbid oriole
#

:3

#

:v Give me ideas to practice and gain experience. I read the complete mdn Mozilla documentation.

simple zodiac
#

but you will need a bundler to make them accesible or just you know 1 random file with the lib in it

amber granite
#

Try to make snake game and calculator

turbid oriole
turbid oriole
amber granite
#

English or Spanish?

turbid oriole
#

UwU good idea, I'll do it. I'll use the native controls and a block for the rest.

turbid oriole
amber granite
#

Si te mueves eres goy

turbid oriole
#

:V es ilegal el español. Aquí nos discriminan xD

amber granite
#

I used translator XD

turbid oriole
#

I use the integrated one. Keyboard.

amber granite
#

Nice

remote oyster
turbid oriole
turbid oriole
wary edge
#

Now I'm beyond confused

frozen vine
remote oyster
distant gulch
#

does anyone know how to convert the number vars to a vector3 value

#

like const vector = new Vector3 (num1,num2,num3)

#

is the idea

#

how would i achieve this

wary edge
#

So it be:
{x: blah, y: blah, z: blah}

distant gulch
#

i thought that but i thought that was ts exclusive...

#

thanks

halcyon phoenix
#

Oh TS is more beginner friendly then

tight plume
halcyon phoenix
#

lol, why?

#

is the difference only on the typing side?

granite badger
#

@gaunt salmon is has a TS debugger inside. Check it out

solar dagger
chrome flint
#

i wonder, which one is much more optimized
multiple lines of .spawnParticle() or a one line of .runCommand() that runs a function with particle commands

valid ice
#

spawn particle- run commands are very slow, regardless of what they run.

chrome flint
#

i see, thank you

valid ice
#

functions are faster than runCommands, but only if used outside of runCommands- like inside of an animation controller or whatnot

#

calling a mcfunction from scripts is... not great

granite badger
chrome flint
#

ill just resort to runCommand with functions, much more shorter to write in script

valid ice
#

if possible, try to use runCommandAsync

chrome flint
#

ah, async

valid ice
#

async queues until the end of the tick and does not hold up the code.
regular halts code execution until the command has returned a successful/unsuccessful execution- and unsuccessful ones may throw a console error and prevent the code from running further

chrome flint
#

too dumb of me

valid ice
#

I despise runCommand

#

had lag issues on a world, and went to diagnose- 18 runCommands took 16 ms to process.
switched to native methods, and zero problems since.

chrome flint
#

okay then, ill resort to native methods if possible

fast lark
#

#1265218592568246282 if someone can help

random flint
runic gust
#

how do i transfer info from scripts to json ui

#

what exactly do i need to do

devout hazel
#

how do I use the debug tool?

buoyant canopy
runic gust
#

like transfering text

#

or making certain hud elements visible

devout hazel
#

hi, could anyone see whats wrong with my script, used to work but i guess they changed the API

#

its supposed to remove health score from entities when they are hit by my projectiles

#

dw worked it out

glacial widget
#

How do i give a item a name?

#
const item = new ItemStack("minecraft:netherite_pickaxe", 1)
                            item.setLore(["Tier 6"])
                            inv.addItem(item).nameTag("Tier 6 pick")
distant tulip
#

itemStack.nameTag = "item name"

glacial widget
distant tulip
#
const item = new ItemStack("minecraft:netherite_pickaxe", 1)
                            item.setLore(["Tier 6"])
                            item.nameTag = "item name"  
                            inv.addItem(item)
glacial widget
distant tulip
#

man*
your wlc

glacial widget
#
enchant.addEnchantment({ type: "unbreaking", level: 3 })
const enchant = item.getComponent("enchantable")

Did i mess up the syntax of addEnchantment?

subtle cove
#

define the variable "enchant" first before using it to make changes

#

const enchant
enchant.addEnch

glacial widget
# subtle cove define the variable "enchant" first before using it to make changes
for (const player of world.getAllPlayers()) {

                    const inv = player.getComponent("inventory").container;
                    const item = new ItemStack("minecraft:netherite_pickaxe", 1)
                    const enchant = item.getComponent("enchantable")

                            item.setLore(["Tier 6"])
                            item.nameTag = "§l§3Tier 6"
                            enchant.addEnchantment({ type: "unbreaking", level: 3 })
                            inv.addItem(item)
subtle cove
#

type: new EnchantmentType("unbreaking")

#
const nPix = new ItemStack("minecraft:netherite_pickaxe")
nPix.setLore(["Tier 6"])
nPix.nameTag = "§l§3Tier 6§r"
const ench = nPix.getComponent("enchantable")
ench.addEnchantment({ type: new EnchantmentType("unbreaking"), level: 1 })
``````js
for (const p of world.getAllPlayers()) {
    const inv = p.getComponent("inventory").container
    //other code if statements 
    inv.addItem(nPix)
} ```
vocal elbow
#
player.onScreenDisplay.setActionBar(`${jetpackDurability}`);``` I tried with setTitle it was working but with setActionBar it doesn't work, why ?
subtle cove
vocal elbow
#

I'm going to see

#

It must be that thank u

sudden nest
#

There's a mistyped in the minecraft fandom wiki, anyone know any accurate as possible enchantment's level table range?

#

Min: 52
Max: 50

#

Idk if that's on purpose or mistyped. Not so big deal anyways.

sudden nest
wary edge
#

Dont use fandom

sudden nest
#

I just knew rn that I was using fandom the whole time xp, and checked the official wiki

#

Still 52 - 50

fast lark
#

how can i test for a item in the inventory of a player whit script

#

with

glacial widget
subtle cove
#

import it

glacial widget
#

make everything look nice

#

i dont understand the problem lol

#

i didnt know you could - the amount with world.scoreboard

#

however thank you

valid ice
#

addScore of negative number

glacial widget
weary umbra
#

guys why is it so weird when I use camera on player its jerky

system.runInterval(() => {
    for (let plr of world.getPlayers()) {
        let { x, y, z } = plr.location
        let scaleValue = player.getComponent("scale").value
        plr.camera.setCamera("minecraft:free",
            { location: { x: x, y: y + 5 + scaleValue / 2, z: z }, 
            facingEntity: plr }
        )
    }
})
shy leaf
#
player.camera.setCamera("minecraft:free",{
                easeOptions: {easeTime: player.getDynamicProperty("dc_camlerp")/100, easeType: "Linear"}, 
                location:camlocation, 
                facingLocation: {x: player.location.x, y: (player.location.y+player.getHeadLocation().y)/2, z: player.location.z }
                })```
#

took it from my code

weary umbra
shy leaf
#

np

weary umbra
#

Is there away to set the players rotation?
bc this doesn't work

            if (plr.getRotation().x <= 0) {
                plr.setRotation({ x: 0, y: plr.getRotation().y });
            }
#

I had this solution but its not good if you move

            if (plr.getRotation().x <= 0) {
                plr.teleport(plr.location, {rotation: {x: 1, y: plr.getRotation().y}})
            }
warm drum
#

does anyone have a list of all minecraft block that could be import into script?

wary edge
# warm drum how...

Just do BlockTypes.getAll() and you'll get an array of of all block ids in the game

#

What exactly are you trying to do?

warm drum
#

I do have to import it

#

Thanks

amber granite
#

Import it from

#

Vanilla-data

#

@warm drum

cold grove
#

Vanilla data is not used

amber granite
#

And put it in scripts folder

#

Somehow

cold grove
#

Just import it from minecraft-server

amber granite
cold grove
amber granite
#

I didn't know

amber granite
remote oyster
amber granite
elder heath
thorn ocean
#

Is there a way to use the player.teleport where you can still move the camera?

#

Cuz I noticed the camera is forced to a specific location.

fast lark
#

const moneyTransfer = (player) => {
const players = [...world.getPlayers()];
const money = getPlayerScore(player, "Money")
new ModalFormData()
.title('Money Transfer')
.dropdown('§o§5 destinatario!', players.map(player => player.name))
.textField(§uEnter The Amount You're Sending!\n§dYour money=§5 (${money}), §o solo numeri)
.show(player)
.then(({ formValues: [dropdown, textField] }) => {
const selectedPlayer = players[dropdown];
const amount = parseInt(textField, 10);
const receiverCurrentMoney = getPlayerScore(selectedPlayer, "Money");

            if (selectedPlayer === player) {
                player.sendMessage(`§cYou can't select yourself`);
                return;
            }
            if (isNaN(amount) || amount <= 0) {
                player.sendMessage(`§cPlease enter a valid positive number`);
                return;
            }
            if (money < amount) {
                player.sendMessage(`§cYou don't have enough money`);
                return;
            }

            try {
                setPlayerScore(player, money, money - amount);
                player.sendMessage(`§aSent §l${selectedPlayer.name} §r§2$${amount}`);
                selectedPlayer.sendMessage(`tellraw @s {"rawtext":[{"text":"§l${player.name} §r§aHas Given You §2$${amount}"}]}`);
                setPlayerScore(selectedPlayer, "Money", receiverCurrentMoney + amount);
            }
});
};

});

#

there is a syntax error

distant tulip
fast lark
#

setPlayerScore(selectedPlayer, "Money", receiverCurrentMoney + amount);
}
}<--- ); here i dont knnow why

#

pls help

sudden nest
#

im happy... i followed the whole enchanting mechanics from the minecraft wiki. Feelsgoodman🫡

last latch
#

i switched to my laptop and need the ChestFormData of Herobrine but cannot fnd it . Could anyone send me its link?

last latch
#

thanks g

pale terrace
#

isnt there dynamic properties for blocks?

pale terrace
#

💀

last latch
#

wait, how do you add enchantments without using the Enchantment class?

valid ice
#

ItemStack.getComponent('enchantable').addEnchantment({ type: new EnchantmentType('unbreaking'), level: 2}) for instance

last latch
#

oh right,

#

it is odd

valid ice
#

yep

thorn ocean
#

Are there any script events that can work in spectator mode?

last latch
#

changeDimension?

#

if i understand your question right, changing dimension should trigger a event

thorn ocean
glacial widget
#

I have the structure saved on the world

pale terrace
#

many dynamic properties can be laggy? if yes, how can I remove / reset a dynamic property?

subtle cove
#

set(prop)

pale terrace
subtle cove
#

does it...

granite badger
scenic bolt
#

Would someone be able to tell me why this would not work?

#

e is defined, no errors

subtle cove
#

entity.runCmd would follow ~ but not dimension

#

U gota specify the location for that

scenic bolt
#

ah

#

This is running off of onPlayerDestroy

#
    initEvent.blockTypeRegistry.registerCustomComponent('not_enough_adventure:bottom_collision', {
        onPlayerDestroy(e) {
            e.block.dimension.runCommandAsync("setblock ~-1 ~ ~ air destroy");
        },
    });
});```
scenic bolt
#

oh shoot

#

so

#

I think Im dumb

#

e.block.dimension.runCommandAsync("setblock ~~-1~ air destroy");

#

Had to fix that because otherwise it wouldnt be getting the block below it lol

#

still does not work though

subtle cove
#
const b = e.block
b.dimension.runCommandAsync(`setblock ${b.x} ${b.y-1} ${b.z} air [] destroy`)
scenic bolt
#

interesting

#

I thought location was defined since it was running the event from a custom component on the block

subtle cove
#

nope, it's running from dimension

subtle cove
woven oyster
#

Instead of [] ?

subtle cove
#

Try it

woven oyster
#

: ) kkk

scenic bolt
#

testing now

#

I gotcha

woven oyster
subtle cove
#

U know u can still try the bad ones to understand how it's "bad"

woven oyster
scenic bolt
#

[Scripting][error]-Unhandled promise rejection: CommandError: Syntax error: Unexpected "0": at "-1083 air >>0<< destroy"

subtle cove
#

Noice

scenic bolt
#

The only reason im even using this command is because you cant set destroy on a block through a script

#

Using destroy gives out loot

subtle cove
#

Yeh, which is frustrating

scenic bolt
#

Best thing I could think of lol

woven oyster
scenic bolt
#

no

#

not that

woven oyster
scenic bolt
#

the loot itself

subtle cove
#

More like cobble from stone instead of stone

scenic bolt
#

So im making a crop thats 2 blocks tall

#

Instead of giving the top collision loot and doing a whole thing

#

I have it so that on destroying the top block, set the bottom one to air, but give me the bottom blocks loot

woven oyster
#

Oh i understand

#

Soo good luck

#

: )

scenic bolt
#

Thanks, works perfectly now thanks to you guys

#

Oh

#

About the []

#

You don't need it at all

#

just remove it and it still works

subtle cove
#

Mhm

solar dagger
#

anybody know why the saddle is given back to the player?Is the saddle considered to be in slot 0 of the entity?Also as you can see in the video for some reason when i try to open the mammoth's inventory it instantly closes...(is that a component issue?)

subtle cove
solar dagger
#

Range of seat?

#

i just press E to try to open the inv ui

subtle cove
#

Yeh

#

Well what else could it be...

buoyant canopy
#

your seat might be too far away from the entity's feet, maybe

solar dagger
#

@subtle cove do you know about the saddle issue?

cold grove
#

is your hitbox small? hmm

subtle cove
solar dagger
subtle cove
#

Dunno what's happening, sorry

solar dagger
#

alr 😛

subtle cove
#

Uhm u have a code that moved the items to player's inv...

solar dagger
#

well nvm i figured out why it was giving me the saddle. The saddle is located in slot 0. Just had to pull slots 1+

pale terrace
#

hmm what? level 1 is not in 0-4?

#

idk how to fix this

shy leaf
pale terrace
elder heath
turbid oriole
#

[error]-ReferenceError: Native function [Dimension::setBlockType] does not have required privileges

#

How do I give privileges?

random flint
turbid oriole
#

I had entered the argument format incorrectly. Wait I check.

turbid oriole
#

Lose, tick by tick.

random flint
turbid oriole
#

I know

random flint
#

system.run push that outside of the scope

turbid oriole
random flint
#

k

turbid oriole
#

Time to test if it works.

#

UcU then you say what should I place how the structure? I want to place a block in the world after the player places one.

#

Should I create a function?

#

I think I already understood. It's because of the scope.

pale terrace
#

how can I summon a zombie with enchanted armor?

#

I cant use equippable on entities...

turbid oriole
# random flint k

You were right. Events do not need a loop and a block cannot be placed immediately after e. The run helped.

meager leaf
pale terrace
#

thx

warm drum
#

is there a way to use fillblock but with break?

#

like make the block break?

#

with item drop and sound

granite badger
#

no you gotta use commands for that

warm drum
#

40 ish

#

Commands will not be able to handle that 😦

glacial widget
#
world.structureManager.place(`pshop1`, player.dimension, { ...player.location, y: player.location.y + 2})

                          const inventory = player.getComponent(`inventory`).container
                          const item = player.dimension.getBlock({ ...player.location, y: player.location.y + 2 })
                          inventory.addItem(item)

could someone tell me what i did wrong?

distant tulip
distant tulip
glacial widget
pale terrace
distant tulip
glacial widget
distant tulip
glacial widget
#

does it have to be saved on my storage?

distant tulip
#

with the id "id:pshop1" ?

glacial widget
# distant tulip with the id "id:pshop1" ?
world.structureManager.place("id:pshop", player.dimension, { ...player.location, y: player.location.y + 2})

const inventory = player.getComponent(`inventory`).container
                            const block = player.dimension.getBlock({ ...player.location, y: player.location.y + 2 })
                            const chest = block.getComponent(`inventory`).container

                            for (let i = 0; chest.size; i++) {
                            const item = chest.getItem(i)

                                if (item) inventory.addItem(item)
                            }

                              block.setType(`minecraft:air`)

                              player.playSound(`note.pling`, { pitch: 2 })
distant tulip
#

how are you saving it

#

with what id

glacial widget
distant tulip
#

i meant the structure

glacial widget
distant tulip
#

use that instead of "id:pshop1"

glacial widget
pale terrace
#

first get your structure in a variable and then use it in .place

distant tulip
pale terrace
#

when I tried didnt work by using the structure identifier directly

distant tulip
#

i did try it too
and the docs say it use both

pale terrace
#

weird, I don't know what I did wrong then

glacial widget
warm drum
#

Lemme try to queue it

shy leaf
#

is beforeEvents.worldInitialize a beta thing?

#

oh it is

#

bummer

distant tulip
shy leaf
#

just beta API?

distant tulip
#

huh?

shy leaf
#

huh?

distant tulip
#

it is not beta in the preview

#

meaning it will be stable next update

shy leaf
#

i mean

#

its not in stable API right

shy leaf
distant tulip
#

no

#

stable in the preview

shy leaf
#

welp ty for telling

#

it sucks when everything i need is in next update pensive_cry

distant tulip
#

i don't see why not use beta api
unless it is for marketplace

shy leaf
#

or have a chance to break apart

distant tulip
glacial widget
#

Is there a way to get the block location of a playerInteractWithBlock

#

?

distant tulip
#

block.location 🤷‍♂️

glacial widget
shy leaf
#

unless the stuff im using is bound to break in next update

#

i accidentally forgot my code was in 1.8.0 one day so i up'd the version to 1.11.0

#

didnt have any issue

distant tulip
#

up to you
personally i use what i can
all my addons were using beta api
but with time i will port the all to stable
i have 5 addons they were all beta but now just three of them

short cliff
#

How could I detect a specific durability value?

wary edge
short cliff
#

Thanks

glacial widget
#
for (const player of world.getAllPlayers()) {
                   const Money = getScore(player, "Money")

                          if (Money >= 400000) {
                           removeScore(400000, player, "Money")
                            world.structureManager.place("mystructure:pshop2", player.dimension, { ...player.location, y: player.location.y + 2})

                            const inventory = player.getComponent(`inventory`).container
                            const block = player.dimension.getBlock({ ...player.location, y: player.location.y + 2 })

                              player.playSound(`note.pling`, { pitch: 2 })

                            player.sendMessage("§l§dHCV KitPvP >> §l§aYou have purchased Tier 7 pickaxe")

                    } else if (Money < 400000) {

                        player.sendMessage("§l§dHCV KitPvP >> §l§4You do not have enough for a Tier 7 pickaxe")

                    }
                 }

Why when a player buys this i get one aswell

valid ice
#

You are doing a for loop for all players in the world, so it will run the code for all players.

glacial widget
valid ice
#

Don't use a loop

#

No reason to

glacial widget
valid ice
#

What's the context of your code?

glacial widget
valid ice
#

Like do you have a player class as a defined variable somewhere?

#

Consider opening a post for your code

valid ice
#

Yeah you have a player variable inside of the UI function already. No need to do a loop over every player unless you want to run code for every player.

gaunt salmonBOT
#

Latest NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Beta APIs NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Preview Latest NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Preview Beta APIs NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
spare fox
#

did you get it to work? I couldnt find it in the types?

#

It was posted here so shouldnt it be in 1.2.0-beta?

valid ice
#

It is in 1.2.0-beta, yes.

#

I got it working fine

spare fox
warm drum
#

how can i get the location infront of the player again?

valid ice
warm drum
#

getViewDirection()

#

Anyone has the math for that?

spare fox
#

oh, I think @granite badger's thing is outdated

valid ice
#

ye

spare fox
#

it should be using 1.21.2

spare fox
valid ice
spare fox
valid ice
#

They're just NPM types, and nothing was added between the versions

spare fox
valid ice
#

dunno

spare fox
valid ice
#

It's there in the 1.21.2 types

warm drum
#

Can anyone help?

glacial widget
# valid ice Yeah you have a player variable inside of the UI function already. No need to do...
export function removeScore(amount, target, objective) {
    if (!(target instanceof Player)) return;
    target.runCommand(`scoreboard players remove @s ${objective} ${amount}`);
  }
  export function getScore(target, objective) {
    try {
      target.runCommand(`scoreboard players add @s ${objective} 0`);
      return world.scoreboard.getObjective(objective).getScore(target);
    } catch {
      return 0;
    }
  }
const player = world.getAllPlayers()
const Money = getScore(player, "Money")

Does anyone know why its not picking up the objective?

valid ice
#

player is an array of players there

#

not an invididual player

neat hound
turbid oriole
neat hound
turbid oriole
#

XD

neat hound
#

It is a vector and I believe people may have put vector math classes in the resources... so maybe a discord search for vector or vector3 may bring up information or code snippits or convos from others.

turbid oriole
#

How it behaves.

neat hound
# turbid oriole Do you know how the general execution flow is executed?

not an expert, and some others may have better answers... but as far as event processing... I understand from watching this.. https://www.youtube.com/watch?v=eiC58R16hb8

turbid oriole
#

Do we have concurrency in Minecraft script? Without counting events.

neat hound
#

Then this may help understand how that works... https://www.youtube.com/watch?v=TlB_eWDSMt4&t=1783s At time mark 53:19 he talks about events and you can see how it can work concurrently . After watching that I understand how the subscribes work. Sorry if I am not getting the jest of your question. I suggest to anyone, watch the whole video..

Learn Node.js basics in 1 hour! ⚡ This beginner-friendly tutorial gets you coding fast.

🚀 Want to master Node.js?

✋ Stay connected:

▶ Play video
#

I think this explains the concurrency....

amber granite
#

If async

#

There are two flows at the same time

turbid oriole
amber granite
#

If there is asynchronous lines in ur code

turbid oriole
#

Oh yes, but "run" is concurrent with the main scope

amber granite
#

Yes

neat hound
#

They say they add it to the end of the current tick... I read that somewhere

#

JS is single threaded....

#

there is no real concurrency

amber granite
neat hound
#

async stil adds to end of current tick

amber granite
#

In JavaScript, "asynchronous" refers to operations that can be executed without blocking the main thread, allowing other operations to continue running while waiting for the asynchronous task to complete. This is particularly important for tasks that might take an indeterminate amount of time, such as fetching data from a server, reading files, or executing timers.

JavaScript handles asynchronous operations using several mechanisms:

  1. Callbacks: Functions that are passed as arguments to other functions and are executed after an operation is completed.

  2. Promises: Objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises provide .then() and .catch() methods to handle success and failure cases, respectively.

  3. Async/Await: A syntactic sugar built on top of Promises that allows writing asynchronous code in a synchronous-looking manner. It uses the async keyword to define an asynchronous function and the await keyword to pause the execution of the function until the Promise is resolved or rejected.

Here's a simple example of each:

Callbacks

function fetchData(callback) {
    setTimeout(() => {
        callback('Data loaded');
    }, 1000);
}

fetchData((data) => {
    console.log(data);
});

Promises

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Data loaded');
        }, 1000);
    });
}

fetchData().then((data) => {
    console.log(data);
});

Async/Await

async function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Data loaded');
        }, 1000);
    });
}

async function loadData() {
    const data = await fetchData();
    console.log(data);
}

loadData();

Using these asynchronous methods, JavaScript can perform tasks efficiently without freezing or slowing down the user inte

neat hound
#

well that first video I sent, goes over stuff like how this is working... micro tasks and such

remote oyster
fickle pulsar
#

can someone read my thread and reply to it there?

weary umbra
#

Just made a website where I can see how much lines js I used xD

unique dragon
fickle pulsar
#

i saw someone talking about it and saying yes

#

but im not sure

valid ice
fickle pulsar
#

so its constant in one world?

valid ice
#

Yes

fickle pulsar
#

ok

#

thanks

fast lark
#

where i can find all the emoji like this and copy them? LIKE THIS 

fast lark
wary edge
fast lark
#

i dont have any resource pack and i can use it

woven loom
#

you mean you want to kniw the unicode

fast lark
fickle pulsar
#

wait in my script console.log(message) is referenced to the node.js console

#

and it doesnt show up in my screen

#

can someone pls help

wary edge
fast lark
woven loom
# fast lark ?

the emoji u see are unicode char which u can copy, game renders it as emoji defined in rp

fast lark
fickle pulsar
#

nvm

spring dove
#

how do i teleport player to another dimension

#

without commands

#

like entity class

distant tulip
#

look into teleport options in the docs

#

probably entity.teleport(vector3,{dimension:dim})

spring dove
#

I think there's no dimension parameter

valid ice
#

it's in teleport options

spring dove
#

alr

simple zodiac
#

it wants teleport options and not a string

spring dove
#

so ..

simple zodiac
#

{}

spring dove
#

im not finding the correct documentation sorry

distant tulip
#
const dim = world.getDimension("minecraft:the_end")
entity.teleport(vector3,{dimension:dim})
spring dove
#

it tps me to the overworld

#

const dim = world.getDimension("minecraft:nether")
let user = message.substring(4).trim(); // THIS VARIABLE OBTAINS WHATEVER THAT IS AFTER THE .HELPOP
if(sender.hasTag('mod')){
system.run(() => {
sender.teleport({x: 0, y:64, z:0}, dim)
})
}
e.cancel = true;

remote oyster
distant tulip
remote oyster
#

{dimension: dim}

distant tulip
#

{dimension:dim}

spring dove
#

ah let me check

#

sender.teleport({x: 0, y:64, z:0}, {dimension:dim})

distant tulip
#

yeah

spring dove
#

it worked

#

ty

distant tulip
#

np

remote oyster
# spring dove ah let me check

Teleport Options requires an object with properties that exist, and you defining the properties accordingly. That object is the second parameter of the teleport method.

spring dove
#

i just wanted all this to close the chat

#

🫠

distant tulip
spring dove
#

i tried placing a portal block on player's feet but it only closes the inventory

distant tulip
#

you can just wait for the chat to close

spring dove
#

and the dimension changer its automatic

distant tulip
#

depend
but i like your idea tbh

spring dove
#

yeah imma send a video when i done with this

remote oyster
#

When you need that chat window to be closed just send a message to that player instructing them to close the window.

spring dove
#

This is actually not that bad, i dont like that there's a transition like that, but its so fast

remote oyster
#

You teleport to the void? Lol

#

Oh wait, 64

spring dove
#

nop, its a superflat world

remote oyster
#

I see.

#

You fell on an invisible platform?

spring dove
#

nop, flatworld first layers starts at -59

#

so i fell

remote oyster
#

Ah, then it was just stopping the coord at 37 because you accessed the menu.

remote oyster
#

Lol

valid ice
#

I'm assuming the transition may be longer for certain cases, no?

#

If it's always super short like that, that's actually a decent way to close menus

spring dove
remote oyster
#

So teleporting a player will close the window huh?

spring dove
#

but any way i have a event listener that can show the form as soon as you get into the overworld again

#

and for less resources i could use the end

spring dove
remote oyster
#

Because if that closes the window then that will be far better than any other method I have seen.

remote oyster
spring dove
#

mm

remote oyster
#

👀

valid ice
#

From what I can remember, it does not close any windows

remote oyster
spring dove
#

i just tested it

#

nop

remote oyster
#

Rip

spring dove
#

it doesnt close nothing

valid ice
#

Forms, and chat, stay open for that- I had to use closeForms for when teleporting

#

Can't do anything about chat tho

spring dove
subtle cove
#

End <=> overworld

spring dove
remote oyster
neat hound
remote oyster
valid ice
#

yeah

remote oyster
distant tulip
#

i hope we get chat close function before chatSend get stable

valid ice
#

Well.. there may be reasons why chatSend is still beta... so one can hope lol

distant tulip
#

custom commands?

valid ice
#

perhaps

#

Who knows

remote oyster
#

We already can implement our own custom commands.

valid ice
#

I do see custom commands as being registered in world initalize event, similar to how block & custom CCs are currently

distant tulip
# valid ice perhaps

maybe they will be like custom component
you register a command with all it parameter
chatSend should be just for messages

valid ice
#

Maybe the devs are still scratching their heads over the chat send bug that you found, Visual

remote oyster
distant tulip
#

what bug is that

spring dove
#

It worked

valid ice
distant tulip
#

huh? you can edit the actual message?

remote oyster
valid ice
#

#879773489601585244 message

distant tulip
#

that's wired

remote oyster
#

Was gonna share it here but you beat me to it.

#

I remember that issue. Been a while.

#

Wouldn't be surprised if they are still brainstorming that issue.

#

On the bright side, the issue seemed to be a rare occurrence. My idea of testing communication with encryption in mind is basically what stumbled across it. An accidental find.

distant tulip
#

but message property readonly, no?

neat hound
#

No it is not.. but that would fix it until they FIX it... and give it to us if they made readonly....

remote oyster
remote oyster
distant tulip
#

marked as readonly

neat hound
#

Oh the after is not readOnly

If they can release it in a way that is just for us to do custome commands that is what we care about

remote oyster
#

They will probably mess up my ability to accomplish end to end encryption in the process lol

neat hound
#

never mind both readonly.. swear I looked for that and now I see it

distant tulip
#

lol

neat hound
#

So who is intercepting chat.. and wtf is MC being used for that needs to be secret

remote oyster
neat hound
#

Too many secrets in the world... I don't agree with the encryption thingy... tell them to make a Roblox game that cost a lot to use and they can talk all they want in there...

#

MAybe the spy network can just make signs to communicate... or name stuff on the anvil...

remote oyster
neat hound
#

But anvils are expensive.. so they gotta grind

#

Yeah, don't want the hackers to know where I hid my diamonds...

remote oyster
neat hound
#

I know I know... but just seems.. like ... If ya gotta do that.. wrong game to play... well the players can be in a discord group and not talk in chat period... LOL if it is that serious

remote oyster
#

It was just one approach to combating the hackers. I think standing by and allowing the behavior is simply unacceptable and shouldn't be tolerated. Whether it be this game or any other game. The equivalence of that logic could equate to a coworker cheating you out of your paycheck and if you don't like it, then the wrong job to have so go find another job.

neat hound
#

No... it is just a matter of where you put the bandaid....

#

The ability to hack should be fixed...

#

not encrypt chat

remote oyster
neat hound
#

.. okay you do that, while I go kick my co-workers azz

valid ice
#

Don't be stealing their paycheck, now

neat hound
#

I will break fingers or chop off finger tips, see if you have the ability to steal after that.... hehehe... besides that is not a fair comparison in the seriousness of the issue. And would never happen.

#

Meanwhile, I wonder at peoples attempt to hide meaningless conversations in a game. To me, it means that it will be used to communicate other things that should not be talked about in a game. It is a gateway to... I don't have to say it... but you get the jest.

#

But to each their own... I do not care, do not play which such people....

remote oyster
#

It's a sad reality.

neat hound
#

I do applaud the attempt to do it. Most of us programmers like the challenge of doing the impossible.

remote oyster
#

Live and learn 😬

remote oyster
#

Had no idea it would trigger the moderators lol.

neat hound
#

Maybe you can put the message in a book/quill and deliver it, LOL

remote oyster
#

Sounds like a resource pack with Little Red Riding Hood sending out baskets to be delivered.

neat hound
#

sometimes when I cancel the event in the beforeEvents it does not work tho

remote oyster
#

I did wonder why they changed chatSend to read-only, but now I suppose it could have been that bug I reported.

#

Probably other reasons I'm sure.

neat hound
#

Well the account lock is serious and if people know about it, it can be exploited

remote oyster
#

This is true.

neat hound
#

was it the person who sent the message?

#

what if the world sent the message after captured and canceled, 3rd party, or amor stand?

#

the message has to make it to the server, post office, in order to be routed.. who is being hacked? sender, receiver, server?

#

so it is like a pgp/gpg file over the internet... probably... and you did it, cool...

#

but you have to encrypt on the client, right?

#

I better stay out of espionage...

remote oyster
deep yew
#

What would be a simple way to convert an Entity to a Player? (entityHitEntity event has Entity variable, I want it to be Player for the .name property)

neat hound
neat hound
remote oyster
neat hound
#

For that to work, make sure you JS import {Player} from...

remote oyster
#

^

neat hound
#

Alternatively, you can check for typeId = minecraft:player.. I've seen some do that, but I do the instance because I use JDoc and @ts-check

random flint
#

why use instanceof? Is it because of typings?

neat hound
#

Yes... if you are not using TS

#

it helps to avoid errors

#

after a while it becomes natural to want to use it.

remote oyster
#

I think I have an old demo video of me encrypting the messages...

#

Random... Thought

valid ice
#

instanceof does pull types, I assume that's why folks use it over checking typeId

#

Although you could cast types with jsdocs... not nearly as neat

neat hound
#

besides, too many languages right now... I just learned JS a few months ago, and got fluent redoing my regolith filter... and I am supposed to be getting deep into c#... TS was a no go for now.

remote oyster
#

Been a while since I touched C#. I wrote so many codes in C# for Android applications years ago.

neat hound
#

is there a 3rd party lib to emmulate JS? LOL... I am frustrated that so many things I want to do are not as simple as they are in JS

valid ice
#

I mean if you want there's probably something out there, where you take pictures of rocks placed on the ground and it translates to valid JS

remote oyster
#

Lol

neat hound
#

Even wish I could inject JS into T-Sql

#

love { }

granite badger
grand heart
#

how to get a random safe-to-spawn location in an area?

pale terrace
#

how can I create a potion bottle itemStack? since this item only can be obtained with "data"

pale terrace
pale terrace
#

There actually is a componentType called "minecraft:potion" but there is no information on how to assign an effect to it

summer walrus
#

help i'm getting the error
cannot read property 'setItem' of undefined

code:

const inventory = player.getComponent('minecraft:inventory')
inventory.setContainer.setItem(selectedSlotIndex, undefined);
pale terrace
#

its container, not setContainer

wary edge
pale terrace
summer walrus
#

now the error is selectedSlotIndex is undefined

neat hound
wary edge
pale terrace
summer walrus
#

not yet sorry i thought it was a thing for the inventory

pale terrace
#

Any other method to assign a data value to an itemStack?

wary edge
#

Nope

pale terrace
#

I guess I'll use commands

neat hound
#

Or... work on it, perfect it, so it is ready to go when it comes out of beta....

pale terrace
summer walrus
#

i'm in the last part now and i will attempt to get the enchantments of the item! 😄

neat hound
neat hound
shy leaf
#

how do i read an item's enchantments

#

the docs are quite a head scratcher

neat hound
# shy leaf how do i read an item's enchantments

get to the ItemStack Class
select the getComponent method
click on ItemComponentTypeMap interface
select class = ItemEnchantableComponent
(or go straight there, lol)
I bet there are some methods on that page....

#

It pays to poke around in the classes and see what is there.. oh the possibilities

shy leaf
#

hmm im using equippable component instead of itemStack

valid ice
#

Well that's fine, that returns an ItemStack class

neat hound
#

well, what is equipped is something from ItemStack... you can get to itemstack from there

shy leaf
#

thankfully

#

ty ill try smth

#

oh christ ItemEnchantableComponent has everything

neat hound
#

and if you do not find something in latest, remember to check beta, and then preview.. lots of new stuff commin' .... I think.... probably.. who knows... no one tells me anything

shy leaf
#

i was looking at the wrong one

valid ice
summer walrus
#

where did i go wrong? bao_foxxo_smile

player.getComponent('inventory').container.getSlot(player.selectedSlotIndex).getItem().getComponent('minecraft:enchantable');
#

don't mind the one line i wanna get it right first before destructuring

shy leaf
#

it can be hard to catch the error if those are all in one place (for me at least)

neat hound
#

what is the last error, then look back to one that shows the filename and line number of thise line

#

Here is what I know, from helping another.. getSlot is not happy if nothing there... use getItem to comfirm there.... where is your if ya gonna need some ifs... or ? thingies

summer walrus
#

turns out i was just doing something unnecessary, thanks anyways guys 😁

neat hound
#

yeah I see.... I had to do a double take on that line

#

whole middle part... and you may need to check hasComponent. just read the fine print of the methods, if it says it returns undefined... then fine, but if not, it may error if it is not valid.\

summer walrus
#

okk thank you nikki!!

near siren
#

How do you get entities that arent being loaded? player.dimension.getEntities seems like it doesnt

random flint
#

place a tickingarea

near siren
#

Isnt there a max to ticking areas though?

random flint
#

yes

near siren
#

I need a way that doesn't really have a limit ;-;

random flint
#

Why do u need to get the entity?

near siren
#

I need to be able to find the entity so I can teleport to it from far away

random flint
#

Teleport the player to the entity?

#

...Then just store the location Vector3 directly in dynamicProperty.

near siren
#

If you mean store the location in the player's dynamicproperties, I have multiple entities I would need to teleport to

#

And they're based on what the player picks

shy leaf
#

does the entities move or smth

near siren
#

Nope, could be described as teleporters

shy leaf
#

then i think you can use dynamic properties without issues

#

without entities even

random flint
#

Then it's more fitting to rely on dynamicProperty instead of entities as anchor points

random flint
near siren
#

Guess thats what I'm going to have to do

shy leaf
#

yeah and it should be less head-aching

random flint
#

There's a string limit for dynamicProperty.

I'll probably limit it to only 100 locations per property If you take into account additional data like description or more. (If you have it)

You could chunk the stringified JSON into multiple dynamic properties, and then parse it back later for a larger range.

near siren
#

Man..im going to have to rewrite a bunch of code

shy leaf
#

how many entities did you use for script

near siren
#

Placing a custom block spawns a custom entity for storing its data and opening a menu associated

shy leaf
near siren
somber onyx
#

how to recover dynamicproperty since getDynamicProperty is not aparament correct

near siren
#

getDynamicProperty() exactly?

somber onyx
#
world.beforeEvents.chatSend.subscribe((eventData) => {
    const player = eventData.player;
    const message = eventData.message;
//58    const homeLocation = getHome(player)
    switch(message) {
        case `!home`:
        if (homeLocation === undefined) {
            player.sendMessage("§cYou have not yet defined your home")
        }else {
            sender.teleport(homeLocation);
            player.sendMessage("§aYou have been teleported to your home successfully")
        }
        break;
        case "!sethome":
            if(homeLocation === undefined) {
                setHome(player)
                player.sendMessage("§aYour home has been successfully set")
            }else player.sendMessage("§cYou have already defined your home")
    }
})

function setHome(player) {
    player.setDynamicProperty("nano:home", player.location);
}

function getHome(player) {
//83    return player.getDynamicProperty("nano:home")
}
knotty plaza
#

const player = eventData.player; this is not correct

#

The player property in that event is called sender

somber onyx
#
world.beforeEvents.chatSend.subscribe((data) => {
    const sender = data.sender;
    const message = data.message

I changed the 3 first line

amber granite
#

What s the problem

#

No worries, because the greatest scripter that ever lived is here

#

Jk

somber onyx
#

it’s good by changing the 3 first line the script works

somber onyx
amber granite
#

@somber onyx ?

#

U mean an array?

somber onyx
somber onyx
amber granite
#

U want to put an array inside dynamic properties

somber onyx
#

if possible yes

amber granite
#

@somber onyx

#

You can use array of Vector3

#

Then stringify it

#

And put it in dynamic propreties

#

@somber onyx

somber onyx
#

yes I check documentation on internet

amber granite
#

Then that s all

#

Whenever player make new home

#

Let it push new location to than array

#

Then stringify it

#

And setIt in dp

somber onyx
#

thanks you

amber granite
#

Uw

somber onyx
# amber granite Uw
    if (item[0] == "!sethome") {
        const homeName = item[1]
        homeList.push(homeName)
        sender.setDynamicProperty(`${homeList}`);
        sender.setDynamicProperty(`${homeName}`, sender.location)
        sender.sendMessage("§a>>Your home has been successfully set")
    }
#

why it doesn’t work? the data is not recording correctly?

#

since the message is sent in the chat

random flint
#

homeList is most likely an array

#

ur trying to convert it into a string

somber onyx
#

I did that, yes

#
    const homeList = []
somber onyx
subtle cove
#
const homeList = JSON.parse(sender.getDynamicProperty("homes") ?? "{}")
homeList[homeName] = sender.location
sender.setDynamicProperty("homes", JSON.stringify(homeList))
#

!sethome home1

{
    "home1": { "x": 1, "y": 1, "z": 1 }, 
    "home2": { "x": 1, "y": 1, "z": 1 }
} ```
somber onyx
subtle cove
somber onyx
#

oh ok but the my code looks like a ca I know well these not finished but the for me the !sethome does not work

world.beforeEvents.chatSend.subscribe((data) => {
    const sender = data.sender;
    const message = data.message
    const item = message.split(" ")
    const homeList = JSON.parse(sender.getDynamicProperty("homes") ?? "{}")
    const homeLocation = getHome(sender)
    switch(message) {

        case "!help":
            sender.sendMessage(`§8Here is the list of commands: \n§8/sethome homeName: §7to define a home \n§8/home list / homeName: §7list to get a list of all these home, add to create a new home\n§8/delhome homeName: §7To remove a home`)
        break;
        case "!home":
            sender.sendMessage(">>§cIncomplete command !help")
                system.run(() => {
                    sender.teleport(homeLocation);
                    sender.sendMessage("§a>>You have been teleported to your home successfully")
                })
        break;

        case "!home list":
            sender.sendMessage(`§7>>Here is your home list: ${JSON.stringify(homeList)}`)
        break;

        case "!delhome":
            if (homeLocation === undefined) {
                sender.sendMessage("§c>>You do not own any home")
            }else {
                sender.setDynamicProperty("nano:home", )
                sender.sendMessage("§a>>Your home has been deleted successfully")
            }
        break;
    }

    if (item[0] == "!sethome") {
        const homeName = item[1]
        homeList[homeName] = sender.location
        sender.setDynamicProperty(JSON.stringify(homeList))
        sender.setDynamicProperty(`${homeList}`);
        sender.setDynamicProperty(`${homeName}`, sender.location)
        sender.sendMessage("§a>>Your home has been successfully set")
    }
})
subtle cove
#

Prob need a post for that

somber onyx
subtle cove
#

It's alr, I'm just too tired atm

somber onyx
#

just the !sethome for the rest I make myself out of it once I have understood the !sethome

somber onyx
amber granite
#

@somber onyx

world.beforeEvents.chatSend.subscribe((data) => {
    const sender = data.sender;
    const message = data.message.trim();
    const item = message.split(" ");
    const command = item[0];
    const homeName = item[1];
    const homeList = JSON.parse(sender.getDynamicProperty("homes") ?? "{}");

    switch (command) {
        case "!help":
            sender.sendMessage(`§8Here is the list of commands: \n§8/sethome homeName: §7to define a home \n§8/home list / homeName: §7list to get a list of all these homes, add to create a new home\n§8/delhome homeName: §7To remove a home`);
            break;

        case "!home":
            if (homeList[homeName]) {
                sender.teleport(homeList[homeName]);
                sender.sendMessage("§a>>You have been teleported to your home successfully");
            } else {
                sender.sendMessage("§c>>Home not found! Use !home list to see available homes.");
            }
            break;

        case "!home list":
            sender.sendMessage(`§7>>Here is your home list: ${JSON.stringify(homeList)}`);
            break;

        case "!delhome":
            if (homeList[homeName]) {
                delete homeList[homeName];
                sender.setDynamicProperty("homes", JSON.stringify(homeList));
                sender.sendMessage("§a>>Your home has been deleted successfully");
            } else {
                sender.sendMessage("§c>>Home not found!");
            }
            break;

        case "!sethome":
            if (homeName) {
                homeList[homeName] = sender.location;
                sender.setDynamicProperty("homes", JSON.stringify(homeList));
                sender.sendMessage("§a>>Your home has been successfully set");
            } else {
                sender.sendMessage("§c>>Please provide a home name.");
            }
            break;

        default:
            sender.sendMessage("§c>> list of commas.");
    }
});
somber onyx
tender ocean
#

how do i use getBlocks so that it returns all the blocks locations that match a specific type

#
const startLocation = {
  x: player.location.x + radius,
  y: player.location.y + radius,
  z: player.location.z + radius,
}
const endLocation = {
  x: player.location.x - radius,
  y: player.location.y - radius,
  z: player.location.z - radius,
}
const volume = new BlockVolume(startLocation, endLocation)
const blocks = player.dimension.getBlocks(volume, {includeTypes: ['minecraft:air']}, true)
console.warn(blocks[0]) ```this doesnt work
tender ocean
#

ohh yes it works thank you

somber onyx
valid ice
#

Seems to be- you can use Object.entries(homeList) to get all key, value pairs in the object, as an array

#

Which would return [["a", {x: number, y: number, z: number}], ["b", {x: number, y: number, z: number}]]

amber granite
#

Finally

glacial widget
#
//Made by xGAMEZAx#1241, do not claim this code as yours!

import { world, system, Player } from '@minecraft/server'
import { setTimeout, clearTimeout } from './index'

const combatCooldownMap = new Map();
world.afterEvents.entityHurt.subscribe((ev) => {
  const player = ev.damageSource.damagingEntity;
  const entity = ev.hurtEntity;
  if (entity instanceof Player) {
    player.addTag('incombat');
    entity.addTag('incombat');
    resetCombatCooldown(player);
    resetCombatCooldown(entity);
  }
});
world.afterEvents.playerSpawn.subscribe((ev) => {
  const player = ev.player;
  if (ev.initialSpawn) {
    const combatCooldown = combatCooldownMap.get(player);
    if (player.hasTag('incombat')) {
      if (combatCooldown) {
        clearTimeout(combatCooldown.timeout);
        combatCooldownMap.delete(player);
      }
      player.removeTag('incombat');
      player.kill();
      world.sendMessage(`§c§lAntiLog >> §r§e ${player.name} §cdied for getting out in combat!`)
    }
  } else {
    const combatCooldown = combatCooldownMap.get(player);
    player.removeTag('incombat');
    if (combatCooldown) {
      clearTimeout(combatCooldown.timeout);
      combatCooldownMap.delete(player);
    }
  }
});
function resetCombatCooldown(player) {
  const combatCooldown = combatCooldownMap.get(player);
  if (combatCooldown) {
    clearTimeout(combatCooldown.timeout);
  }
  const timeout = setTimeout(() => {
    player.removeTag('incombat');
    combatCooldownMap.delete(player);
  }, 30000);
  combatCooldownMap.set(player, { timeout });
}
system.runInterval(
  function scoreBP() {
    const players = world.getAllPlayers();
    for (let player of players) {
      let antilogCooldown = '';
      const combatCooldown = combatCooldownMap.get(player);
    if (combatCooldown) {
      let remainingSeconds = Math.ceil((combatCooldown.timeout._idleStart + combatCooldown.timeout._idleTimeout - Date.now()) / 1000);
      antilogCooldown = `§7${remainingSeconds}s`;
    }
  player.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§l§eYOUR REALM§r\n\n§fLog Cooldown: ${antilogCooldown}`);
    }
  }, 1);

Could someone help me with this, because it keep crashing the world am testing this in

glacial widget
distant tulip
# glacial widget

you are declaring function scoreBP() every tick
move it outside the runInterval scope and call it from inside

glacial widget
distant tulip
#

that's not at all what i said

true isle
#

Lmao

glacial widget
#

💀

#

well it now stops crashing

glacial widget
distant tulip
cinder shadow
#

any reason why the game somehow thinks I'm using the item on the gravel I'm standing on?

#

It's only at specific angles as well

distant tulip
cinder shadow
#

no

#

wait why is the selection box on the gravel

#

I'm not looking at it

#

It should be where my crosshair is

wary edge
cinder shadow
#

great

glacial widget
#

Could i pay someone to change smth for me

distant tulip
cinder shadow
#

yeah that's what I'm trying

#

I hate water

distant tulip
true isle
#

Does it use a specific pov?

glacial widget
solar dagger
#

Dude just make a post instead of paying for help

#

Majority of the people on here aren't worth your money

glacial widget
glacial widget
solar dagger
true isle
#

If they reply

solar dagger
#

Eventually someone will reply

glacial widget
#

alr thank you guys

solar dagger
#

Trust me, it's not worth your money

#

Let me take a look

glacial widget
#

imma make a post

cinder shadow
distant tulip
#

why dose the selection box even show?
is the item a block?

cinder shadow
#

because of what Sean said

#

it's for bridging

distant tulip
#

let me see if can do something

cinder shadow
#

eat gravel mojang

#
const playerLocation = player.location;
            const blockFromRay = player.dimension.getBlockFromRay({x:playerLocation.x, y:playerLocation.y + 1.4, z:playerLocation.z}, player.getViewDirection(), {includeLiquidBlocks: true})?.block;
            const blockFromRayId = blockFromRay.typeId;
            const blockLocation = blockFromRay.location;
            const blockFromRayDistance = Math.hypot(playerLocation.x - blockLocation.x, playerLocation.y - blockLocation.y, playerLocation.z - blockLocation.z) <= 7;
            const blockId = block.typeId
            const blockAboveId = block.above(1).typeId;
            world.sendMessage(`fromRayLocation ${JSON.stringify(blockFromRay.location)} fromRayId ${blockFromRay.typeId} distanceFromPlayer ${blockFromRayDistance}`)
            if(blockId == 'minecraft:water' || blockId == 'minecraft:flowing_water' || blockAboveId == 'minecraft:water' || blockAboveId == 'minecraft:flowing_water' || (blockFromRayId == 'minecraft:flowing_water' || blockFromRayId == 'minecraft:water' && blockFromRayDistance)) {}
#

I did it lmao

distant tulip
#
Dimension.prototype.getBlockFromRay = function(direction, location, maxSteps = 10, stepSize = 0.2) {
  for (let step = 0; step < maxSteps; step++) {
    location.x += direction.x * stepSize;
    location.y += direction.y * stepSize;
    location.z += direction.z * stepSize;
    
    const block = this.getBlock(location);
    if (block.typeId !== "minecraft:air") {
      return block;
    }
  }
  return null;
};
distant tulip
cinder shadow
#

yes, but it doesn't work how you would expect it to

#

includeLiquidBlocks means it will consider the liquid block as part of the Ray. HOWEVER, it will not work unless the ray is touching a solid block

#

there's honestly no reason for the block.typeId and block.above(1).typeId conditionals

#

getBlockFromRay covers everything

turbid oriole
#

Is there a limit of modifications per tick????

#

I was looking and in my script it only allows me 1 modification per tick I think. It blocks me from executing a third modification.

distant tulip
#

whats a "modification"

turbid oriole
#

Place blocks in the world

fallow rivet
#

Can anyone write me a code that makes it say "hello" when I right click on an apple?

fallow rivet
#

I forgot because I haven't dealt with the script for a long time.

glacial widget
glacial widget
glacial widget
#
import { Player, world, system } from "@minecraft/server";
fallow rivet
#

Ok

#

Thanks

glacial widget
#

np

fallow rivet
#

Are the versions of Minecraft server and Minecraft server UI modules important?

#

What is the difference between 1.0.0 and 1.12.0?

valid ice
#

Buncha stuff was added

#

And the version is very important

fallow rivet
#

I made it

valid ice
#

Version is always important

fallow rivet
#

Everything I do gets corrupted with every update.

valid ice
#

Well, that's the perils of using beta APIs

fallow minnow
#

must be bad scripts

#

ive never had a world corrupt because of beta api's

valid ice
#

I assume he just meant "stopped working"

fickle pulsar
#

does the fetch api work in behaviour packs for local files?

valid ice
#

no

fickle pulsar
#

ok

tacit sigil
#

Yo

#

I need help

glacial widget
#
// Script example for ScriptAPI
// Author: Jayly <https://github.com/JaylyDev>
// Project: https://github.com/JaylyDev/ScriptAPI
import { Player, world, system } from "@minecraft/server";
;
//Using map because typescript doesn't support prototype property declaration properly
const clicks = new Map();
world.afterEvents.entityHitBlock.subscribe(function ({ damagingEntity }) {
    if (!(damagingEntity instanceof Player))
        return;
    const clickInfo = { timestamp: Date.now() };
    const playerClicks = clicks.get(damagingEntity) || [];
    playerClicks.push(clickInfo);
    clicks.set(damagingEntity, playerClicks);
});
world.afterEvents.entityHitEntity.subscribe(function ({ damagingEntity }) {
    if (!(damagingEntity instanceof Player))
        return;
    const clickInfo = { timestamp: Date.now() };
    const playerClicks = clicks.get(damagingEntity) || [];
    playerClicks.push(clickInfo);
    clicks.set(damagingEntity, playerClicks);
});
/**
 * Get a player's clicks per second
 * @param player
 * @returns
 */
export function getPlayerCPS(player) {
    const currentTime = Date.now();
    const playerClicks = clicks.get(player) || [];
    const recentClicks = playerClicks.filter(({ timestamp }) => currentTime - 1000 < timestamp);
    clicks.set(player, recentClicks);
    return recentClicks.length;
}

system.runInterval(() => {
    for (const player of world.getPlayers()){
      player.onScreenDisplay.setActionBar(`§d§lCps: ${getPlayerCPS(player)}`)
    const cps = getPlayerCPS(player);
      if(getPlayerCPS(player)>14) {
        world.sendMessage(`${player.name} went over the Cps Limit ${getPlayerCPS(player)}`)
        player.runCommandAsync(`kick "${player.name}" Cps Limit ${getPlayerCPS(player)}`)
        player.playSound('note.bass');
      }
      // player.runCommandAsync(`scoreboard players set @s cps ${getPlayerCPS(player)}`)
      // {"text":"\n  • §dCPS§r: "},{"score":{"name":"*","objective":"cps"}}
    }
})
;

could someone help me with this, i wanna put the cps counter to scoreboard

fickle pulsar
#

use scoreboard manager @glacial widget not running commands async.

#

why cant i do {dimension: vanilladata.MinecraftDimensionTypes.Overworld} in teleport options tho

gaunt salmonBOT
#

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 0 errors.

Lint Result

ESLint results:

<REPL0>.js

40:11 error 'cps' is assigned a value but never used @typescript-eslint/no-unused-vars

median stream
#

Can we have signs with existing data like when you Ctrl + Pick a block it shows +DATA in it?

I'm planning on making something that would generate a pre-filled sign.

woven loom
#

i don't think so, maybe place a sign somewhere in the world first edit it destroy it then get its itemstack and place it in the inv

#

@median stream

abstract cave
#
import { Player, world } from "@minecraft/server";

world.afterEvents.entityHurt.subscribe(eventData => {
    const player = eventData.damageSource;
    const entity = eventData.hurtEntity;

    if (player instanceof Player) {
        player.sendMessage(
            "You hurt something, you get a buff");
    }

});
#

anyone know why this isnt working

#

im new to scripts and don't understand any of this, I'm just picking up bits of code and patching them together

wary edge
#

I really recommend reading the docs and using an IDE that has intellisense so you can install the type defs

abstract cave
fallow minnow
#

anyone have some examples of server net?

#

idk how to use it

granite badger
#

it’s bds only

fallow minnow
#

but, how would i connect said server to discord?

#

or some external stuff

woven loom
#

anyone got a way to cancel piatons

fallow minnow
#

well no

#

idk

#

isnt there an event

woven loom
#

yea but they changed the cancel thing

granite badger
fallow minnow
granite badger
#

that’s the most childish explanation

fallow minnow
#

then i need toddler explanation sadJoe

burnt remnant
#

youre welcome, thank me later

fallow minnow
#

COURAGE THE COWARDLY DOG

random flint
#

What are typings anyway?
-# — me with 20% randomized error on world load

subtle cove
#

For code projection

arctic pike
#

How can I detect when a custom item has been picked up?

shy leaf
#

you could either compare inventory or do checks on item entity

arctic pike
#

Ahh okay, thanks

crude ferry
#

How to play animation using scripting?

crude ferry
#

Meow meow thanks.

tiny tartan
#

just question, does playerInteractWithBlock is stable in preview 1.21.20

crude ferry
#

How to detect player dismounting from a entity?

glacial widget
#
import { world, system, Player, ItemStack, EquipmentSlot, World, } from '@minecraft/server';
import { ActionFormData, MessageFormData, ModalFormData } from "@minecraft/server-ui"; 

world.afterEvents.itemUse.subscribe((i) =>{
  let player = i.source
  const itemStack = i.itemStack
  if (itemStack.typeId == "minecraft:heart_of_the_sea") system.run(() => main(player))


function main() {
      const form = new ActionFormData()
      .title("§l§dModration Menu§r")
      .body("                  §l§aby Maxis")
      .button("§lkick")
      .button("§lwarn")
      .button("§lmute")
      .button(`§cExit Menu`);
    form.show(player).then(r => {
        if (r.selection == 0) kick(player)
        if (r.selection == 1) warn(player)
        if (r.selection == 2) mute(player)
    })
}

function kick() {
  new ModalFormData()
  .title("Kick Menu")
  .textField("", "Reason for Kick")
  .dropdown("Pick a member", player.map(player => player.name), 2)
  .submitButton("done")
  .show(player).then(r =>{
    let input = r.formValues[0]

    if (input) { 
      player.sendMessage(`${player.name} Has kicked a player for ${input}`); 
    } else {
      player.sendMessage(`${player.name} Has kicked a player for no reason.`);
    }
  })  
}

function warn() {
  new ModalFormData()
  .title("")
  .textField("", "Reason for warn" )
  .dropdown("Pick a player to warn", player.map(player => player.name), 2)
  .submitButton("done")
  .show(player).then(r =>{
    let input = r.formValues[0]

    if (input) { 
      player.sendMessage(`${player.name} Has warned a player for ${input}`); 
    } else {
      player.sendMessage(`${player.name} Has warned a player for no reason.`);
    }
  })
 }

 function mute() {
  new ModalFormData()
  .title("")
  .textField("", "Reason for mute")
  .dropdown("Pick a mute", player.map(player => player.name), 2)
  .submitButton("done")
  .show(player).then(r =>{
    let input = r.formValues[0]
    if (input) { 
      player.sendMessage(`${player.name} Has warned a player for ${input}`); 
    } else {
      player.sendMessage(`${player.name} Has warned a player for no reason.`);
    }
  })
 }

})

How does "player" have zero arugments?

cinder shadow
#

just pass in the player as a parameter

cinder shadow
#

I honestly have no idea how events handle variables, but I'm assuming they cannot be used by any functions declared in the same space

glacial widget
#

take the functions out the world events?

cinder shadow
#

yes

#

outside of the {})

glacial widget
nimble schooner
#

Is there a way to make custom dimensions?

glacial widget
valid ice
#

player is a Player class, I am assuming, but you are treating it as both a Player class and an array of Player classes- that is, Player[]

#

Can't call a .map() on a non-array

cinder shadow
tiny fable
#

Hello! is it possible to rename a item through scripts?

valid ice
#

yes it is!

glacial widget