Material grabber functional

This commit is contained in:
ForestOfLight
2025-04-21 02:15:27 -07:00
Unverified
parent 6d7db482c0
commit 6c32436cf0
8 changed files with 122 additions and 35 deletions
@@ -2,7 +2,7 @@ import { BuilderOptions } from "./BuilderOptions";
export class Builder { export class Builder {
playerId; playerId;
materialInstanceName; materialInstanceName = void 0;
constructor(playerId) { constructor(playerId) {
this.playerId = playerId; this.playerId = playerId;
@@ -27,20 +27,21 @@ export class StructureInstance {
delete this.structure; delete this.structure;
delete this.outliner; delete this.outliner;
delete this.verifier; delete this.verifier;
delete this.materials;
} }
refreshBox() { refreshBox() {
if (!this.materials)
this.materials = new StructureMaterials(this);
this.materials.refresh();
if (!this.hasLocation()) if (!this.hasLocation())
return; return;
if (!this.outliner) if (!this.outliner)
this.outliner = new StructureOutliner(this); this.outliner = new StructureOutliner(this);
if (!this.verifier) if (!this.verifier)
this.verifier = new StructureVerifier(this, { isEnabled: this.options.verifier.isEnabled, trackPlayerDistance: this.options.verifier.trackPlayerDistance }); this.verifier = new StructureVerifier(this, { isEnabled: this.options.verifier.isEnabled, trackPlayerDistance: this.options.verifier.trackPlayerDistance });
if (!this.materials)
this.materials = new StructureMaterials(this);
this.outliner.refresh(); this.outliner.refresh();
this.verifier.refresh(); this.verifier.refresh();
this.materials.refresh();
} }
getName() { getName() {
@@ -186,8 +187,8 @@ export class StructureInstance {
} }
place(dimensionId, worldLocation) { place(dimensionId, worldLocation) {
this.move(dimensionId, worldLocation);
this.enable(); this.enable();
this.move(dimensionId, worldLocation);
} }
move(dimensionId, worldLocation) { move(dimensionId, worldLocation) {
@@ -1,6 +1,7 @@
import { MaterialsFormBuilder } from './MaterialsFormBuilder'; import { MaterialsFormBuilder } from './MaterialsFormBuilder';
import { forceShow } from '../../utils'; import { forceShow } from '../../utils';
import { Builders } from '../Builder/Builders'; import { Builders } from '../Builder/Builders';
import { structureCollection } from '../Structure/StructureCollection';
export class MaterialsForm { export class MaterialsForm {
constructor(player) { constructor(player) {
@@ -10,14 +11,13 @@ export class MaterialsForm {
show() { show() {
try { try {
return forceShow(this.player, MaterialsFormBuilder.buildInstanceSelector()).then((response) => { return forceShow(this.player, MaterialsFormBuilder.buildInstanceSelector(this.player)).then((response) => {
if (response.canceled) if (response.canceled)
return; return;
let selection = response.selection; const selectedInstanceName = structureCollection.getInstanceNames()[response.selection];
const selectedInstanceName = structureCollection.getInstanceNames()[selection];
if (selectedInstanceName) { if (selectedInstanceName) {
this.setActiveInstance(selectedInstanceName); this.setActiveInstance(selectedInstanceName);
this.player.sendMessage(`§8Selected instance for material grabber: §2${selectedInstanceName}`); this.player.sendMessage(`§7Selected instance for material grabber: §2${selectedInstanceName}`);
return; return;
} }
}); });
@@ -1,12 +1,22 @@
import { ActionFormData } from "@minecraft/server-ui";
import { MenuFormBuilder } from "../MenuFormBuilder"; import { MenuFormBuilder } from "../MenuFormBuilder";
import { structureCollection } from "../Structure/StructureCollection";
import { Builders } from "../Builder/Builders";
export class InstanceFormBuilder { export class MaterialsFormBuilder {
menuTitle = MenuFormBuilder.menuTitle + ' Material Grabber'; static menuTitle = MenuFormBuilder.menuTitle + ' Material Grabber';
static buildInstanceSelector() { static buildInstanceSelector(player) {
const allInstanceNameForm = new ActionFormData() const allInstanceNameForm = new ActionFormData()
.title(this.menuTitle) .title(this.menuTitle);
.body('Select an instance:'); const currInstanceName = Builders.get(player.id).materialInstanceName;
let body = '§7Current instance: ';
if (currInstanceName)
body += `§2${currInstanceName}`;
else
body += '§7None';
body += '\n§7Select an instance:';
allInstanceNameForm.body(body);
structureCollection.getInstanceNames().forEach(instanceName => { structureCollection.getInstanceNames().forEach(instanceName => {
allInstanceNameForm.button(`§2${instanceName}`); allInstanceNameForm.button(`§2${instanceName}`);
}); });
@@ -9,12 +9,45 @@ class StructureMaterials {
refresh() { refresh() {
this.clear(); this.clear();
this.populateInstance();
}
populateInstance() {
try {
if (this.instance.hasLocation())
this.populateActive(); this.populateActive();
else
this.populateAll();
} catch (e) {
if (e.name === 'InstanceNotPlacedError')
this.clear();
else
throw e;
}
}
get(itemType) {
return this.materials[itemType];
}
isEmpty() {
return Object.keys(this.materials).length === 0;
}
has(itemType) {
return this.materials[itemType] !== undefined;
}
remove(itemType, amount) {
if (!this.materials[itemType]) return;
this.materials[itemType].count -= amount;
if (this.materials[itemType].count <= 0)
delete this.materials[itemType];
} }
populateAll() { populateAll() {
for (const layer = 0; layer < this.instance.getMaxLayer(); layer++) for (let layer = 0; layer < this.instance.getMaxLayer(); layer++)
this.getLayer(layer) this.populateLayer(layer)
} }
populateLayer(layer) { populateLayer(layer) {
@@ -59,7 +59,14 @@ export class MenuForm {
const structureId = await this.getStructureId(); const structureId = await this.getStructureId();
if (!structureId) if (!structureId)
return; return;
try {
structureCollection.add(instanceName, structureId); structureCollection.add(instanceName, structureId);
} catch (e) {
if (e.name === 'InvalidInstanceError') {
this.player.sendMessage(`§cInstance '${instanceName}' already exists. Try again with a new name.`);
return void 0;
}
}
return instanceName; return instanceName;
}); });
} }
@@ -8,7 +8,7 @@ const builderOption = new BuilderOption({
identifier: 'materialGrabber', identifier: 'materialGrabber',
displayName: 'Material Grabber', displayName: 'Material Grabber',
description: 'Pulls structure items from inventories.', description: 'Pulls structure items from inventories.',
howToUse: "Interact with inventories using a paper named 'Material Grabber' to pull structure items from them.", howToUse: "Interact with inventories using an item named 'Material Grabber' to pull structure items from them.",
}); });
world.beforeEvents.itemUse.subscribe(onItemUse); world.beforeEvents.itemUse.subscribe(onItemUse);
@@ -19,7 +19,7 @@ function onItemUse(event) {
if (!isActionItem(event.itemStack) || !builderOption.isEnabled(event.source.id)) if (!isActionItem(event.itemStack) || !builderOption.isEnabled(event.source.id))
return; return;
event.cancel = true; event.cancel = true;
new MaterialsForm(event.source); system.run(() => new MaterialsForm(event.source));
} }
function onPlayerInteract(event) { function onPlayerInteract(event) {
@@ -30,50 +30,81 @@ function onPlayerInteract(event) {
if (target instanceof Player) if (target instanceof Player)
return; return;
const materials = getActiveMaterials(player); const materials = getActiveMaterials(player);
if (!materials)
return;
const targetContainer = target.getComponent(EntityComponentTypes.Inventory)?.container; const targetContainer = target.getComponent(EntityComponentTypes.Inventory)?.container;
const playerContainer = player.getComponent(EntityComponentTypes.Inventory)?.container; if (!targetContainer || materials.isEmpty())
if (!targetContainer || !playerContainer)
return; return;
event.cancel = true; event.cancel = true;
system.run(() => { system.run(() => transferMaterialsToPlayer(player, targetContainer, materials));
transferMaterialsToPlayer(targetContainer, playerContainer, materials);
});
} }
function isActionItem(itemStack) { function isActionItem(itemStack) {
return itemStack?.typeId === 'minecraft:paper' && itemStack?.nameTag === 'Material Grabber'; return itemStack?.nameTag === 'Material Grabber';
} }
function getActiveMaterials(player) { function getActiveMaterials(player) {
const focusedInstanceName = Builders.get(player.id).materialInstanceName; const focusedInstanceName = Builders.get(player.id).materialInstanceName;
if (!focusedInstanceName)
return void 0;
const structure = structureCollection.get(focusedInstanceName); const structure = structureCollection.get(focusedInstanceName);
if (!structure) if (!structure)
return []; return void 0;
return structure.getActiveMaterials(); return structure.getActiveMaterials();
} }
function transferMaterialsToPlayer(targetContainer, playerContainer, materials) { function transferMaterialsToPlayer(player, targetContainer, materials) {
const playerContainer = player.getComponent(EntityComponentTypes.Inventory)?.container;
if (!playerContainer)
return;
ignoreAlreadyGathered(materials, playerContainer);
let transferCount = 0;
for (let slotIndex = 0; slotIndex < targetContainer.size; slotIndex++) { for (let slotIndex = 0; slotIndex < targetContainer.size; slotIndex++) {
const slot = targetContainer.getSlot(slotIndex); const slot = targetContainer.getSlot(slotIndex);
tryTransferToPlayer(slot, playerContainer, materials); transferCount += tryTransferToPlayer(slot, playerContainer, materials);
}
sendTransferMessage(player, transferCount);
materials.refresh();
}
function ignoreAlreadyGathered(materials, playerContainer) {
for (let slotIndex = 0; slotIndex < playerContainer.size; slotIndex++) {
const slot = playerContainer.getSlot(slotIndex);
if (slot.hasItem()) {
materials.remove(slot.typeId, slot.amount);
}
}
}
function sendTransferMessage(player, transferCount) {
if (transferCount === 0) {
player.onScreenDisplay.setActionBar('§7Grabbed 0 items.');
} else if (transferCount === 1) {
player.onScreenDisplay.setActionBar('§aGrabbed 1 item.');
} else {
player.onScreenDisplay.setActionBar(`§aGrabbed ${transferCount} item(s).`);
} }
} }
function tryTransferToPlayer(slot, playerContainer, materials) { function tryTransferToPlayer(slot, playerContainer, materials) {
if (slot.hasItem() && materials[slot.typeId]) { if (slot.hasItem() && materials.has(slot.typeId)) {
const grabAmount = Math.min(slot.amount, materials[slot.typeId].count); const grabAmount = Math.min(slot.amount, materials.get(slot.typeId).count);
if (grabAmount > 0) if (grabAmount > 0)
tryTransferAmountToPlayer(slot, playerContainer, materials, grabAmount); return tryTransferAmountToPlayer(slot, playerContainer, materials, grabAmount);
} }
return 0;
} }
function tryTransferAmountToPlayer(slot, playerContainer, materials, grabAmount) { function tryTransferAmountToPlayer(slot, playerContainer, materials, grabAmount) {
const itemStack = slot.getItem(); const itemStack = slot.getItem();
if (canAddItem(playerContainer, itemStack)) { if (canAddItem(playerContainer, itemStack)) {
addItem(playerContainer, itemStack); const itemStackToAdd = new ItemStack(itemStack.typeId, grabAmount);
materials[slot.typeId].count -= grabAmount; addItem(playerContainer, itemStackToAdd);
materials.remove(itemStack.typeId, grabAmount);
removeAmount(slot, grabAmount); removeAmount(slot, grabAmount);
return grabAmount;
} }
return 0;
} }
function removeAmount(slot, amount) { function removeAmount(slot, amount) {
@@ -131,3 +162,7 @@ function emptySlotPass(inventory, itemStack) {
} }
return false; return false;
} }
function isSlotAvailableForStacking(slot, itemStack) {
return slot.hasItem() && slot.isStackableWith(itemStack) && slot.amount !== slot.maxAmount;
}
+2 -1
View File
@@ -15,6 +15,7 @@ Give yourself the tools to ease the survival building process with Construct: an
- **Block Validation**: Highlights incorrectly placed blocks. - **Block Validation**: Highlights incorrectly placed blocks.
- **Easy Place**: Always places blocks correctly. - **Easy Place**: Always places blocks correctly.
- **Material Grabbing**: Pulls the required materials from chests in just one click.
- **Layered Display**: Build structures in layers. - **Layered Display**: Build structures in layers.
- **Structure Management**: Create and edit many structures at once. - **Structure Management**: Create and edit many structures at once.
@@ -52,7 +53,7 @@ Shows the construct form. Only available while **Canopy** is installed.
- [x] Structure naming & movement - [x] Structure naming & movement
- [x] Easyplace - [x] Easyplace
- [x] Correct block placement checking - [x] Correct block placement checking
- [ ] Automatic material gathering from inventories - [x] Automatic material gathering from inventories
- [ ] Structure Mirroring & Rotation - [ ] Structure Mirroring & Rotation
- [ ] Structure Merging into SuperStructures - [ ] Structure Merging into SuperStructures