更新至1.21.50.24
Some checks failed
Deploy Original / deploy (push) Has been cancelled

This commit is contained in:
ProjectXero 2024-10-18 10:42:28 +08:00
parent 0c5e335b27
commit 7dcf6b8c54
No known key found for this signature in database
GPG Key ID: 5B1AA72F4425593E
173 changed files with 2231 additions and 1154 deletions

View File

@ -9,7 +9,7 @@
"@minecraft/server-gametest": "beta",
"@minecraft/server-net": "beta",
"@minecraft/server-ui": "beta",
"@minecraft/vanilla-data": "1.21.50-preview.20"
"@minecraft/vanilla-data": "preview"
},
"overrides": {
"@minecraft/debug-utilities": {

View File

@ -1,25 +1,20 @@
import { Dimension } from '@minecraft/server';
import { DimensionLocation } from "@minecraft/server";
// Having this command:
function blockConditional(targetLocation: DimensionLocation) {
targetLocation.dimension
.getEntities({
type: "fox",
})
.filter((entity) => {
const block = targetLocation.dimension.getBlock({
x: entity.location.x,
y: entity.location.y - 1,
z: entity.location.z,
});
// execute as @e[type=fox] positioned as @s if block ^ ^-1 ^ stone run summon salmon
// Equivalent scripting code would be:
function spawnFish(dimension: Dimension) {
dimension
.getEntities({
type: 'fox',
})
.filter(entity => {
const block = dimension.getBlock({
x: entity.location.x,
y: entity.location.y - 1,
z: entity.location.z,
});
return block !== undefined && block.matches('minecraft:stone');
})
.forEach(entity => {
dimension.spawnEntity('salmon', entity.location);
});
return block !== undefined && block.matches("minecraft:stone");
})
.forEach((entity) => {
targetLocation.dimension.spawnEntity("salmon", entity.location);
});
}

View File

@ -1,29 +0,0 @@
import { world, EntityQueryOptions } from '@minecraft/server';
// Having this command:
// execute as @e[has_property={property=propId}]
// Equivalent scripting code would be:
function findEntitiesHavingAProperty(propId: string) {
const queryOption: EntityQueryOptions = {
propertyOptions: [{ propertyId: propId }]
};
const overworld = world.getDimension('overworld');
const entities = overworld.getEntities(queryOption);
}
// Having this command:
// execute as @e[has_property={propId=propValue}]
// Equivalent scripting code would be:
function findEntitiesHavingPropertyEqualsTo(propId: string, propValue: boolean | number | string) {
const queryOption: EntityQueryOptions = {
propertyOptions: [{ propertyId: propId, value: { equals: propValue } }]
};
const overworld = world.getDimension('overworld');
const entities = overworld.getEntities(queryOption);
}

View File

@ -1,22 +1,17 @@
import { Dimension } from '@minecraft/server';
import { DimensionLocation } from "@minecraft/server";
// Having this command:
function playSoundChained(targetLocation: DimensionLocation) {
const targetPlayers = targetLocation.dimension.getPlayers();
const originEntities = targetLocation.dimension.getEntities({
type: "armor_stand",
name: "myArmorStand",
tags: ["dummyTag1"],
excludeTags: ["dummyTag2"],
});
// execute as @e[type=armor_stand,name=myArmorStand,tag=dummyTag1,tag=!dummyTag2] run playsound raid.horn @a
// Equivalent scripting code would be:
function playSounds(dimension: Dimension) {
const targetPlayers = dimension.getPlayers();
const originEntities = dimension.getEntities({
type: 'armor_stand',
name: 'myArmorStand',
tags: ['dummyTag1'],
excludeTags: ['dummyTag2'],
});
originEntities.forEach(entity => {
targetPlayers.forEach(player => {
player.playSound('raid.horn');
});
originEntities.forEach((entity) => {
targetPlayers.forEach((player) => {
player.playSound("raid.horn");
});
});
}

View File

@ -1,22 +0,0 @@
import { Dimension } from '@minecraft/server';
// Having this command:
// execute as @e[type=armor_stand,name=myArmorStand,tag=dummyTag1,tag=!dummyTag2] run tellraw @a { "rawtext": [{"translate": "hello.world" }] }
// Equivalent scripting code would be:
function sendMessagesToPlayers(dimension: Dimension) {
const targetPlayers = dimension.getPlayers();
const originEntities = dimension.getEntities({
type: 'armor_stand',
name: 'myArmorStand',
tags: ['dummyTag1'],
excludeTags: ['dummyTag2'],
});
originEntities.forEach(entity => {
targetPlayers.forEach(player => {
player.sendMessage({ rawtext: [{ translate: 'hello.world' }] });
});
});
}

View File

@ -1,21 +1,17 @@
import { Dimension, world } from '@minecraft/server';
import { world, DimensionLocation } from "@minecraft/server";
// Having these commands:
// scoreboard objectives add scoreObjective1 dummy
// scoreboard players set @e[type=armor_stand,name=myArmorStand] scoreObjective1 -1
// Equivalent scripting code would be:
function setScores(dimension: Dimension) {
const objective = world.scoreboard.addObjective('scoreObjective1', 'dummy');
dimension
.getEntities({
type: 'armor_stand',
name: 'myArmorStand',
})
.forEach(entity => {
if (entity.scoreboardIdentity !== undefined) {
objective.setScore(entity.scoreboardIdentity, -1);
}
});
function setScoreboardChained(
targetLocation: DimensionLocation
) {
const objective = world.scoreboard.addObjective("scoreObjective1", "dummy");
targetLocation.dimension
.getEntities({
type: "armor_stand",
name: "myArmorStand",
})
.forEach((entity) => {
if (entity.scoreboardIdentity !== undefined) {
objective.setScore(entity.scoreboardIdentity, -1);
}
});
}

View File

@ -1,26 +1,21 @@
import { Dimension } from '@minecraft/server';
import { DimensionLocation } from "@minecraft/server";
// Having this command:
// execute as @e[type=armor_stand] run execute as @a[x=0,y=-60,z=0,c=4,r=15] run summon pig ~1 ~ ~
// Equivalent scripting code would be:
function spawnPigs(dimension: Dimension) {
const armorStandArray = dimension.getEntities({
type: 'armor_stand',
});
const playerArray = dimension.getPlayers({
location: { x: 0, y: -60, z: 0 },
closest: 4,
maxDistance: 15,
});
armorStandArray.forEach(entity => {
playerArray.forEach(player => {
dimension.spawnEntity('pig', {
x: player.location.x + 1,
y: player.location.y,
z: player.location.z,
});
});
function summonMobChained(targetLocation: DimensionLocation) {
const armorStandArray = targetLocation.dimension.getEntities({
type: "armor_stand",
});
const playerArray = targetLocation.dimension.getPlayers({
location: { x: 0, y: -60, z: 0 },
closest: 4,
maxDistance: 15,
});
armorStandArray.forEach((entity) => {
playerArray.forEach((player) => {
targetLocation.dimension.spawnEntity("pig", {
x: player.location.x + 1,
y: player.location.y,
z: player.location.z,
});
});
});
}

View File

@ -1,21 +0,0 @@
import { Player } from '@minecraft/server';
import { ActionFormData, ActionFormResponse } from '@minecraft/server-ui';
function askFavoriteMonth(player: Player) {
const form = new ActionFormData()
.title('Months')
.body('Choose your favorite month!')
.button('January')
.button('February')
.button('March')
.button('April')
.button('May');
form.show(player).then((response: ActionFormResponse) => {
if (response.selection === 3) {
player.sendMessage('I like April too!');
} else {
player.sendMessage('Nah, April is the best.');
}
});
}

View File

@ -1,7 +1,9 @@
import { DimensionLocation, BlockPermutation } from '@minecraft/server';
import { MinecraftBlockTypes } from '@minecraft/vanilla-data';
import { BlockPermutation, DimensionLocation } from "@minecraft/server";
import { Vector3Utils } from "@minecraft/math";
import { MinecraftBlockTypes } from "@minecraft/vanilla-data";
const allWoolBlocks: string[] = [
function addBlockColorCube(targetLocation: DimensionLocation) {
const allWoolBlocks: string[] = [
MinecraftBlockTypes.WhiteWool,
MinecraftBlockTypes.OrangeWool,
MinecraftBlockTypes.MagentaWool,
@ -18,20 +20,20 @@ const allWoolBlocks: string[] = [
MinecraftBlockTypes.GreenWool,
MinecraftBlockTypes.RedWool,
MinecraftBlockTypes.BlackWool,
];
];
const cubeDim = 7;
const cubeDim = 7;
function placeRainbowCube(location: DimensionLocation) {
let colorIndex = 0;
for (let x = 0; x <= cubeDim; x++) {
for (let y = 0; y <= cubeDim; y++) {
for (let z = 0; z <= cubeDim; z++) {
colorIndex++;
location.dimension
.getBlock({ x: location.x + x, y: location.y + y, z: location.z + z })
?.setPermutation(BlockPermutation.resolve(allWoolBlocks[colorIndex % allWoolBlocks.length]));
}
}
let colorIndex = 0;
for (let x = 0; x <= cubeDim; x++) {
for (let y = 0; y <= cubeDim; y++) {
for (let z = 0; z <= cubeDim; z++) {
colorIndex++;
targetLocation.dimension
.getBlock(Vector3Utils.add(targetLocation, { x, y, z }))
?.setPermutation(BlockPermutation.resolve(allWoolBlocks[colorIndex % allWoolBlocks.length]));
}
}
}
}

View File

@ -0,0 +1,22 @@
import { world, BlockPermutation, BlockSignComponent, BlockComponentTypes, DimensionLocation } from "@minecraft/server";
import { MinecraftBlockTypes } from "@minecraft/vanilla-data";
function addSign(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
const players = world.getPlayers();
const dim = players[0].dimension;
const signBlock = dim.getBlock(targetLocation);
if (!signBlock) {
log("Could not find a block at specified location.");
return -1;
}
const signPerm = BlockPermutation.resolve(MinecraftBlockTypes.StandingSign, { ground_sign_direction: 8 });
signBlock.setPermutation(signPerm);
const signComponent = signBlock.getComponent(BlockComponentTypes.Sign) as BlockSignComponent;
signComponent?.setText(`Basic sign!\nThis is green on the front.`);
}

View File

@ -0,0 +1,22 @@
import { world, BlockPermutation, BlockSignComponent, BlockComponentTypes, DimensionLocation } from "@minecraft/server";
import { MinecraftBlockTypes } from "@minecraft/vanilla-data";
function addTranslatedSign(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
const players = world.getPlayers();
const dim = players[0].dimension;
const signBlock = dim.getBlock(targetLocation);
if (!signBlock) {
log("Could not find a block at specified location.");
return -1;
}
const signPerm = BlockPermutation.resolve(MinecraftBlockTypes.StandingSign, { ground_sign_direction: 8 });
signBlock.setPermutation(signPerm);
const signComponent = signBlock.getComponent(BlockComponentTypes.Sign) as BlockSignComponent;
signComponent?.setText({ translate: "item.skull.player.name", with: [players[0].name] });
}

View File

@ -1,35 +1,28 @@
// A function the creates a sign at the specified location with text on both sides and dye colors
import {
DimensionLocation,
BlockPermutation,
BlockSignComponent,
BlockComponentTypes,
DyeColor,
SignSide,
} from '@minecraft/server';
import { MinecraftBlockTypes } from '@minecraft/vanilla-data';
import { BlockPermutation, BlockSignComponent, SignSide, DyeColor, BlockComponentTypes, DimensionLocation } from "@minecraft/server";
import { MinecraftBlockTypes } from "@minecraft/vanilla-data";
function createSignAt(location: DimensionLocation) {
const block = location.dimension.getBlock(location);
if (!block) {
console.warn('Could not find a block at specified location.');
return;
}
const signPerm = BlockPermutation.resolve(MinecraftBlockTypes.StandingSign, {
ground_sign_direction: 8,
});
block.setPermutation(signPerm);
const sign = block.getComponent(BlockComponentTypes.Sign);
function addTwoSidedSign(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
const signBlock = targetLocation.dimension.getBlock(targetLocation);
if (sign !== undefined) {
sign.setText(`Party Sign!\nThis is green on the front.`);
sign.setText(`Party Sign!\nThis is red on the back.`, SignSide.Back);
sign.setTextDyeColor(DyeColor.Green);
sign.setTextDyeColor(DyeColor.Red, SignSide.Back);
if (!signBlock) {
log("Could not find a block at specified location.");
return -1;
}
const signPerm = BlockPermutation.resolve(MinecraftBlockTypes.StandingSign, { ground_sign_direction: 8 });
// players cannot edit sign!
sign.setWaxed(true);
} else {
console.warn('Could not find a sign component on the block.');
}
signBlock.setPermutation(signPerm);
const signComponent = signBlock.getComponent(BlockComponentTypes.Sign) as BlockSignComponent;
if (signComponent) {
signComponent.setText(`Party Sign!\nThis is green on the front.`);
signComponent.setText(`Party Sign!\nThis is red on the back.`, SignSide.Back);
signComponent.setTextDyeColor(DyeColor.Green);
signComponent.setTextDyeColor(DyeColor.Red, SignSide.Back);
// players cannot edit sign!
signComponent.setWaxed(true);
} else {
log("Could not find sign component.");
}
}

View File

@ -1,19 +1,18 @@
// A function that applies damage and then heals the entity
import { Entity, EntityComponentTypes, system, world } from '@minecraft/server';
import { system, EntityHealthComponent, EntityComponentTypes, DimensionLocation } from "@minecraft/server";
import { MinecraftEntityTypes } from "@minecraft/vanilla-data";
function applyDamageAndHeal(entity: Entity) {
entity.applyDamage(19); // Many mobs have max damage of 20 so this is a near-death mob
function applyDamageThenHeal(
log: (message: string, status?: number) => void,
targetLocation: DimensionLocation
) {
const skelly = targetLocation.dimension.spawnEntity(MinecraftEntityTypes.Skeleton, targetLocation);
system.runTimeout(() => {
const health = entity.getComponent(EntityComponentTypes.Health);
if (health) {
world.sendMessage(`Entity health before heal: ${health.currentValue}`);
skelly.applyDamage(19); // skeletons have max damage of 20 so this is a near-death skeleton
health.resetToMaxValue();
world.sendMessage(`Entity after before heal: ${health.currentValue}`);
} else {
console.warn('Entity does not have health component');
}
}, 40); // Run in a few seconds (40 ticks)
system.runTimeout(() => {
const health = skelly.getComponent(EntityComponentTypes.Health) as EntityHealthComponent;
log("Skeleton health before heal: " + health?.currentValue);
health?.resetToMaxValue();
log("Skeleton health after heal: " + health?.currentValue);
}, 20);
}

View File

@ -0,0 +1,11 @@
import { DimensionLocation } from "@minecraft/server";
import { MinecraftEntityTypes } from "@minecraft/vanilla-data";
function applyImpulse(targetLocation: DimensionLocation) {
const zombie = targetLocation.dimension.spawnEntity(MinecraftEntityTypes.Zombie, targetLocation);
zombie.clearVelocity();
// throw the zombie up in the air
zombie.applyImpulse({ x: 0, y: 0.5, z: 0 });
}

View File

@ -1,18 +1,18 @@
import { EntityQueryOptions, DimensionLocation } from '@minecraft/server';
import { EntityQueryOptions, DimensionLocation } from "@minecraft/server";
function mobParty(targetLocation: DimensionLocation) {
const mobs = ['creeper', 'skeleton', 'sheep'];
function bounceSkeletons(targetLocation: DimensionLocation) {
const mobs = ["creeper", "skeleton", "sheep"];
// create some sample mob data
for (let i = 0; i < 10; i++) {
targetLocation.dimension.spawnEntity(mobs[i % mobs.length], targetLocation);
}
// create some sample mob data
for (let i = 0; i < 10; i++) {
targetLocation.dimension.spawnEntity(mobs[i % mobs.length], targetLocation);
}
const eqo: EntityQueryOptions = {
type: 'skeleton',
};
const eqo: EntityQueryOptions = {
type: "skeleton",
};
for (const entity of targetLocation.dimension.getEntities(eqo)) {
entity.applyKnockback(0, 0, 0, 1);
}
for (const entity of targetLocation.dimension.getEntities(eqo)) {
entity.applyKnockback(0, 0, 0, 1);
}
}

View File

@ -1,9 +1,28 @@
import { world, ButtonPushAfterEvent, system } from '@minecraft/server';
import { world, system, BlockPermutation, ButtonPushAfterEvent, DimensionLocation } from "@minecraft/server";
import { MinecraftBlockTypes } from "@minecraft/vanilla-data";
world.afterEvents.buttonPush.subscribe((buttonPushEvent: ButtonPushAfterEvent) => {
function buttonPushEvent(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
// set up a button on cobblestone
const cobblestone = targetLocation.dimension.getBlock(targetLocation);
const button = targetLocation.dimension.getBlock({
x: targetLocation.x,
y: targetLocation.y + 1,
z: targetLocation.z,
});
if (cobblestone === undefined || button === undefined) {
log("Could not find block at location.");
return -1;
}
cobblestone.setPermutation(BlockPermutation.resolve(MinecraftBlockTypes.Cobblestone));
button.setPermutation(BlockPermutation.resolve(MinecraftBlockTypes.AcaciaButton).withState("facing_direction", 1));
world.afterEvents.buttonPush.subscribe((buttonPushEvent: ButtonPushAfterEvent) => {
const eventLoc = buttonPushEvent.block.location;
world.sendMessage(
`Button push event at tick ${system.currentTick} Power:${buttonPushEvent.block.getRedstonePower()}`,
);
});
if (eventLoc.x === targetLocation.x && eventLoc.y === targetLocation.y + 1 && eventLoc.z === targetLocation.z) {
log("Button push event at tick " + system.currentTick);
}
});
}

View File

@ -0,0 +1,13 @@
import { DimensionLocation } from "@minecraft/server";
function checkBlockTags(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
// Fetch the block
const block = targetLocation.dimension.getBlock(targetLocation);
// check that the block is loaded
if (block) {
log(`Block is dirt: ${block.hasTag("dirt")}`);
log(`Block is wood: ${block.hasTag("wood")}`);
log(`Block is stone: ${block.hasTag("stone")}`);
}
}

View File

@ -1,21 +0,0 @@
import { DimensionLocation, EntityComponentTypes } from "@minecraft/server";
// Returns true if a feather item entity is within 'distance' blocks of 'location'.
function isFeatherNear(location: DimensionLocation, distance: number): boolean {
const items = location.dimension.getEntities({
location: location,
maxDistance: 20,
});
for (const item of items) {
const itemComp = item.getComponent(EntityComponentTypes.Item);
if (itemComp) {
if (itemComp.itemStack.typeId.endsWith('feather')) {
return true;
}
}
}
return false;
}

View File

@ -1,9 +0,0 @@
import { world } from "@minecraft/server";
// Fetch the block
const block = world.getDimension("overworld").getBlock({ x: 1, y: 2, z: 3 });
const blockPerm = block.getPermutation();
console.log(`Block is dirt: ${blockPerm.hasTag("dirt")}`);
console.log(`Block is wood: ${blockPerm.hasTag("wood")}`);
console.log(`Block is stone: ${blockPerm.hasTag("stone")}`);

View File

@ -1,8 +0,0 @@
import { world } from "@minecraft/server";
// Fetch the block
const block = world.getDimension("overworld").getBlock({ x: 1, y: 2, z: 3 });
console.log(`Block is dirt: ${block.hasTag("dirt")}`);
console.log(`Block is wood: ${block.hasTag("wood")}`);
console.log(`Block is stone: ${block.hasTag("stone")}`);

View File

@ -1,45 +0,0 @@
let leftLocation = test.worldLocation({ x: 2, y: 2, z: 2 }); // left chest location
let rightLocation = test.worldLocation({ x: 4, y: 2, z: 2 }); // right chest location
const chestCart = test.spawn("chest_minecart", { x: 6, y: 2, z: 2 });
let leftChestBlock = defaultDimension.getBlock(leftLocation);
let rightChestBlock = defaultDimension.getBlock(rightLocation);
leftChestBlock.setType(MinecraftBlockTypes.chest);
rightChestBlock.setType(MinecraftBlockTypes.chest);
const rightChestInventoryComp = rightChestBlock.getComponent("inventory");
const leftChestInventoryComp = leftChestBlock.getComponent("inventory");
const chestCartInventoryComp = chestCart.getComponent("inventory");
const rightChestContainer = rightChestInventoryComp.container;
const leftChestContainer = leftChestInventoryComp.container;
const chestCartContainer = chestCartInventoryComp.container;
rightChestContainer.setItem(0, new ItemStack(Items.apple, 10, 0));
test.assert(rightChestContainer.getItem(0).id === "apple", "Expected apple in right container slot index 0");
rightChestContainer.setItem(1, new ItemStack(Items.emerald, 10, 0));
test.assert(rightChestContainer.getItem(1).id === "emerald", "Expected emerald in right container slot index 1");
test.assert(rightChestContainer.size === 27, "Unexpected size: " + rightChestContainer.size);
test.assert(
rightChestContainer.emptySlotsCount === 25,
"Unexpected emptySlotsCount: " + rightChestContainer.emptySlotsCount
);
const itemStack = rightChestContainer.getItem(0);
test.assert(itemStack.id === "apple", "Expected apple");
test.assert(itemStack.amount === 10, "Expected 10 apples");
test.assert(itemStack.data === 0, "Expected 0 data");
leftChestContainer.setItem(0, new ItemStack(Items.cake, 10, 0));
rightChestContainer.transferItem(0, 4, chestCartContainer); // transfer the apple from the right chest to a chest cart
rightChestContainer.swapItems(1, 0, leftChestContainer); // swap the cake and emerald
test.assert(chestCartContainer.getItem(4).id === "apple", "Expected apple in left container slot index 4");
test.assert(leftChestContainer.getItem(0).id === "emerald", "Expected emerald in left container slot index 0");
test.assert(rightChestContainer.getItem(1).id === "cake", "Expected cake in right container slot index 1");

View File

@ -0,0 +1,72 @@
import { ItemStack, EntityInventoryComponent, BlockInventoryComponent, DimensionLocation } from "@minecraft/server";
import { MinecraftBlockTypes, MinecraftItemTypes, MinecraftEntityTypes } from "@minecraft/vanilla-data";
function containers(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
const xLocation = targetLocation; // left chest location
const xPlusTwoLocation = { x: targetLocation.x + 2, y: targetLocation.y, z: targetLocation.z }; // right chest
const chestCart = targetLocation.dimension.spawnEntity(MinecraftEntityTypes.ChestMinecart, {
x: targetLocation.x + 4,
y: targetLocation.y,
z: targetLocation.z,
});
const xChestBlock = targetLocation.dimension.getBlock(xLocation);
const xPlusTwoChestBlock = targetLocation.dimension.getBlock(xPlusTwoLocation);
if (!xChestBlock || !xPlusTwoChestBlock) {
log("Could not retrieve chest blocks.");
return;
}
xChestBlock.setType(MinecraftBlockTypes.Chest);
xPlusTwoChestBlock.setType(MinecraftBlockTypes.Chest);
const xPlusTwoChestInventoryComp = xPlusTwoChestBlock.getComponent("inventory") as BlockInventoryComponent;
const xChestInventoryComponent = xChestBlock.getComponent("inventory") as BlockInventoryComponent;
const chestCartInventoryComp = chestCart.getComponent("inventory") as EntityInventoryComponent;
const xPlusTwoChestContainer = xPlusTwoChestInventoryComp.container;
const xChestContainer = xChestInventoryComponent.container;
const chestCartContainer = chestCartInventoryComp.container;
if (!xPlusTwoChestContainer || !xChestContainer || !chestCartContainer) {
log("Could not retrieve chest containers.");
return;
}
xPlusTwoChestContainer.setItem(0, new ItemStack(MinecraftItemTypes.Apple, 10));
if (xPlusTwoChestContainer.getItem(0)?.typeId !== MinecraftItemTypes.Apple) {
log("Expected apple in x+2 container slot index 0", -1);
}
xPlusTwoChestContainer.setItem(1, new ItemStack(MinecraftItemTypes.Emerald, 10));
if (xPlusTwoChestContainer.getItem(1)?.typeId !== MinecraftItemTypes.Emerald) {
log("Expected emerald in x+2 container slot index 1", -1);
}
if (xPlusTwoChestContainer.size !== 27) {
log("Unexpected size: " + xPlusTwoChestContainer.size, -1);
}
if (xPlusTwoChestContainer.emptySlotsCount !== 25) {
log("Unexpected emptySlotsCount: " + xPlusTwoChestContainer.emptySlotsCount, -1);
}
xChestContainer.setItem(0, new ItemStack(MinecraftItemTypes.Cake, 10));
xPlusTwoChestContainer.transferItem(0, chestCartContainer); // transfer the apple from the xPlusTwo chest to a chest cart
xPlusTwoChestContainer.swapItems(1, 0, xChestContainer); // swap the cake from x and the emerald from xPlusTwo
if (chestCartContainer.getItem(0)?.typeId !== MinecraftItemTypes.Apple) {
log("Expected apple in minecraft chest container slot index 0", -1);
}
if (xChestContainer.getItem(0)?.typeId === MinecraftItemTypes.Emerald) {
log("Expected emerald in x container slot index 0", -1);
}
if (xPlusTwoChestContainer.getItem(1)?.typeId === MinecraftItemTypes.Cake) {
log("Expected cake in x+2 container slot index 1", -1);
}
}

View File

@ -0,0 +1,23 @@
import { world, system, DimensionLocation } from "@minecraft/server";
function countdown(targetLocation: DimensionLocation) {
const players = world.getPlayers();
players[0].onScreenDisplay.setTitle("Get ready!", {
stayDuration: 220,
fadeInDuration: 2,
fadeOutDuration: 4,
subtitle: "10",
});
let countdown = 10;
const intervalId = system.runInterval(() => {
countdown--;
players[0].onScreenDisplay.updateSubtitle(countdown.toString());
if (countdown == 0) {
system.clearRun(intervalId);
}
}, 20);
}

View File

@ -1,14 +0,0 @@
const form = new ActionFormData()
.title("Months")
.body("Choose your favorite month!")
.button("January")
.button("February")
.button("March")
.button("April")
.button("May");
form.show(players[0]).then((response) => {
if (response.selection === 3) {
dimension.runCommand("say I like April too!");
}
});

View File

@ -0,0 +1,6 @@
import { DimensionLocation } from "@minecraft/server";
function createExplosion(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
log("Creating an explosion of radius 10.");
targetLocation.dimension.createExplosion(targetLocation, 10);
}

View File

@ -1,13 +1,14 @@
// Creates an explosion of radius 15 that does not break blocks
import { DimensionLocation } from '@minecraft/server';
import { DimensionLocation } from "@minecraft/server";
import { Vector3Utils } from "@minecraft/math";
function createExplosions(location: DimensionLocation) {
// Creates an explosion of radius 15 that does not break blocks
location.dimension.createExplosion(location, 15, { breaksBlocks: false });
function createExplosions(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
const explosionLoc = Vector3Utils.add(targetLocation, { x: 0.5, y: 0.5, z: 0.5 });
// Creates an explosion of radius 15 that does not cause fire
location.dimension.createExplosion(location, 15, { causesFire: true });
log("Creating an explosion of radius 15 that causes fire.");
targetLocation.dimension.createExplosion(explosionLoc, 15, { causesFire: true });
// Creates an explosion of radius 10 that can go underwater
location.dimension.createExplosion(location, 10, { allowUnderwater: true });
const belowWaterLoc = Vector3Utils.add(targetLocation, { x: 3, y: 1, z: 3 });
log("Creating an explosion of radius 10 that can go underwater.");
targetLocation.dimension.createExplosion(belowWaterLoc, 10, { allowUnderwater: true });
}

View File

@ -0,0 +1,12 @@
import { DimensionLocation } from "@minecraft/server";
import { Vector3Utils } from "@minecraft/math";
function createNoBlockExplosion(
log: (message: string, status?: number) => void,
targetLocation: DimensionLocation
) {
const explodeNoBlocksLoc = Vector3Utils.floor(Vector3Utils.add(targetLocation, { x: 1, y: 2, z: 1 }));
log("Creating an explosion of radius 15 that does not break blocks.");
targetLocation.dimension.createExplosion(explodeNoBlocksLoc, 15, { breaksBlocks: false });
}

View File

@ -1,7 +0,0 @@
// Spawns an adult horse
import { DimensionLocation } from '@minecraft/server';
function spawnAdultHorse(location: DimensionLocation) {
// Create a horse and triggering the 'ageable_grow_up' event, ensuring the horse is created as an adult
location.dimension.spawnEntity('minecraft:horse<minecraft:ageable_grow_up>', location);
}

View File

@ -1,22 +0,0 @@
// A function the creates a sign at the specified location with the specified text
import { DimensionLocation, BlockPermutation, BlockComponentTypes } from '@minecraft/server';
import { MinecraftBlockTypes } from '@minecraft/vanilla-data';
function createSignAt(location: DimensionLocation) {
const signBlock = location.dimension.getBlock(location);
if (!signBlock) {
console.warn('Could not find a block at specified location.');
return;
}
const signPerm = BlockPermutation.resolve(MinecraftBlockTypes.StandingSign, { ground_sign_direction: 8 });
signBlock.setPermutation(signPerm); // Update block to be a sign
// Update the sign block's text
// with "Steve's Head"
const signComponent = signBlock.getComponent(BlockComponentTypes.Sign);
if (signComponent) {
signComponent.setText({ translate: 'item.skull.player.name', with: ['Steve'] });
}
}

View File

@ -1,27 +1,21 @@
import { BlockPermutation, DimensionLocation, world, ButtonPushAfterEvent, system } from '@minecraft/server';
import { system, BlockPermutation, DimensionLocation } from "@minecraft/server";
// A simple generator that places blocks in a cube at a specific location
// with a specific size, yielding after every block place.
function* blockPlacingGenerator(blockPerm: BlockPermutation, startingLocation: DimensionLocation, size: number) {
for (let x = startingLocation.x; x < startingLocation.x + size; x++) {
for (let y = startingLocation.y; y < startingLocation.y + size; y++) {
for (let z = startingLocation.z; z < startingLocation.z + size; z++) {
const block = startingLocation.dimension.getBlock({ x: x, y: y, z: z });
if (block) {
block.setPermutation(blockPerm);
}
yield;
}
}
}
function cubeGenerator(targetLocation: DimensionLocation) {
const blockPerm = BlockPermutation.resolve("minecraft:cobblestone");
system.runJob(blockPlacingGenerator(blockPerm, targetLocation, 15));
}
// When a button is pushed, we will place a 15x15x15 cube of cobblestone 10 blocks above it
world.afterEvents.buttonPush.subscribe((buttonPushEvent: ButtonPushAfterEvent) => {
const cubePos = buttonPushEvent.block.location;
cubePos.y += 10;
const blockPerm = BlockPermutation.resolve('minecraft:cobblestone');
system.runJob(blockPlacingGenerator(blockPerm, { dimension: buttonPushEvent.dimension, ...cubePos }, 15));
});
function* blockPlacingGenerator(blockPerm: BlockPermutation, startingLocation: DimensionLocation, size: number) {
for (let x = startingLocation.x; x < startingLocation.x + size; x++) {
for (let y = startingLocation.y; y < startingLocation.y + size; y++) {
for (let z = startingLocation.z; z < startingLocation.z + size; z++) {
const block = startingLocation.dimension.getBlock({ x: x, y: y, z: z });
if (block) {
block.setPermutation(blockPerm);
}
yield;
}
}
}
}

View File

@ -0,0 +1,24 @@
import { world, DimensionLocation } from "@minecraft/server";
function customCommand(targetLocation: DimensionLocation) {
const chatCallback = world.beforeEvents.chatSend.subscribe((eventData) => {
if (eventData.message.includes("cancel")) {
// Cancel event if the message contains "cancel"
eventData.cancel = true;
} else {
const args = eventData.message.split(" ");
if (args.length > 0) {
switch (args[0].toLowerCase()) {
case "echo":
// Send a modified version of chat message
world.sendMessage(`Echo '${eventData.message.substring(4).trim()}'`);
break;
case "help":
world.sendMessage(`Available commands: echo <message>`);
break;
}
}
}
});
}

View File

@ -1,9 +0,0 @@
const chatCallback = World.beforeEvents.chatSend.subscribe((eventData) => {
if (eventData.message.includes("cancel")) {
// Cancel event if the message contains "cancel"
eventData.canceled = true;
} else {
// Modify chat message being sent
eventData.message = `Modified '${eventData.message}'`;
}
});

View File

@ -1,18 +0,0 @@
// Gives a player a half-damaged diamond sword
import { ItemStack, Player, ItemComponentTypes, EntityComponentTypes } from '@minecraft/server';
import { MinecraftItemTypes } from '@minecraft/vanilla-data';
function giveHurtDiamondSword(player: Player) {
const hurtDiamondSword = new ItemStack(MinecraftItemTypes.DiamondSword);
const durabilityComponent = hurtDiamondSword.getComponent(ItemComponentTypes.Durability);
if (durabilityComponent !== undefined) {
durabilityComponent.damage = durabilityComponent.maxDurability / 2;
}
const inventory = player.getComponent(EntityComponentTypes.Inventory);
if (inventory === undefined || inventory.container === undefined) {
return;
}
inventory.container.addItem(hurtDiamondSword);
}

View File

@ -1,7 +1,9 @@
import { system, world } from '@minecraft/server';
import { world, system, DimensionLocation } from "@minecraft/server";
const intervalRunIdentifier = Math.floor(Math.random() * 10000);
function every30Seconds(targetLocation: DimensionLocation) {
const intervalRunIdentifier = Math.floor(Math.random() * 10000);
system.runInterval(() => {
world.sendMessage('This is an interval run ' + intervalRunIdentifier + ' sending a message every 30 seconds.');
}, 600);
system.runInterval(() => {
world.sendMessage("This is an interval run " + intervalRunIdentifier + " sending a message every 30 seconds.");
}, 600);
}

View File

@ -0,0 +1,12 @@
import { EntityQueryOptions, DimensionLocation } from "@minecraft/server";
function findEntitiesHavingPropertyEqualsTo(
targetLocation: DimensionLocation
) {
// Minecraft bees have a has_nectar boolean property
const queryOption: EntityQueryOptions = {
propertyOptions: [{ propertyId: "minecraft:has_nectar", value: { equals: true } }],
};
const entities = targetLocation.dimension.getEntities(queryOption);
}

View File

@ -1 +0,0 @@
test.assertItemEntityCountIs(Items.feather, expectedFeatherLoc, 0, 1);

View File

@ -1,13 +1,15 @@
// A function that spawns fireworks and logs their velocity after 5 ticks
import { DimensionLocation, system, world } from '@minecraft/server';
import { MinecraftEntityTypes } from '@minecraft/vanilla-data';
import { system, DimensionLocation } from "@minecraft/server";
import { MinecraftEntityTypes } from "@minecraft/vanilla-data";
function spawnFireworks(location: DimensionLocation) {
const fireworkRocket = location.dimension.spawnEntity(MinecraftEntityTypes.FireworksRocket, location);
function getFireworkVelocity(
log: (message: string, status?: number) => void,
targetLocation: DimensionLocation
) {
const fireworkRocket = targetLocation.dimension.spawnEntity(MinecraftEntityTypes.FireworksRocket, targetLocation);
system.runTimeout(() => {
const velocity = fireworkRocket.getVelocity();
system.runTimeout(() => {
const velocity = fireworkRocket.getVelocity();
world.sendMessage(`Velocity of firework is: ${velocity.x}, ${velocity.y}, ${velocity.z}`);
}, 5);
log("Velocity of firework is: (x: " + velocity.x + ", y:" + velocity.y + ", z:" + velocity.z + ")");
}, 5);
}

View File

@ -0,0 +1,17 @@
import { world, EntityInventoryComponent, DimensionLocation } from "@minecraft/server";
function getFirstHotbarItem(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
for (const player of world.getAllPlayers()) {
const inventory = player.getComponent(EntityInventoryComponent.componentId) as EntityInventoryComponent;
if (inventory && inventory.container) {
const firstItem = inventory.container.getItem(0);
if (firstItem) {
log("First item in hotbar is: " + firstItem.typeId);
}
return inventory.container.getItem(0);
}
return undefined;
}
}

View File

@ -1,10 +0,0 @@
// A function that gets a copy of the first item in the player's hotbar
import { Player, EntityInventoryComponent, ItemStack } from '@minecraft/server';
function getFirstHotbarItem(player: Player): ItemStack | undefined {
const inventory = player.getComponent(EntityInventoryComponent.componentId);
if (inventory && inventory.container) {
return inventory.container.getItem(0);
}
return undefined;
}

View File

@ -0,0 +1,18 @@
import { world, ItemStack, EntityInventoryComponent, DimensionLocation } from "@minecraft/server";
import { MinecraftItemTypes } from "@minecraft/vanilla-data";
function giveDestroyRestrictedPickaxe(
targetLocation: DimensionLocation
) {
for (const player of world.getAllPlayers()) {
const specialPickaxe = new ItemStack(MinecraftItemTypes.DiamondPickaxe);
specialPickaxe.setCanDestroy([MinecraftItemTypes.Cobblestone, MinecraftItemTypes.Obsidian]);
const inventory = player.getComponent("inventory") as EntityInventoryComponent;
if (inventory === undefined || inventory.container === undefined) {
return;
}
inventory.container.addItem(specialPickaxe);
}
}

View File

@ -0,0 +1,21 @@
import { world, ItemStack, EntityInventoryComponent, EntityComponentTypes, ItemComponentTypes, ItemDurabilityComponent, DimensionLocation } from "@minecraft/server";
import { MinecraftItemTypes } from "@minecraft/vanilla-data";
function giveHurtDiamondSword(
targetLocation: DimensionLocation
) {
const hurtDiamondSword = new ItemStack(MinecraftItemTypes.DiamondSword);
const durabilityComponent = hurtDiamondSword.getComponent(ItemComponentTypes.Durability) as ItemDurabilityComponent;
if (durabilityComponent !== undefined) {
durabilityComponent.damage = durabilityComponent.maxDurability / 2;
}
for (const player of world.getAllPlayers()) {
const inventory = player.getComponent(EntityComponentTypes.Inventory) as EntityInventoryComponent;
if (inventory && inventory.container) {
inventory.container.addItem(hurtDiamondSword);
}
}
}

View File

@ -0,0 +1,18 @@
import { world, ItemStack, EntityInventoryComponent, EntityComponentTypes, DimensionLocation } from "@minecraft/server";
import { MinecraftItemTypes } from "@minecraft/vanilla-data";
function givePlaceRestrictedGoldBlock(
targetLocation: DimensionLocation
) {
for (const player of world.getAllPlayers()) {
const specialGoldBlock = new ItemStack(MinecraftItemTypes.GoldBlock);
specialGoldBlock.setCanPlaceOn([MinecraftItemTypes.GrassBlock, MinecraftItemTypes.Dirt]);
const inventory = player.getComponent(EntityComponentTypes.Inventory) as EntityInventoryComponent;
if (inventory === undefined || inventory.container === undefined) {
return;
}
inventory.container.addItem(specialGoldBlock);
}
}

View File

@ -1,17 +1,31 @@
// Gives the player some equipment
import { EquipmentSlot, ItemStack, Player, EntityComponentTypes } from '@minecraft/server';
import { MinecraftItemTypes } from '@minecraft/vanilla-data';
import { world, ItemStack, EntityEquippableComponent, EquipmentSlot, EntityComponentTypes, DimensionLocation } from "@minecraft/server";
import { MinecraftItemTypes } from "@minecraft/vanilla-data";
function giveEquipment(player: Player) {
const equipmentCompPlayer = player.getComponent(EntityComponentTypes.Equippable);
if (equipmentCompPlayer) {
equipmentCompPlayer.setEquipment(EquipmentSlot.Head, new ItemStack(MinecraftItemTypes.GoldenHelmet));
equipmentCompPlayer.setEquipment(EquipmentSlot.Chest, new ItemStack(MinecraftItemTypes.IronChestplate));
equipmentCompPlayer.setEquipment(EquipmentSlot.Legs, new ItemStack(MinecraftItemTypes.DiamondLeggings));
equipmentCompPlayer.setEquipment(EquipmentSlot.Feet, new ItemStack(MinecraftItemTypes.NetheriteBoots));
equipmentCompPlayer.setEquipment(EquipmentSlot.Mainhand, new ItemStack(MinecraftItemTypes.WoodenSword));
equipmentCompPlayer.setEquipment(EquipmentSlot.Offhand, new ItemStack(MinecraftItemTypes.Shield));
} else {
console.warn('No equipment component found on player');
}
function givePlayerEquipment(
targetLocation: DimensionLocation
) {
const players = world.getAllPlayers();
const armorStandLoc = { x: targetLocation.x, y: targetLocation.y, z: targetLocation.z + 4 };
const armorStand = players[0].dimension.spawnEntity(MinecraftItemTypes.ArmorStand, armorStandLoc);
const equipmentCompPlayer = players[0].getComponent(EntityComponentTypes.Equippable) as EntityEquippableComponent;
if (equipmentCompPlayer) {
equipmentCompPlayer.setEquipment(EquipmentSlot.Head, new ItemStack(MinecraftItemTypes.GoldenHelmet));
equipmentCompPlayer.setEquipment(EquipmentSlot.Chest, new ItemStack(MinecraftItemTypes.IronChestplate));
equipmentCompPlayer.setEquipment(EquipmentSlot.Legs, new ItemStack(MinecraftItemTypes.DiamondLeggings));
equipmentCompPlayer.setEquipment(EquipmentSlot.Feet, new ItemStack(MinecraftItemTypes.NetheriteBoots));
equipmentCompPlayer.setEquipment(EquipmentSlot.Mainhand, new ItemStack(MinecraftItemTypes.WoodenSword));
equipmentCompPlayer.setEquipment(EquipmentSlot.Offhand, new ItemStack(MinecraftItemTypes.Shield));
}
const equipmentCompArmorStand = armorStand.getComponent(EntityComponentTypes.Equippable) as EntityEquippableComponent;
if (equipmentCompArmorStand) {
equipmentCompArmorStand.setEquipment(EquipmentSlot.Head, new ItemStack(MinecraftItemTypes.GoldenHelmet));
equipmentCompArmorStand.setEquipment(EquipmentSlot.Chest, new ItemStack(MinecraftItemTypes.IronChestplate));
equipmentCompArmorStand.setEquipment(EquipmentSlot.Legs, new ItemStack(MinecraftItemTypes.DiamondLeggings));
equipmentCompArmorStand.setEquipment(EquipmentSlot.Feet, new ItemStack(MinecraftItemTypes.NetheriteBoots));
equipmentCompArmorStand.setEquipment(EquipmentSlot.Mainhand, new ItemStack(MinecraftItemTypes.WoodenSword));
equipmentCompArmorStand.setEquipment(EquipmentSlot.Offhand, new ItemStack(MinecraftItemTypes.Shield));
}
}

View File

@ -1,18 +0,0 @@
// Spawns a bunch of item stacks
import { EnchantmentType, ItemComponentTypes, ItemStack, Player } from '@minecraft/server';
import { MinecraftItemTypes, MinecraftEnchantmentTypes } from '@minecraft/vanilla-data';
function giveFireSword(player: Player) {
const ironFireSword = new ItemStack(MinecraftItemTypes.DiamondSword, 1);
const enchantments = ironFireSword?.getComponent(ItemComponentTypes.Enchantable);
if (enchantments) {
enchantments.addEnchantment({ type: new EnchantmentType(MinecraftEnchantmentTypes.FireAspect), level: 1 });
}
const inventory = player.getComponent('minecraft:inventory');
if (inventory === undefined || inventory.container === undefined) {
return;
}
inventory.container.setItem(0, ironFireSword);
}

View File

@ -1,15 +0,0 @@
// Creates a gold block that can be placed on grass and dirt
import { ItemStack, Player, EntityComponentTypes } from '@minecraft/server';
import { MinecraftItemTypes } from '@minecraft/vanilla-data';
function giveRestrictedGoldBlock(player: Player) {
const specialGoldBlock = new ItemStack(MinecraftItemTypes.GoldBlock);
specialGoldBlock.setCanPlaceOn([MinecraftItemTypes.Grass, MinecraftItemTypes.Dirt]);
const inventory = player.getComponent(EntityComponentTypes.Inventory);
if (inventory === undefined || inventory.container === undefined) {
return;
}
inventory.container.addItem(specialGoldBlock);
}

View File

@ -1,18 +0,0 @@
const specialPickaxe = new ItemStack('minecraft:diamond_pickaxe');
specialPickaxe.setCanDestroy(['minecraft:cobblestone', 'minecraft:obsidian']);
// Creates a diamond pickaxe that can destroy cobblestone and obsidian
import { ItemStack, Player } from '@minecraft/server';
import { MinecraftItemTypes } from '@minecraft/vanilla-data';
function giveRestrictedPickaxe(player: Player) {
const specialPickaxe = new ItemStack(MinecraftItemTypes.DiamondPickaxe);
specialPickaxe.setCanPlaceOn([MinecraftItemTypes.Cobblestone, MinecraftItemTypes.Obsidian]);
const inventory = player.getComponent('inventory');
if (inventory === undefined || inventory.container === undefined) {
return;
}
inventory.container.addItem(specialPickaxe);
}

View File

@ -1 +0,0 @@
test.assertEntityHasArmor("minecraft:horse", armorSlotTorso, "diamond_horse_armor", 0, horseLocation, true);

View File

@ -1,21 +1,21 @@
import * as mc from '@minecraft/server';
import { world, DimensionLocation } from "@minecraft/server";
function incrementProperty(propertyName: string): boolean {
let number = mc.world.getDynamicProperty(propertyName);
function incrementDynamicProperty(
log: (message: string, status?: number) => void,
targetLocation: DimensionLocation
) {
let number = world.getDynamicProperty("samplelibrary:number");
console.warn('Current value is: ' + number);
log("Current value is: " + number);
if (number === undefined) {
number = 0;
}
if (number === undefined) {
number = 0;
}
if (typeof number !== 'number') {
console.warn('Number is of an unexpected type.');
return false;
}
if (typeof number !== "number") {
log("Number is of an unexpected type.");
return -1;
}
mc.world.setDynamicProperty(propertyName, number + 1);
return true;
world.setDynamicProperty("samplelibrary:number", number + 1);
}
incrementProperty('samplelibrary:number');

View File

@ -1,40 +1,39 @@
import * as mc from '@minecraft/server';
import { world, DimensionLocation } from "@minecraft/server";
function updateWorldProperty(propertyName: string): boolean {
let paintStr = mc.world.getDynamicProperty(propertyName);
let paint: { color: string; intensity: number } | undefined = undefined;
function incrementDynamicPropertyInJsonBlob(
log: (message: string, status?: number) => void,
targetLocation: DimensionLocation
) {
let paintStr = world.getDynamicProperty("samplelibrary:longerjson");
let paint: { color: string; intensity: number } | undefined = undefined;
console.log('Current value is: ' + paintStr);
log("Current value is: " + paintStr);
if (paintStr === undefined) {
paint = {
color: 'purple',
intensity: 0,
};
} else {
if (typeof paintStr !== 'string') {
console.warn('Paint is of an unexpected type.');
return false;
}
try {
paint = JSON.parse(paintStr);
} catch (e) {
console.warn('Error parsing serialized struct.');
return false;
}
if (paintStr === undefined) {
paint = {
color: "purple",
intensity: 0,
};
} else {
if (typeof paintStr !== "string") {
log("Paint is of an unexpected type.");
return -1;
}
if (!paint) {
console.warn('Error parsing serialized struct.');
return false;
try {
paint = JSON.parse(paintStr);
} catch (e) {
log("Error parsing serialized struct.");
return -1;
}
}
paint.intensity++;
paintStr = JSON.stringify(paint); // be very careful to ensure your serialized JSON str cannot exceed limits
mc.world.setDynamicProperty(propertyName, paintStr);
if (!paint) {
log("Error parsing serialized struct.");
return -1;
}
return true;
paint.intensity++;
paintStr = JSON.stringify(paint); // be very careful to ensure your serialized JSON str cannot exceed limits
world.setDynamicProperty("samplelibrary:longerjson", paintStr);
}
updateWorldProperty('samplelibrary:longerjson');

View File

@ -0,0 +1,21 @@
import { ItemStack, DimensionLocation } from "@minecraft/server";
import { MinecraftItemTypes } from "@minecraft/vanilla-data";
function itemStacks(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
const oneItemLoc = { x: targetLocation.x + targetLocation.y + 3, y: 2, z: targetLocation.z + 1 };
const fiveItemsLoc = { x: targetLocation.x + 1, y: targetLocation.y + 2, z: targetLocation.z + 1 };
const diamondPickaxeLoc = { x: targetLocation.x + 2, y: targetLocation.y + 2, z: targetLocation.z + 4 };
const oneEmerald = new ItemStack(MinecraftItemTypes.Emerald, 1);
const onePickaxe = new ItemStack(MinecraftItemTypes.DiamondPickaxe, 1);
const fiveEmeralds = new ItemStack(MinecraftItemTypes.Emerald, 5);
log(`Spawning an emerald at (${oneItemLoc.x}, ${oneItemLoc.y}, ${oneItemLoc.z})`);
targetLocation.dimension.spawnItem(oneEmerald, oneItemLoc);
log(`Spawning five emeralds at (${fiveItemsLoc.x}, ${fiveItemsLoc.y}, ${fiveItemsLoc.z})`);
targetLocation.dimension.spawnItem(fiveEmeralds, fiveItemsLoc);
log(`Spawning a diamond pickaxe at (${diamondPickaxeLoc.x}, ${diamondPickaxeLoc.y}, ${diamondPickaxeLoc.z})`);
targetLocation.dimension.spawnItem(onePickaxe, diamondPickaxeLoc);
}

View File

@ -1,8 +1,30 @@
import { world, system, LeverActionAfterEvent } from '@minecraft/server';
import { world, system, BlockPermutation, LeverActionAfterEvent, DimensionLocation } from "@minecraft/server";
import { MinecraftBlockTypes } from "@minecraft/vanilla-data";
world.afterEvents.leverAction.subscribe((leverActivateEvent: LeverActionAfterEvent) => {
console.warn(
`Lever event at ${system.currentTick} with power: ${leverActivateEvent.block.getRedstonePower()}`,
);
});
function leverActionEvent(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
// set up a lever
const cobblestone = targetLocation.dimension.getBlock(targetLocation);
const lever = targetLocation.dimension.getBlock({
x: targetLocation.x,
y: targetLocation.y + 1,
z: targetLocation.z,
});
if (cobblestone === undefined || lever === undefined) {
log("Could not find block at location.");
return -1;
}
cobblestone.setPermutation(BlockPermutation.resolve(MinecraftBlockTypes.Cobblestone));
lever.setPermutation(
BlockPermutation.resolve(MinecraftBlockTypes.Lever).withState("lever_direction", "up_north_south")
);
world.afterEvents.leverAction.subscribe((leverActionEvent: LeverActionAfterEvent) => {
const eventLoc = leverActionEvent.block.location;
if (eventLoc.x === targetLocation.x && eventLoc.y === targetLocation.y + 1 && eventLoc.z === targetLocation.z) {
log("Lever activate event at tick " + system.currentTick);
}
});
}

View File

@ -0,0 +1,23 @@
import { world, system, EntitySpawnAfterEvent, DimensionLocation } from "@minecraft/server";
import { Vector3Utils } from "@minecraft/math";
function logEntitySpawnEvent(
log: (message: string, status?: number) => void,
targetLocation: DimensionLocation
) {
// register a new function that is called when a new entity is created.
world.afterEvents.entitySpawn.subscribe((entityEvent: EntitySpawnAfterEvent) => {
if (entityEvent && entityEvent.entity) {
log(`New entity of type ${entityEvent.entity.typeId} created!`, 1);
} else {
log(`The entity event did not work as expected.`, -1);
}
});
system.runTimeout(() => {
targetLocation.dimension.spawnEntity(
"minecraft:horse<minecraft:ageable_grow_up>",
Vector3Utils.add(targetLocation, { x: 0, y: 1, z: 0 })
);
}, 20);
}

View File

@ -1,9 +0,0 @@
// Register a new function that is called when a new entity is created.
import { world, EntitySpawnAfterEvent } from '@minecraft/server';
world.afterEvents.entitySpawn.subscribe((entityEvent: EntitySpawnAfterEvent) => {
const spawnLocation = entityEvent.entity.location;
world.sendMessage(
`New entity of type '${entityEvent.entity.typeId}' spawned at ${spawnLocation.x}, ${spawnLocation.y}, ${spawnLocation.z}!`,
);
});

View File

@ -1,24 +0,0 @@
import { Player } from '@minecraft/server';
import { MessageFormResponse, MessageFormData } from '@minecraft/server-ui';
function showMessage(player: Player) {
const messageForm = new MessageFormData()
.title({ translate: 'permissions.removeplayer' }) // "Remove player"
.body({ translate: 'accessibility.list.or.two', with: ['Player 1', 'Player 2'] }) // "Player 1 or Player 2"
.button1('Player 1')
.button2('Player 2');
messageForm
.show(player)
.then((formData: MessageFormResponse) => {
// player canceled the form, or another dialog was up and open.
if (formData.canceled || formData.selection === undefined) {
return;
}
player.sendMessage(`You selected ${formData.selection === 0 ? 'Player 1' : 'Player 2'}`);
})
.catch((error: Error) => {
player.sendMessage('Failed to show form: ' + error);
});
}

View File

@ -0,0 +1,17 @@
import { EntityComponentTypes } from "@minecraft/server";
import { Test, register } from "@minecraft/server-gametest";
import { MinecraftBlockTypes, MinecraftEntityTypes } from "@minecraft/vanilla-data";
function minibiomes(test: Test) {
const minecart = test.spawn(MinecraftEntityTypes.Minecart, { x: 9, y: 7, z: 7 });
const pig = test.spawn(MinecraftEntityTypes.Pig, { x: 9, y: 7, z: 7 });
test.setBlockType(MinecraftBlockTypes.Cobblestone, { x: 10, y: 7, z: 7 });
const minecartRideableComp = minecart.getComponent(EntityComponentTypes.Rideable);
minecartRideableComp?.addRider(pig);
test.succeedWhenEntityPresent(MinecraftEntityTypes.Pig, { x: 8, y: 3, z: 1 }, true);
}
register("ChallengeTests", "minibiomes", minibiomes).structureName("gametests:minibiomes").maxTicks(160);

View File

@ -1,28 +0,0 @@
import { Player } from '@minecraft/server';
import { ModalFormData } from '@minecraft/server-ui';
function showExampleModal(player: Player) {
const modalForm = new ModalFormData().title('Example Modal Controls for §o§7ModalFormData§r');
modalForm.toggle('Toggle w/o default');
modalForm.toggle('Toggle w/ default', true);
modalForm.slider('Slider w/o default', 0, 50, 5);
modalForm.slider('Slider w/ default', 0, 50, 5, 30);
modalForm.dropdown('Dropdown w/o default', ['option 1', 'option 2', 'option 3']);
modalForm.dropdown('Dropdown w/ default', ['option 1', 'option 2', 'option 3'], 2);
modalForm.textField('Input w/o default', 'type text here');
modalForm.textField('Input w/ default', 'type text here', 'this is default');
modalForm
.show(player)
.then(formData => {
player.sendMessage(`Modal form results: ${JSON.stringify(formData.formValues, undefined, 2)}`);
})
.catch((error: Error) => {
player.sendMessage('Failed to show form: ' + error);
return -1;
});
}

View File

@ -0,0 +1,25 @@
import { world, EntityInventoryComponent, EntityComponentTypes, DimensionLocation } from "@minecraft/server";
import { MinecraftEntityTypes } from "@minecraft/vanilla-data";
function moveBetweenContainers(
targetLocation: DimensionLocation
) {
const players = world.getAllPlayers();
const chestCart = targetLocation.dimension.spawnEntity(MinecraftEntityTypes.ChestMinecart, {
x: targetLocation.x + 1,
y: targetLocation.y,
z: targetLocation.z,
});
if (players.length > 0) {
const fromPlayer = players[0];
const fromInventory = fromPlayer.getComponent(EntityComponentTypes.Inventory) as EntityInventoryComponent;
const toInventory = chestCart.getComponent(EntityComponentTypes.Inventory) as EntityInventoryComponent;
if (fromInventory && toInventory && fromInventory.container && toInventory.container) {
fromInventory.container.moveItem(0, 0, toInventory.container);
}
}
}

View File

@ -1,11 +0,0 @@
// A function that moves an item from one slot of the player's inventory to another player's inventory
import { Player, EntityComponentTypes } from '@minecraft/server';
function moveBetweenPlayers(slotId: number, fromPlayer: Player, toPlayer: Player) {
const fromInventory = fromPlayer.getComponent(EntityComponentTypes.Inventory);
const toInventory = toPlayer.getComponent(EntityComponentTypes.Inventory);
if (fromInventory && toInventory && fromInventory.container && toInventory.container) {
fromInventory.container.moveItem(slotId, slotId, toInventory.container);
}
}

View File

@ -1,8 +1,10 @@
import { world } from '@minecraft/server';
import { world, DimensionLocation } from "@minecraft/server";
// Displays "Apple or Coal"
const rawMessage = {
translate: 'accessibility.list.or.two',
with: { rawtext: [{ translate: 'item.apple.name' }, { translate: 'item.coal.name' }] },
};
world.sendMessage(rawMessage);
function nestedTranslation(targetLocation: DimensionLocation) {
// Displays "Apple or Coal"
const rawMessage = {
translate: "accessibility.list.or.two",
with: { rawtext: [{ translate: "item.apple.name" }, { translate: "item.coal.name" }] },
};
world.sendMessage(rawMessage);
}

View File

@ -0,0 +1,12 @@
import { Test, register } from "@minecraft/server-gametest";
import { MinecraftEntityTypes } from "@minecraft/vanilla-data";
function phantomsShouldFlyFromCats(test: Test) {
test.spawn(MinecraftEntityTypes.Cat, { x: 4, y: 3, z: 3 });
test.spawn(MinecraftEntityTypes.Phantom, { x: 4, y: 3, z: 3 });
test.succeedWhenEntityPresent(MinecraftEntityTypes.Phantom, { x: 4, y: 6, z: 3 }, true);
}
register("MobBehaviorTests", "phantoms_should_fly_from_cats", phantomsShouldFlyFromCats)
.structureName("gametests:glass_cells");

View File

@ -1,7 +1,36 @@
import { world, system, PistonActivateAfterEvent } from '@minecraft/server';
import { world, system, BlockPermutation, BlockPistonState, PistonActivateAfterEvent, DimensionLocation } from "@minecraft/server";
import { MinecraftBlockTypes } from "@minecraft/vanilla-data";
world.afterEvents.pistonActivate.subscribe((pistonEvent: PistonActivateAfterEvent) => {
console.warn(
`Piston event at ${system.currentTick} ${(pistonEvent.piston.isMoving ? ' Moving' : 'Not moving')} with state: ${pistonEvent.piston.state}`,
);
});
function pistonAfterEvent(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
// set up a couple of piston blocks
const piston = targetLocation.dimension.getBlock(targetLocation);
const button = targetLocation.dimension.getBlock({
x: targetLocation.x,
y: targetLocation.y + 1,
z: targetLocation.z,
});
if (piston === undefined || button === undefined) {
log("Could not find block at location.");
return -1;
}
piston.setPermutation(BlockPermutation.resolve(MinecraftBlockTypes.Piston).withState("facing_direction", 3));
button.setPermutation(BlockPermutation.resolve(MinecraftBlockTypes.AcaciaButton).withState("facing_direction", 1));
world.afterEvents.pistonActivate.subscribe((pistonEvent: PistonActivateAfterEvent) => {
const eventLoc = pistonEvent.piston.block.location;
if (eventLoc.x === targetLocation.x && eventLoc.y === targetLocation.y && eventLoc.z === targetLocation.z) {
log(
"Piston event at " +
system.currentTick +
(pistonEvent.piston.isMoving ? " Moving" : "") +
(pistonEvent.piston.state === BlockPistonState.Expanding ? " Expanding" : "") +
(pistonEvent.piston.state === BlockPistonState.Expanded ? " Expanded" : "") +
(pistonEvent.piston.state === BlockPistonState.Retracting ? " Retracting" : "") +
(pistonEvent.piston.state === BlockPistonState.Retracted ? " Retracted" : "")
);
}
});
}

View File

@ -0,0 +1,28 @@
import { ItemStack, BlockInventoryComponent, DimensionLocation } from "@minecraft/server";
import { MinecraftBlockTypes, MinecraftItemTypes } from "@minecraft/vanilla-data";
function placeItemsInChest(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
// Fetch block
const block = targetLocation.dimension.getBlock(targetLocation);
if (!block) {
log("Could not find block. Maybe it is not loaded?", -1);
return;
}
// Make it a chest
block.setType(MinecraftBlockTypes.Chest);
// Get the inventory
const inventoryComponent = block.getComponent("inventory") as BlockInventoryComponent;
if (!inventoryComponent || !inventoryComponent.container) {
log("Could not find inventory component.", -1);
return;
}
const inventoryContainer = inventoryComponent.container;
// Set slot 0 to a stack of 10 apples
inventoryContainer.setItem(0, new ItemStack(MinecraftItemTypes.Apple, 10));
}

View File

@ -1,15 +0,0 @@
import { world, MinecraftBlockTypes, Items, ItemStack } from "@minecraft/server";
// Fetch block
const block = world.getDimension("overworld").getBlock({ x: 1, y: 2, z: 3 });
// Make it a chest
block.setType(MinecraftBlockTypes.chest);
// Get the inventory
const inventoryComponent = block.getComponent("inventory");
const inventoryContainer = inventoryComponent.container;
// Set slot 0 to a stack of 10 apples
inventoryContainer.setItem(0, new ItemStack(Items.apple, 10, 0));

View File

@ -1,30 +1,25 @@
import { world, MusicOptions, WorldSoundOptions, PlayerSoundOptions, Vector3 } from '@minecraft/server';
import { MinecraftDimensionTypes } from '@minecraft/vanilla-data';
import { world, MusicOptions, WorldSoundOptions, PlayerSoundOptions, DimensionLocation } from "@minecraft/server";
const players = world.getPlayers();
const targetLocation: Vector3 = {
x: 0,
y: 0,
z: 0,
};
function playMusicAndSound(targetLocation: DimensionLocation) {
const players = world.getPlayers();
const musicOptions: MusicOptions = {
const musicOptions: MusicOptions = {
fade: 0.5,
loop: true,
volume: 1.0,
};
world.playMusic('music.menu', musicOptions);
};
world.playMusic("music.menu", musicOptions);
const worldSoundOptions: WorldSoundOptions = {
const worldSoundOptions: WorldSoundOptions = {
pitch: 0.5,
volume: 4.0,
};
const overworld = world.getDimension(MinecraftDimensionTypes.Overworld);
overworld.playSound('ambient.weather.thunder', targetLocation, worldSoundOptions);
};
world.playSound("ambient.weather.thunder", targetLocation, worldSoundOptions);
const playerSoundOptions: PlayerSoundOptions = {
const playerSoundOptions: PlayerSoundOptions = {
pitch: 1.0,
volume: 1.0,
};
};
players[0].playSound('bucket.fill_water', playerSoundOptions);
players[0].playSound("bucket.fill_water", playerSoundOptions);
}

View File

@ -1,14 +0,0 @@
// Spawns a villager and gives it the poison effect
import {
DimensionLocation,
} from '@minecraft/server';
import { MinecraftEffectTypes } from '@minecraft/vanilla-data';
function spawnPoisonedVillager(location: DimensionLocation) {
const villagerType = 'minecraft:villager_v2<minecraft:ageable_grow_up>';
const villager = location.dimension.spawnEntity(villagerType, location);
const duration = 20;
villager.addEffect(MinecraftEffectTypes.Poison, duration, { amplifier: 1 });
}

View File

@ -1,23 +1,26 @@
// Spawns a fox over a dog
import { DimensionLocation } from '@minecraft/server';
import { MinecraftEntityTypes } from '@minecraft/vanilla-data';
import { DimensionLocation } from "@minecraft/server";
import { MinecraftEntityTypes, MinecraftEffectTypes } from "@minecraft/vanilla-data";
function spawnAdultHorse(location: DimensionLocation) {
// Create fox (our quick brown fox)
const fox = location.dimension.spawnEntity(MinecraftEntityTypes.Fox, {
x: location.x,
y: location.y + 2,
z: location.z,
});
function quickFoxLazyDog(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
const fox = targetLocation.dimension.spawnEntity(MinecraftEntityTypes.Fox, {
x: targetLocation.x + 1,
y: targetLocation.y + 2,
z: targetLocation.z + 3,
});
fox.addEffect('speed', 10, {
amplifier: 2,
});
fox.addEffect(MinecraftEffectTypes.Speed, 10, {
amplifier: 2,
});
log("Created a fox.");
// Create wolf (our lazy dog)
const wolf = location.dimension.spawnEntity(MinecraftEntityTypes.Wolf, location);
wolf.addEffect('slowness', 10, {
amplifier: 2,
});
wolf.isSneaking = true;
const wolf = targetLocation.dimension.spawnEntity(MinecraftEntityTypes.Wolf, {
x: targetLocation.x + 4,
y: targetLocation.y + 2,
z: targetLocation.z + 3,
});
wolf.addEffect(MinecraftEffectTypes.Slowness, 10, {
amplifier: 2,
});
wolf.isSneaking = true;
log("Created a sneaking wolf.", 1);
}

View File

@ -1,5 +1,7 @@
import { world } from '@minecraft/server';
import { world, DimensionLocation } from "@minecraft/server";
// Displays the player's score for objective "obj". Each player will see their own score.
const rawMessage = { score: { name: '*', objective: 'obj' } };
world.sendMessage(rawMessage);
function scoreWildcard(targetLocation: DimensionLocation) {
// Displays the player's score for objective "obj". Each player will see their own score.
const rawMessage = { score: { name: "*", objective: "obj" } };
world.sendMessage(rawMessage);
}

View File

@ -0,0 +1,7 @@
import { world, DimensionLocation } from "@minecraft/server";
function sendBasicMessage(targetLocation: DimensionLocation) {
const players = world.getPlayers();
players[0].sendMessage("Hello World!");
}

View File

@ -1,24 +0,0 @@
import { Player } from "@minecraft/server";
function sendPlayerMessages(player: Player) {
// Displays "First or Second"
const rawMessage = { translate: 'accessibility.list.or.two', with: ['First', 'Second'] };
player.sendMessage(rawMessage);
// Displays "Hello, world!"
player.sendMessage('Hello, world!');
// Displays "Welcome, Amazing Player 1!"
player.sendMessage({ translate: 'authentication.welcome', with: ['Amazing Player 1'] });
// Displays the player's score for objective "obj". Each player will see their own score.
const rawMessageWithScore = { score: { name: '*', objective: 'obj' } };
player.sendMessage(rawMessageWithScore);
// Displays "Apple or Coal"
const rawMessageWithNestedTranslations = {
translate: 'accessibility.list.or.two',
with: { rawtext: [{ translate: 'item.apple.name' }, { translate: 'item.coal.name' }] },
};
player.sendMessage(rawMessageWithNestedTranslations);
}

View File

@ -0,0 +1,26 @@
import { world, DimensionLocation } from "@minecraft/server";
function sendPlayerMessages(targetLocation: DimensionLocation) {
for (const player of world.getAllPlayers()) {
// Displays "First or Second"
const rawMessage = { translate: "accessibility.list.or.two", with: ["First", "Second"] };
player.sendMessage(rawMessage);
// Displays "Hello, world!"
player.sendMessage("Hello, world!");
// Displays "Welcome, Amazing Player 1!"
player.sendMessage({ translate: "authentication.welcome", with: ["Amazing Player 1"] });
// Displays the player's score for objective "obj". Each player will see their own score.
const rawMessageWithScore = { score: { name: "*", objective: "obj" } };
player.sendMessage(rawMessageWithScore);
// Displays "Apple or Coal"
const rawMessageWithNestedTranslations = {
translate: "accessibility.list.or.two",
with: { rawtext: [{ translate: "item.apple.name" }, { translate: "item.coal.name" }] },
};
player.sendMessage(rawMessageWithNestedTranslations);
}
}

View File

@ -0,0 +1,9 @@
import { world, DimensionLocation } from "@minecraft/server";
function sendTranslatedMessage(
targetLocation: DimensionLocation
) {
const players = world.getPlayers();
players[0].sendMessage({ translate: "authentication.welcome", with: ["Amazing Player 1"] });
}

View File

@ -1,15 +0,0 @@
import { world, Entity, EntityComponentTypes, system } from "@minecraft/server";
function setAblaze(entity: Entity) {
entity.setOnFire(20, true);
system.runTimeout(() => {
const onfire = entity.getComponent(EntityComponentTypes.OnFire);
if (onfire) {
world.sendMessage(`${onfire.onFireTicksRemaining} fire ticks remaining, extinguishing the entity.`);
}
// This will extinguish the entity
entity.extinguishFire(true);
}, 30); // Run in 30 ticks or ~1.5 seconds
}

View File

@ -0,0 +1,16 @@
import { system, EntityOnFireComponent, EntityComponentTypes, DimensionLocation } from "@minecraft/server";
import { MinecraftEntityTypes } from "@minecraft/vanilla-data";
function setOnFire(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
const skelly = targetLocation.dimension.spawnEntity(MinecraftEntityTypes.Skeleton, targetLocation);
skelly.setOnFire(20, true);
system.runTimeout(() => {
const onfire = skelly.getComponent(EntityComponentTypes.OnFire) as EntityOnFireComponent;
log(onfire?.onFireTicksRemaining + " fire ticks remaining.");
skelly.extinguishFire(true);
log("Never mind. Fire extinguished.");
}, 20);
}

View File

@ -1,31 +0,0 @@
import {
BlockComponentTypes,
DimensionLocation,
RawMessage,
RawText,
} from '@minecraft/server';
// Function which updates a sign blocks text to raw text
function updateSignText(signLocation: DimensionLocation) {
const block = signLocation.dimension.getBlock(signLocation);
if (!block) {
console.warn('Could not find a block at specified location.');
return;
}
const sign = block.getComponent(BlockComponentTypes.Sign);
if (sign) {
// RawMessage
const helloWorldMessage: RawMessage = { text: 'Hello World' };
sign.setText(helloWorldMessage);
// RawText
const helloWorldText: RawText = { rawtext: [{ text: 'Hello World' }] };
sign.setText(helloWorldText);
// Regular string
sign.setText('Hello World');
} else {
console.warn('Could not find a sign component on the block.');
}
}

View File

@ -1,5 +1,9 @@
import { world } from '@minecraft/server';
import { world, DimensionLocation } from "@minecraft/server";
world.afterEvents.playerSpawn.subscribe((event) => {
event.player.onScreenDisplay.setTitle('§o§6You respawned!§r');
});
function setTitle(targetLocation: DimensionLocation) {
const players = world.getPlayers();
if (players.length > 0) {
players[0].onScreenDisplay.setTitle("§o§6Fancy Title§r");
}
}

View File

@ -1,10 +1,14 @@
import { world } from '@minecraft/server';
import { world, DimensionLocation } from "@minecraft/server";
world.afterEvents.playerSpawn.subscribe((event) => {
event.player.onScreenDisplay.setTitle('You respawned', {
stayDuration: 100,
fadeInDuration: 2,
fadeOutDuration: 4,
subtitle: 'Try not to die next time!',
});
});
function setTitleAndSubtitle(
targetLocation: DimensionLocation
) {
const players = world.getPlayers();
players[0].onScreenDisplay.setTitle("Chapter 1", {
stayDuration: 100,
fadeInDuration: 2,
fadeOutDuration: 4,
subtitle: "Trouble in Block Town",
});
}

View File

@ -1 +0,0 @@
test.assertEntityHasComponent("minecraft:sheep", "minecraft:is_sheared", entityLoc, false);

View File

@ -1,7 +1,15 @@
import { world, Vector3 } from '@minecraft/server';
import { DimensionLocation, EntityProjectileComponent } from "@minecraft/server";
const location: Vector3 = { x: 0, y: -59, z: 0 }; // Replace with the coordinates of where you want to spawn the arrow
const velocity: Vector3 = { x: 0, y: 0, z: 5 };
const arrow = world.getDimension('overworld').spawnEntity('minecraft:arrow', location);
const projectileComp = arrow.getComponent('minecraft:projectile');
projectileComp?.shoot(velocity);
function shootArrow(targetLocation: DimensionLocation) {
const velocity = { x: 0, y: 1, z: 5 };
const arrow = targetLocation.dimension.spawnEntity("minecraft:arrow", {
x: targetLocation.x,
y: targetLocation.y + 2,
z: targetLocation.z,
});
const projectileComp = arrow.getComponent("minecraft:projectile") as EntityProjectileComponent;
projectileComp?.shoot(velocity);
}

View File

@ -0,0 +1,26 @@
import { world, DimensionLocation } from "@minecraft/server";
import { ActionFormData, ActionFormResponse } from "@minecraft/server-ui";
function showActionForm(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
const playerList = world.getPlayers();
if (playerList.length >= 1) {
const form = new ActionFormData()
.title("Test Title")
.body("Body text here!")
.button("btn 1")
.button("btn 2")
.button("btn 3")
.button("btn 4")
.button("btn 5");
form.show(playerList[0]).then((result: ActionFormResponse) => {
if (result.canceled) {
log("Player exited out of the dialog. Note that if the chat window is up, dialogs are automatically canceled.");
return -1;
} else {
log("Your result was: " + result.selection);
}
});
}
}

View File

@ -0,0 +1,30 @@
import { world, DimensionLocation } from "@minecraft/server";
import { MessageFormResponse, MessageFormData } from "@minecraft/server-ui";
function showBasicMessageForm(
log: (message: string, status?: number) => void,
targetLocation: DimensionLocation
) {
const players = world.getPlayers();
const messageForm = new MessageFormData()
.title("Message Form Example")
.body("This shows a simple example using §o§7MessageFormData§r.")
.button1("Button 1")
.button2("Button 2");
messageForm
.show(players[0])
.then((formData: MessageFormResponse) => {
// player canceled the form, or another dialog was up and open.
if (formData.canceled || formData.selection === undefined) {
return;
}
log(`You selected ${formData.selection === 0 ? "Button 1" : "Button 2"}`);
})
.catch((error: Error) => {
log("Failed to show form: " + error);
return -1;
});
}

View File

@ -0,0 +1,30 @@
import { world, DimensionLocation } from "@minecraft/server";
import { ModalFormData } from "@minecraft/server-ui";
function showBasicModalForm(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
const players = world.getPlayers();
const modalForm = new ModalFormData().title("Example Modal Controls for §o§7ModalFormData§r");
modalForm.toggle("Toggle w/o default");
modalForm.toggle("Toggle w/ default", true);
modalForm.slider("Slider w/o default", 0, 50, 5);
modalForm.slider("Slider w/ default", 0, 50, 5, 30);
modalForm.dropdown("Dropdown w/o default", ["option 1", "option 2", "option 3"]);
modalForm.dropdown("Dropdown w/ default", ["option 1", "option 2", "option 3"], 2);
modalForm.textField("Input w/o default", "type text here");
modalForm.textField("Input w/ default", "type text here", "this is default");
modalForm
.show(players[0])
.then((formData) => {
players[0].sendMessage(`Modal form results: ${JSON.stringify(formData.formValues, undefined, 2)}`);
})
.catch((error: Error) => {
log("Failed to show form: " + error);
return -1;
});
}

View File

@ -0,0 +1,24 @@
import { world, DimensionLocation } from "@minecraft/server";
import { ActionFormData, ActionFormResponse } from "@minecraft/server-ui";
function showFavoriteMonth(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
const players = world.getPlayers();
if (players.length >= 1) {
const form = new ActionFormData()
.title("Months")
.body("Choose your favorite month!")
.button("January")
.button("February")
.button("March")
.button("April")
.button("May");
form.show(players[0]).then((response: ActionFormResponse) => {
if (response.selection === 3) {
log("I like April too!");
return -1;
}
});
}
}

View File

@ -1,26 +1,30 @@
import { world, Player } from '@minecraft/server';
import { MessageFormData, MessageFormResponse } from '@minecraft/server-ui';
import { world, DimensionLocation } from "@minecraft/server";
import { MessageFormResponse, MessageFormData } from "@minecraft/server-ui";
function showMessage(player: Player) {
const messageForm = new MessageFormData()
.title({ translate: 'permissions.removeplayer' })
.body({ translate: 'accessibility.list.or.two', with: ['Player 1', 'Player 2'] })
.button1('Player 1')
.button2('Player 2');
function showTranslatedMessageForm(
log: (message: string, status?: number) => void,
targetLocation: DimensionLocation
) {
const players = world.getPlayers();
messageForm
.show(player)
.then((formData: MessageFormResponse) => {
// player canceled the form, or another dialog was up and open.
if (formData.canceled || formData.selection === undefined) {
return;
}
const messageForm = new MessageFormData()
.title({ translate: "permissions.removeplayer" })
.body({ translate: "accessibility.list.or.two", with: ["Player 1", "Player 2"] })
.button1("Player 1")
.button2("Player 2");
console.warn(`You selected ${formData.selection === 0 ? 'Player 1' : 'Player 2'}`);
})
.catch((error: Error) => {
console.warn('Failed to show form: ' + error);
});
};
messageForm
.show(players[0])
.then((formData: MessageFormResponse) => {
// player canceled the form, or another dialog was up and open.
if (formData.canceled || formData.selection === undefined) {
return;
}
showMessage(world.getAllPlayers()[0]);
log(`You selected ${formData.selection === 0 ? "Player 1" : "Player 2"}`);
})
.catch((error: Error) => {
log("Failed to show form: " + error);
return -1;
});
}

View File

@ -0,0 +1,17 @@
import { Test, register } from "@minecraft/server-gametest";
import { MinecraftEntityTypes } from "@minecraft/vanilla-data";
function simpleMobGameTest(test: Test) {
const attackerId = MinecraftEntityTypes.Fox;
const victimId = MinecraftEntityTypes.Chicken;
test.spawn(attackerId, { x: 5, y: 2, z: 5 });
test.spawn(victimId, { x: 2, y: 2, z: 2 });
test.assertEntityPresentInArea(victimId, true);
test.succeedWhen(() => {
test.assertEntityPresentInArea(victimId, false);
});
}
register("StarterTests", "simpleMobTest", simpleMobGameTest).maxTicks(400).structureName("gametests:mediumglass");

View File

@ -1,4 +0,0 @@
import { world } from '@minecraft/server';
// Displays "Hello, world!"
world.sendMessage('Hello, world!');

View File

@ -0,0 +1,10 @@
import { DimensionLocation } from "@minecraft/server";
import { Vector3Utils } from "@minecraft/math";
function spawnAdultHorse(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
log("Create a horse and triggering the ageable_grow_up event, ensuring the horse is created as an adult");
targetLocation.dimension.spawnEntity(
"minecraft:horse<minecraft:ageable_grow_up>",
Vector3Utils.add(targetLocation, { x: 0, y: 1, z: 0 })
);
}

View File

@ -1 +0,0 @@
test.spawn("minecraft:pig<minecraft:ageable_grow_up>", { x: 1.5, y: 2, z: 1.5 });

View File

@ -1,2 +0,0 @@
test.spawn("minecraft:pig<minecraft:ageable_grow_up>", { x: 1, y: 2, z: 1 });

View File

@ -1,5 +0,0 @@
const oneEmerald = new ItemStack(MinecraftItemTypes.Emerald, 1, 0);
const fiveEmeralds = new ItemStack(MinecraftItemTypes.Emerald, 5, 0);
test.spawnItem(oneEmerald, { x: 3.5, y: 3, z: 1.5 });
test.spawnItem(fiveEmeralds, { x: 1.5, y: 3, z: 1.5 });

View File

@ -1,8 +1,9 @@
// Spawns a feather at a location
import { ItemStack, DimensionLocation } from '@minecraft/server';
import { MinecraftItemTypes } from '@minecraft/vanilla-data';
import { ItemStack, DimensionLocation } from "@minecraft/server";
import { MinecraftItemTypes } from "@minecraft/vanilla-data";
function spawnFeather(location: DimensionLocation) {
const featherItem = new ItemStack(MinecraftItemTypes.Feather, 1);
location.dimension.spawnItem(featherItem, location);
function spawnFeatherItem(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
const featherItem = new ItemStack(MinecraftItemTypes.Feather, 1);
targetLocation.dimension.spawnItem(featherItem, targetLocation);
log(`New feather created at ${targetLocation.x}, ${targetLocation.y}, ${targetLocation.z}!`);
}

View File

@ -0,0 +1,16 @@
import { MolangVariableMap, DimensionLocation } from "@minecraft/server";
function spawnParticle(targetLocation: DimensionLocation) {
for (let i = 0; i < 100; i++) {
const molang = new MolangVariableMap();
molang.setColorRGB("variable.color", { red: Math.random(), green: Math.random(), blue: Math.random() });
const newLocation = {
x: targetLocation.x + Math.floor(Math.random() * 8) - 4,
y: targetLocation.y + Math.floor(Math.random() * 8) - 4,
z: targetLocation.z + Math.floor(Math.random() * 8) - 4,
};
targetLocation.dimension.spawnParticle("minecraft:colored_flame_particle", newLocation, molang);
}
}

View File

@ -1,21 +0,0 @@
// A function that spawns a particle at a random location near the target location for all players in the server
import { world, MolangVariableMap, DimensionLocation, Vector3 } from '@minecraft/server';
function spawnConfetti(location: DimensionLocation) {
for (let i = 0; i < 100; i++) {
const molang = new MolangVariableMap();
molang.setColorRGB('variable.color', {
red: Math.random(),
green: Math.random(),
blue: Math.random()
});
const newLocation: Vector3 = {
x: location.x + Math.floor(Math.random() * 8) - 4,
y: location.y + Math.floor(Math.random() * 8) - 4,
z: location.z + Math.floor(Math.random() * 8) - 4,
};
location.dimension.spawnParticle('minecraft:colored_flame_particle', newLocation, molang);
}
}

View File

@ -0,0 +1,12 @@
import { DimensionLocation } from "@minecraft/server";
import { MinecraftEffectTypes } from "@minecraft/vanilla-data";
function spawnPoisonedVillager(
targetLocation: DimensionLocation
) {
const villagerType = "minecraft:villager_v2<minecraft:ageable_grow_up>";
const villager = targetLocation.dimension.spawnEntity(villagerType, targetLocation);
const duration = 20;
villager.addEffect(MinecraftEffectTypes.Poison, duration, { amplifier: 1 });
}

View File

@ -1 +0,0 @@
test.spreadFromFaceTowardDirection({ x: 1, y: 2, z: 1 }, Direction.south, Direction.down);

View File

@ -1,11 +0,0 @@
// A function that swaps an item from one slot of the player's inventory to another player's inventory
import { Player, EntityComponentTypes } from '@minecraft/server';
function swapBetweenPlayers(slotId: number, fromPlayer: Player, toPlayer: Player) {
const fromInventory = fromPlayer.getComponent(EntityComponentTypes.Inventory);
const toInventory = toPlayer.getComponent(EntityComponentTypes.Inventory);
if (fromInventory && toInventory && fromInventory.container && toInventory.container) {
fromInventory.container.swapItems(slotId, slotId, toInventory.container);
}
}

View File

@ -1,20 +1,20 @@
import { EntityQueryOptions, DimensionLocation } from '@minecraft/server';
import { EntityQueryOptions, DimensionLocation } from "@minecraft/server";
function mobParty(targetLocation: DimensionLocation) {
const mobs = ['creeper', 'skeleton', 'sheep'];
function tagsQuery(targetLocation: DimensionLocation) {
const mobs = ["creeper", "skeleton", "sheep"];
// create some sample mob data
for (let i = 0; i < 10; i++) {
const mobTypeId = mobs[i % mobs.length];
const entity = targetLocation.dimension.spawnEntity(mobTypeId, targetLocation);
entity.addTag('mobparty.' + mobTypeId);
}
// create some sample mob data
for (let i = 0; i < 10; i++) {
const mobTypeId = mobs[i % mobs.length];
const entity = targetLocation.dimension.spawnEntity(mobTypeId, targetLocation);
entity.addTag("mobparty." + mobTypeId);
}
const eqo: EntityQueryOptions = {
tags: ['mobparty.skeleton'],
};
const eqo: EntityQueryOptions = {
tags: ["mobparty.skeleton"],
};
for (const entity of targetLocation.dimension.getEntities(eqo)) {
entity.kill();
}
for (const entity of targetLocation.dimension.getEntities(eqo)) {
entity.kill();
}
}

View File

@ -0,0 +1,15 @@
import { system, DimensionLocation } from "@minecraft/server";
import { MinecraftEntityTypes } from "@minecraft/vanilla-data";
function teleport(targetLocation: DimensionLocation) {
const cow = targetLocation.dimension.spawnEntity(MinecraftEntityTypes.Cow, targetLocation);
system.runTimeout(() => {
cow.teleport(
{ x: targetLocation.x + 2, y: targetLocation.y + 2, z: targetLocation.z + 2 },
{
facingLocation: targetLocation,
}
);
}, 20);
}

View File

@ -1,21 +1,21 @@
import { world, system } from '@minecraft/server';
import { system, DimensionLocation } from "@minecraft/server";
import { MinecraftEntityTypes } from "@minecraft/vanilla-data";
const overworld = world.getDimension('overworld');
const targetLocation = { x: 0, y: 0, z: 0 };
function teleportMovement(targetLocation: DimensionLocation) {
const pig = targetLocation.dimension.spawnEntity(MinecraftEntityTypes.Pig, targetLocation);
const pig = overworld.spawnEntity('minecraft:pig', targetLocation);
let inc = 1;
const runId = system.runInterval(() => {
let inc = 1;
const runId = system.runInterval(() => {
pig.teleport(
{ x: targetLocation.x + inc / 4, y: targetLocation.y + inc / 4, z: targetLocation.z + inc / 4 },
{
facingLocation: targetLocation,
},
{ x: targetLocation.x + inc / 4, y: targetLocation.y + inc / 4, z: targetLocation.z + inc / 4 },
{
facingLocation: targetLocation,
}
);
if (inc > 100) {
system.clearRun(runId);
system.clearRun(runId);
}
inc++;
}, 4);
}, 4);
}

View File

@ -1,3 +0,0 @@
test.assertBlockState(buttonPos, (block) => {
return block.permutation.getProperty("button_pressed_bit") == 0;
});

Some files were not shown because too many files have changed in this diff Show More