#Script to detect blocks
1 messages Β· Page 1 of 1 (latest)
import { world, system } from "@minecraft/server"
let blocks = ["minecraft:iron_ore"]
let cmds = ["kill @p"]
world.beforeEvents.playerBreakBlock.subscribe(event => {
let block = event.block
let player = event.player
for (let i = 0; i < blocks.length; i++) {
if (block.typeId == blocks[i]) {
player.runCommandAsync(`${cmds[i]}`)
}
}
})
might work ( prob not lmao )
it basically kills the player that broke iron ores
@limpid echo thats not what im looking for each block has a different scoreboard command
whu
thats the point tho, u can assign different cmds to each block
import { world, system } from "@minecraft/server"
let blocks = ["minecraft:iron_ore", "minecraft:diamond_ore"]
let cmds = ["kill @p", "gamemode c"]
world.beforeEvents.playerBreakBlock.subscribe(event => {
let block = event.block
let player = event.player
for (let i = 0; i < blocks.length; i++) {
if (block.typeId == blocks[i]) {
player.runCommandAsync(`${cmds[i]}`)
}
}
})
- iron ore kills u when broke
- diamond ore gives u gm c when broke
a map or lookup object would be a much better choice than 2 arrays there
( still send how tho
)
import { world } from "@minecraft/server"
const BLOCKS = {
"minecraft:iron_ore": "kill @p"
}
world.afterEvents.playerBreakBlock.subscribe(({block, player}) => {
const command = BLOCKS[block.typeId]
if (command) player.runCommand(command)
})```
(also use after events where you can, before events are a bit finicky with state sometimes)

Ok but commands different per block
i usually call that a dictionary
i thought u meant smth different
just add more blocks to BLOCKS
Ohhh i see tyvm
lmao-
const BLOCKS = {
"minecraft:iron_ore": "kill @p",
"minecraft:stick": "gamemode creative",
}``` etc
js is a bit weird with its terminology, dicts as you might see them in other languages don't really exist
huhhh
how about multiple cmds per block 
objects are like Dictionary Proβ’, they do simple kv pairs like this but also can have methods and are the basis for functions and classes and literally everything that's not a primitive
it's a deep deep rabbit hole
huhhh
i just viewed it as json lmao-

it is just json
I dont know why people complicate it
what is?
literally everything that is not a primitive
huh
huhhhh
π€ they are a callable object
so how is this related to this project
idk you're the one that brought this up 
import { world } from "@minecraft/server"
const BLOCKS = {
"minecraft:iron_ore": ["kill @p", 'say "You broke iron ore!"'],
}
world.afterEvents.playerBreakBlock.subscribe(({block, player}) => {
const command = BLOCKS[block.typeId]
if (command) {
command.forEach(cmd => {
player.runCommand(cmd)
})
}
})```
import { world } from "@minecraft/server";
const BLOCKS = {
"minecraft:iron_ore": ['kill @p', 'say "You broke iron ore!"'],
};
world.afterEvents.playerBreakBlock.subscribe(({ block, player }) => {
BLOCKS[block.typeId]?.forEach(cmd => player.runCommand(cmd));
});
even smaller
change block.typeId to brokenBlockPermutation.type.id
no, this should work fine
what the fuc- 
omgmg i understand it now 
We'll see how he complains to you later that it doesn't work.
ye-

( i came up with the original use of block
)
only libs use brokenBlockPermutation
It will not work since the event occurs AFTER the block is broken, which means block.typeId will always be air
Honestly I'm reading this thread and my only thought has been how would a stick constitute as a block that can be broken π
Giggling to myself for no reason LMAO
cut me some slack ;-;
Happens to the best of us
but yeah serty is right about brokenblockpermutation, forgot to update it when i switched from before to after, my bad
π€ ye your right on that one
I have not used afterEvent for a block broken in a while

import { world } from "@minecraft/server";
const BLOCKS = {
"minecraft:dirt": ['kill @p', 'say "You broke dirt!"'],
};
world.afterEvents.playerBreakBlock.subscribe(({ brokenBlockPermutation, player }) => {
BLOCKS[brokenBlockPermutation.type.id]?.forEach(cmd => player.runCommand(cmd));
});
actually
you should be using runCommandAsync
why?
The script will run kill @p wait until thats done then run say "You broke dirt!"
with runCommandAsync
It will run both commands in the same tick
runcommand runs both commands there and then
It will wait until it is executed, yes, but all commands will be launched in one tick
async does the same, just queueing them for later (which will still be in the same tick)
Yes, but the rest of your script will wait until the command completes itself
/**
* @remarks
* Runs a synchronous command on the entity.
*
* This function can't be called in read-only mode.
*
* @param commandString
* The command string. Note: This should not include a leading
* forward slash.
* @returns
* A command result containing whether the command was
* successful.
* @throws This function can throw errors.
*
* {@link CommandError}
*
* {@link Error}
*/
runCommand(commandString: string): CommandResult;```
**Runs a synchronous command on the entity.**
'say "You broke dirt!"'``` Here you should be using player.sendMessage anyways
and here player.kill()
yes?
what's the problem with that
async isn't magically better
the work still has to be done somewhere
Yes, but instead of creating a "line" of things to do, it will run all at once
????
what you're describing there is exactly what async does, queues them to run in the future
Reread [my ](#1331670949443010620 message)
Clearly due to the usage of a smart word in the name, async solos (/j)
^
import { world } from "@minecraft/server";
const BLOCKS = {
"minecraft:dirt": {
action: (player) => {
player.kill();
player.sendMessage("You broke dirt!");
},
},
};
world.afterEvents.playerBreakBlock.subscribe(({ brokenBlockPermutation, player }) => {
BLOCKS[brokenBlockPermutation.type.id]?.action(player);
});
You shoudnt even be using runCommand anymore, when you have this
yeah but that's not what op asked for
also you don't need the inner action field, you could just have the type map to the method directly
"run a command", code is jujst a list of commands
Yeah the originally poster wanted it to run a scoreboard iirc
otherwise runcommand wouldn't exist in the first place
this is not 2022
you can use gametest api's for most things
import { world } from "@minecraft/server";
const BLOCKS = {
"minecraft:dirt": (player) => {
player.kill();
player.sendMessage("You broke dirt!");
},
};
world.afterEvents.playerBreakBlock.subscribe(({ brokenBlockPermutation, player }) => {
BLOCKS[brokenBlockPermutation.type.id]?.(player);
});
No one can say he wasn't dedicated
lmao-
@minor surge so what your saying is
wththt i have genuinely never seen dat one before- 
There is no difference between runCommand and runCommandAsync?
I just want to make sure
Ok, so runCommand has no performance nor speed difference?
Is that what you said?
So what did you say?
i said that there's no need to use async here
yeah, that's what it does
you imply here there is no speed difference
import { world, system } from "@minecraft/server";
const iterations = 100;
const commands = ['scoreboard objectives list'];
function testRunCommand(player) {
const startTime = Date.now();
for (let i = 0; i < iterations; i++) {
commands.forEach(cmd => {
try {
player.runCommand(cmd);
} catch (e) {
console.error(`Error executing command: ${cmd}`, e);
}
});
}
return Date.now() - startTime;
}
async function testRunCommandAsync(player) {
const startTime = Date.now();
for (let i = 0; i < iterations; i++) {
for (const cmd of commands) {
try {
await player.runCommandAsync(cmd);
} catch (e) {
console.error(`Error executing command: ${cmd}`, e);
}
}
}
return Date.now() - startTime;
}
world.beforeEvents.chatSend.subscribe(async (eventData) => {
const { message, sender: player } = eventData;
if (message.trim().toLowerCase() === "start") {
system.run(async () => {
eventData.cancel = true;
player.sendMessage("Starting performance test...");
const syncTime = testRunCommand(player);
player.sendMessage(`Synchronous runCommand took: ${syncTime} ms`);
const asyncTime = await testRunCommandAsync(player);
player.sendMessage(`Asynchronous runCommandAsync took: ${asyncTime} ms`);
player.sendMessage("Performance test completed.");
});
}
});
y there a entire argument now
( am so sorry- )
WHAT THE RUCUCUCU-
wthth i have been using async lmao i thought it was faster or smth-
am so depressed
That's an absurd level of spite LMAO
In this situtation its completely acceptable in using runCommandAsync, since you have more then one command
your benchmark is kinda meaningless, you're doing something completely arbitrary and introducing a hell of a load of overhead through promise resolution
Wrong lucy btw
???
my bad
i really don't understand what you're trying to achieve here, i'm not looking for an argument
You claim that runCommand is suitable, when it really isnt
Your giving bad performance advice
your own benchmark just proved that it runs 2 orders of magnitude faster
the reason your benchmark takes so long is because you schedule a command to run later, then wait for it before scheduling the next one
No, my benchmark proves what is written on the documentation, in which runCommandAsync queues the commands to run in that tick, making it so all 2(or max 128 commands) run all at once without waiting for the next one
that's not the case because you await each one
await = wait for completion
doing anything async inherently introduces a small performance overhead just from scheduling, it's not automatically better
import { world, system } from "@minecraft/server";
const iterations = 256;
const commands = ['scoreboard objectives list'];
function testRunCommand(player) {
const startTime = Date.now();
for (let i = 0; i < iterations; i++) {
commands.forEach(cmd => {
try {
player.runCommand(cmd);
} catch (e) {
console.error(`Error executing command: ${cmd}`, e);
}
});
}
return Date.now() - startTime;
}
async function testRunCommandAsync(player) {
const startTime = Date.now();
for (let i = 0; i < iterations; i++) {
for (const cmd of commands) {
try {
player.runCommandAsync(cmd);
} catch (e) {
console.error(`Error executing command: ${cmd}`, e);
}
}
}
return Date.now() - startTime;
}
world.beforeEvents.chatSend.subscribe(async (eventData) => {
const { message, sender: player } = eventData;
if (message.trim().toLowerCase() === "start") {
system.run(async () => {
eventData.cancel = true;
player.sendMessage("Starting performance test...");
const syncTime = testRunCommand(player);
player.sendMessage(`Synchronous runCommand took: ${syncTime} ms`);
const asyncTime = await testRunCommandAsync(player);
player.sendMessage(`Asynchronous runCommandAsync took: ${asyncTime} ms`);
player.sendMessage("Performance test completed.");
});
}
});```
that looks much more like what i'd expect
it looks so much faster because the commands haven't actually ran yet when the benchmark finishes timing, they've just been scheduled for later
that work will still happen
just later
so yes, in this situtation they should use runCommandAsync, since they are not awaiting for the command completion result
i'd still argue runcommand is better here, it also makes potential exception handling easier
promises will swallow exceptions unless explicitly caught
the perceived speedup gained here is so tiny and really doesn't serve to gain you anything that introducing that extra complexity isn't worth it
I dont see where the extra complexity is
Your not doing error handling with runCommand anyways, not sure why error handling is a priority for the case of not using AsyncRunCommand
i mean you yourself wrap your runcommandasync in a non-functional try catch
exceptions couold crop up anywhere in your code, why make them harder to track down when you could not?
player.runCommandAsync(cmd).catch(e => {
console.error(`Error executing command: ${cmd}`, e);
});```
The performance loss is less then anything
you'll still lose your stack trace with that
and is still just another thing that could very easily get left out
player.runCommandAsync(cmd).catch(e => {
console.error(`hey im here in x function: ${cmd}`, e);
});```
you still don't have a full stack trace there
in the original code they dont have error logging
which they don't need, because it's running synchronously
so i dont see why you should lose on your performance on somthing you wont even do
if an error gets thrown then it has the full stack already there
this doesn't meaningfully improve performance though
this is premature optimisation
Yes, so it literally does improve performance
not meaningfully
do you know what the word async actually means?
ποΈ
k i'll take that as a no
operations run without blocking the main execution thread
Which is what Ive been saying, if you have a list of commands like the original poster did, then you should use commandAsync so your done with the action as quick as possible
the same amount of work is still being done, whether it's done there and then in your event handler, or later on in the tick (or in a future tick etc)
it does not affect how quickly that thing happens
just when
If you spent 1 hour doing 1 task, and then spend another hour doing another task
you take 2 hours doing it?
yes
yes but that's parallelism, not asynchronous
different things
js does not support parallelism
not in this context at least
async just lets you different things while you wait for other things to happen (often entirely externally to the js runtime), it still can only do one thing at a time
if you have runCommand, it will wait until the runCommand is finished before running other things in your script(including allowing a beforeEvent) to finish
yes, that's correct
yes, so there is no reason to use runCommand
we're just going in circles here
there is literally nothing else in that script that needs to run, it blocking the rest of the event handler is fine
okay
I did not know this would cause a debate lol
So im still thinking the best is
import { world } from "@minecraft/server"
const BLOCKS = {
"minecraft:iron_ore": "kill @p"
}
world.afterEvents.playerBreakBlock.subscribe(({block, player}) => {
const command = BLOCKS[block.typeId]
if (command) player.runCommand(command)
})```
Or did you all debate on a better way
sorry about that, we got a little carried away :β)
thereβs a very slight correction that needs to be made to that
replace both instances of block with brokenBlockPermutation
so
import { world } from "@minecraft/server"
const BLOCKS = {
"minecraft:iron_ore": "kill @p"
}
world.afterEvents.playerBreakBlock.subscribe(({brokenBlockPermutation, player}) => {
const command = BLOCKS[brokenBlockPermutation.typeId]
if (command) player.runCommand(command)
})
@rare carbon i need help cause im having weird script version conflict errors
what errors?
Can i call ypu snd screen share this
1 sec i may have corrected that error just need to fix the script itself
Nope that script doesnt work
what does it do? do you see an error? anything at all?
Nothing
there are infinite things it could be doing, narrowing it down to βnot workingβ leaves us with infinity - 1 options :P
So first off i changed it to just say hi
But it doesnt throw an error it acts like normal minecraft
Are you sure the script is even running?
Use an interval giving out a console.error message
Not 100%
But it should
Okay run the log then to see if your file is running properly
Is it console.log or a dif syntax
I would use console.error()
import { world } from "@minecraft/server"
const BLOCKS = {
"minecraft:iron_ore": "say hi"
}
world.afterEvents.playerBreakBlock.subscribe(({ brokenBlockPermutation, player }) => {
const command = BLOCKS[brokenBlockPermutation.typeId]
if (command) player.runCommand(command)
})
function test() {
console.error("its running");
}
setInterval(test, 5)
so umm thats how normal java script does it is it different here
@lament nymph
@rare carbon
setInterval is a web api and doesn't work here
oh whats the minecraft way to do it
it's system.runInterval
the time is measured in ticks, system is imported from @minecraft/server
do i need to import systems
yep
although the fact you're getting errors means that your script is running, which is a good sign
import { system,world } from "@minecraft/server"
const BLOCKS = {
"minecraft:iron_ore": "say hi"
}
world.afterEvents.playerBreakBlock.subscribe(({ brokenBlockPermutation, player }) => {
const command = BLOCKS[brokenBlockPermutation.typeId]
if (command) player.runCommand(command)
})
function test() {
console.error("its running");
}
system.runInterval(test, 5)
yuo so its working but the breaking blocks is not
what happens if you log the value of command in the event handler?
It says command is not defined
where in the event handler did you put it?
Thats what it logs
it needs to be below the first line, const command = ...
what did it log?
import { system, world } from "@minecraft/server"
const BLOCKS = {
"minecraft:iron_ore": "say hi"
}
world.afterEvents.playerBreakBlock.subscribe(({ brokenBlockPermutation, player }) => {
const command = BLOCKS[brokenBlockPermutation.typeId]
function test() {
console.error(command);
}
system.runInterval(test, 5)
if (command) player.runCommand(command)
})
like that or am i mistaken i feel thats not right tho
you've now got two functions intersecting eachother
you can remove the interval stuff, we know it's running now
World after event works but command is undefined
ok that's good
well not good but at least we know what's going wrong now
can you log brokenBlockPermutation.typeId too?
oh hang on i know why
replace brokenBlockPermutation.typeId with brokenBlockPermutation.type.id
we've had quite a time in here :')
wthth ( am so sorry? )
we went on a bit of a magical off-topic adventure discussing the intricacies of async command dispatching
but we're back on topic now
Still undefined
can you send your complete code?
import { system, world } from "@minecraft/server"
const BLOCKS = {
"minecraft:iron_ore": "say hi"
}
world.afterEvents.playerBreakBlock.subscribe(({ brokenBlockPermutation, player }) => {
const command = BLOCKS[brokenBlockPermutation.type.Id]
if (command) player.runCommand(command)
console.error(command);
})
function test() {
}
It worked
yay!
ππππ€π€π€
Just now the scripting error shows the right stuff
hey that's progress
what's the error now? is it just an issue from the command itself?
i literally watched like a entire anime and this problem is still going on-
ππ€π€π€
Its just the scripting error i put in
Nvm it runs
But say hi for some reason wont show up in chat
When i change it to tp me 5 blocks in the air it works but it wont be nice and say hi to me
Omfg im an idiot
I toggled chat off
πππ
Ty all so much i do have another question
If i want to change a block to req a certain scoreboard to drop how do i do that
wym drop-
Like i want it so if say you want to cut a birch tree but wood cutting is only 5 it wont let you
Ill also need to make it req a hatchet no more chad punching trees
π€π€π€
Huh
that's quite a jump in complexity there
do you mean it like you want it to cancel and not let you break the block?
ππππ€π€π€

It doesnt matter as long as they cant get the block without the correct level
that's a pretty normal thing to do
the tldr is listen to https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/playerbreakblockbeforeevent?view=minecraft-bedrock-stable and cancel it if they can't break it
but like dat would mean u gotta possibly switch back to a before event-
Btw i dont mind if i need to go in and dobeach blocks json manually
yeah?
this is what before events are for :P
okay
i just thought like uhh
u spent like possibly 3 hour on dis-
and like-
it being scarpped just like dat-

Why cant i just change its loot table
we're solving a different problem now
okay
i'm not experienced enough with behaviour packs to really help with this kinda stuff, sorry :(
i am a script girlie and not much else
Middy we solved the first issue its not scrapped
what is going on here
Onto another issue about making a way to not be able to get a block if your scoreboard is not high enough
sorry to just but in here. but how would i make this run more than 1 command?
you need to get the player's scoreboard value and do an if statement to see if they meet those requirements
yeah that basically
listen to the event i linked earlier, check the scoreboard, if their level isn't high enough then cancel
just make the commands an array of commands and run them each in a for-of loop
thanks
Is anyone who knows this able to vc or will be able to vc later
Ai is such an amazing time saver
lmao-
Im having it duplicate and edit another file
120 line file in minutes i cant complain
import {world} from '@minecraft/server';
const oreTypes = [
{ blockId: "minecraft:iron_ore", command: "say iron ore", requiredPlayerLvl: 10, increaseXpAmount: 5 },
{ blockId: "minecraft:gold_ore", command: "say gold ore", requiredPlayerLvl: 20, increaseXpAmount: 10},
];
world.beforeEvents.playerBreakBlock.subscribe(({player, block, cancel}) => {
const getPlayerLevel = world.scoreboard.getObjective('playerLevel');
const playerLevelExp = world.scoreboard.getObjective('playerLevelExp');
if (!getPlayerLevel || !playerLevelExp) return;
const lvl = getPlayerLevel.getScore(player) as number;
const xp = playerLevelExp.getScore(player) as number;
for (const ore of oreTypes) {
if (block.typeId === ore.blockId) {
if (lvl < ore.requiredPlayerLvl) {
console.error(`breaking block ${ore.blockId} requires level ${ore.requiredPlayerLvl}`);
cancel = true;
} else {
playerLevelExp.setScore(player, xp + ore.increaseXpAmount);
}
}
}
});
this should work. Try it out
@dark olive
i have functions doing the levels the command i was going to run was the scoreboard command to set xp
@lament nymph and idk whats to change can we voice chat
I'm not available to Vc
that method may run into an issue where different blocks give dif skills xp such as logs give wc xp req wc ores give mining xp req mining
I just gave you an example. It's up to you to figure out the rest
idk how to edit that to do multiple skills is that to replace the other 1 i have
@lament nymph is there a dif way to do that since the way i have it already set up makes the way you did it confuse me
import { world } from "@minecraft/server";
const BLOCKS = {
"minecraft:dirt": ['kill @p', 'say "You broke dirt!"'],
};
world.afterEvents.playerBreakBlock.subscribe(({ brokenBlockPermutation, player }) => {
BLOCKS[brokenBlockPermutation.type.id]?.forEach(cmd => player.runCommand(cmd));
});```
Ima post my other js question in another chat then
thank you
