Skip to content

Commit

Permalink
feat: added initial script for repairing anvil and reducing iron ingo…
Browse files Browse the repository at this point in the history
…t stack by 1, and command handler
  • Loading branch information
Adr-hyng committed Aug 13, 2024
1 parent 83775fe commit 03f4524
Show file tree
Hide file tree
Showing 42 changed files with 7,855 additions and 476 deletions.
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"request": "attach",
"name": "Debug with Minecraft",
"mode": "listen",
"targetModuleUuid": "3bbf8878-aa5c-4485-ae6d-4ce20c3302ad",
"targetModuleUuid": "253aabda-5a62-4027-aab9-fbaa369f28e0",
"localRoot": "${workspaceFolder}/BP/scripts/",
"generatedSourceRoot": "${workspaceFolder}/BP/scripts/",
"port": 19144
Expand Down
6 changes: 3 additions & 3 deletions BP/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"header": {
"name": "Anvil Repairing BP 1.0.0 [DEBUG]",
"description": "Repair your anvils with as simple as iron ingots to extend its lifespan, and use hammer to damage it without breaking the block.\n @Made By: https://twitter.com/h_YanG_0A",
"uuid": "38e85a3b-4d2a-4980-894d-65778f80b8ae",
"uuid": "8699f58d-1fa2-4af6-85cb-1cbe713d2511",
"version": [
1,
0,
Expand Down Expand Up @@ -45,7 +45,7 @@
"dependencies": [
{
"module_name": "@minecraft/server",
"version": "1.11.0"
"version": "1.12.0-beta"
},
{
"module_name": "@minecraft/server-ui",
Expand All @@ -56,7 +56,7 @@
"version": "1.0.0-beta"
},
{
"uuid": "13d7cd65-887f-4d74-87cd-c4c7595062b2",
"uuid": "f7ea8b5b-c129-4ab7-b813-3120c4adba6c",
"version": [
1,
0,
Expand Down
6 changes: 6 additions & 0 deletions BP/scripts/anvil_states.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export var AnvilStates;
(function (AnvilStates) {
AnvilStates["LOW"] = "undamaged";
AnvilStates["MEDIUM"] = "slightly_damaged";
AnvilStates["HIGH"] = "very_damaged";
})(AnvilStates || (AnvilStates = {}));
1 change: 1 addition & 0 deletions BP/scripts/commands/ICommandBase.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {};
8 changes: 8 additions & 0 deletions BP/scripts/commands/command_handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { ADDON_IDENTIFIER } from "constant";
export const CommandHandler = {
prefix: `/scriptevent ${ADDON_IDENTIFIER} `,
commands: [
'help',
'dev_helper'
]
};
Empty file added BP/scripts/commands/config.js
Empty file.
39 changes: 39 additions & 0 deletions BP/scripts/commands/dev_helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { CommandHandler } from "commands/command_handler";
import { world } from "@minecraft/server";
var REQUIRED_PARAMETER;
(function (REQUIRED_PARAMETER) {
REQUIRED_PARAMETER["TEST"] = "test";
})(REQUIRED_PARAMETER || (REQUIRED_PARAMETER = {}));
const command = {
name: 'dev_helper',
description: 'Developer Utility Command',
format: `[${Object.values(REQUIRED_PARAMETER).join('|')}]`,
usage() {
return (`
Format:
> ${CommandHandler.prefix}${this.name} ${this.format}
Usage:
> ${CommandHandler.prefix}${this.name} ${REQUIRED_PARAMETER.TEST} = TEST a Working-in-progress features.
`).replaceAll(" ", "");
},
execute(player, args) {
if (!(args && args.length))
return;
const requiredParams = (`[${Object.values(REQUIRED_PARAMETER).join('|')}]`).slice(1, -1).split('|').map(command => command.trim());
const selectedReqParam = args[0].toLowerCase();
if (!requiredParams.includes(selectedReqParam))
return player.sendMessage("§cInvalid Usage Format." + command.usage());
if (!player.isOp())
return;
switch (selectedReqParam) {
case REQUIRED_PARAMETER.TEST:
if (!player.isOp())
break;
world.sendMessage("HELLO WORLD!");
break;
default:
break;
}
}
};
export default command;
54 changes: 54 additions & 0 deletions BP/scripts/commands/help.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { CommandHandler } from './command_handler';
import { ADDON_NAME } from 'constant';
const importCommand = async (player, commandName) => {
try {
const importedCommandModule = await import(`./${commandName}.js`);
return importedCommandModule.default;
}
catch (error) {
player.sendMessage(`§cError while fetching ${commandName} command: ${error.message}`);
return null;
}
};
const details = {
__addonName__: ADDON_NAME,
__name__: 'help',
__description__: 'Displays the help message.',
__format__: '[<commandName: string>?]',
};
const command = {
name: details.__name__,
description: details.__description__,
format: details.__format__,
usage() {
return (`Format:
> ${CommandHandler.prefix}${this.name} ${this.format}
Usage:
> ${CommandHandler.prefix}${this.name}
> ${CommandHandler.prefix}${this.name} config
`).replaceAll(" ", "");
},
async execute(player, args) {
if (!args || args.length === 0) {
let helpMessage = `\n§aCommands available @ ${details.__addonName__}: \n`;
for (const commandName of CommandHandler.commands) {
const importedCommand = await importCommand(player, commandName);
if (importedCommand)
helpMessage += `§e${CommandHandler.prefix}${commandName}§r${importedCommand.format.length ? " " + importedCommand.format : ""} - ${importedCommand.description}\n`;
}
player.sendMessage(helpMessage);
}
else {
const specifiedCommand = args[0].toLowerCase();
if (!CommandHandler.commands.includes(specifiedCommand))
return player.sendMessage(`§cInvalid command specified: ${specifiedCommand}`);
if (CommandHandler.commands.includes(specifiedCommand)) {
const importedCommand = await importCommand(player, specifiedCommand);
if (importedCommand) {
player.sendMessage(`\n§e${CommandHandler.prefix}${specifiedCommand}: \n${importedCommand.description}§r ${importedCommand.usage()}`);
}
}
}
}
};
export default command;
8 changes: 8 additions & 0 deletions BP/scripts/configuration/config_handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import Configuration from "./server_configuration";
export let SERVER_CONFIGURATION = {
...Configuration
};
const originalServerConfiguration = JSON.parse(JSON.stringify(Configuration));
export const resetServerConfiguration = () => SERVER_CONFIGURATION = originalServerConfiguration;
export const getServerConfiguration = () => SERVER_CONFIGURATION;
export const setServerConfiguration = (newConfig) => SERVER_CONFIGURATION = newConfig;
Empty file.
4 changes: 4 additions & 0 deletions BP/scripts/configuration/server_configuration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default {
debug: true,
};
export const VERSION = "1.0.0";
17 changes: 17 additions & 0 deletions BP/scripts/constant.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { JsonDatabase } from "./utils/Database/con-database";
export const ADDON_NAMESPACE = "yn";
export const ADDON_NAME = "ANVIL_REPAIR";
export const ADDON_IDENTIFIER = `${ADDON_NAMESPACE}:anvrep`;
export const db = new JsonDatabase(ADDON_NAME);
export var AnvilDamageStates;
(function (AnvilDamageStates) {
AnvilDamageStates["UNDAMAGED"] = "undamaged";
AnvilDamageStates["USED"] = "slightly_damaged";
AnvilDamageStates["BROKEN"] = "very_damaged";
})(AnvilDamageStates || (AnvilDamageStates = {}));
export var AnvilStateTypes;
(function (AnvilStateTypes) {
AnvilStateTypes["DIRECTION"] = "direction";
AnvilStateTypes["DAMAGE"] = "damage";
AnvilStateTypes["CARDINAL_DIRECTION"] = "minecraft:cardinal_direction";
})(AnvilStateTypes || (AnvilStateTypes = {}));
98 changes: 98 additions & 0 deletions BP/scripts/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { world, system, Player, ScriptEventSource, EntityInventoryComponent } from "@minecraft/server";
import { ADDON_IDENTIFIER, AnvilDamageStates, AnvilStateTypes } from "./constant";
import { MinecraftBlockTypes, MinecraftItemTypes } from "vanilla-types/index";
const playerBeingShown = new Map();
export const itemInteractedLogMap = new Map();
import('@minecraft/server-ui').then((ui) => {
var [userBusy, userClosed] = Object.values(ui.FormCancelationReason), formData;
for (formData of [ui.ActionFormData, ui.MessageFormData, ui.ModalFormData]) {
const formShow = Object.getOwnPropertyDescriptor(formData.prototype, "show").value;
Object.defineProperty(formData.prototype, "show", {
value: function (player, persistent = false, trials = 10) {
const show = formShow.bind(this, player);
if (player.id in playerBeingShown)
return;
playerBeingShown[player.id] = true;
return new Promise(async (resolve) => {
let result;
do {
result = await show();
if (!trials-- || persistent && result.cancelationReason === userClosed)
return delete playerBeingShown[player.id];
} while (result.cancelationReason === userBusy);
delete playerBeingShown[player.id];
resolve(result);
});
}
});
}
;
});
world.beforeEvents.playerInteractWithBlock.subscribe((e) => {
const blockInteracted = e.block;
const heldItem = e.itemStack;
const player = e.player;
if (!heldItem)
return;
if (!heldItem.matches(MinecraftItemTypes.IronIngot))
return;
if (!blockInteracted.matches(MinecraftBlockTypes.Anvil))
return;
if (!player.isSneaking)
return;
const anvilDamageStage = blockInteracted.permutation.getState(AnvilStateTypes.DAMAGE);
const PreviousAnvilDamageMapper = new Map([
[AnvilDamageStates.USED, blockInteracted.permutation.withState(AnvilStateTypes.DAMAGE, AnvilDamageStates.UNDAMAGED)],
[AnvilDamageStates.BROKEN, blockInteracted.permutation.withState(AnvilStateTypes.DAMAGE, AnvilDamageStates.USED)],
]);
const prevAnvilState = PreviousAnvilDamageMapper.get(anvilDamageStage);
if (!prevAnvilState)
return;
system.run(() => {
const oldLog = itemInteractedLogMap.get(player.id);
itemInteractedLogMap.set(player.id, Date.now());
if ((oldLog + 150) >= Date.now())
return;
blockInteracted.setPermutation(prevAnvilState);
e.cancel = true;
if (heldItem.amount > 1) {
player.playSound('random.anvil_use');
heldItem.amount -= 1;
const deductedIronIngot = heldItem.clone();
player.getComponent(EntityInventoryComponent.componentId).container.setItem(player.selectedSlotIndex, deductedIronIngot);
}
else {
player.playSound('random.break');
player.getComponent(EntityInventoryComponent.componentId).container.setItem(player.selectedSlotIndex, undefined);
}
});
});
system.afterEvents.scriptEventReceive.subscribe((event) => {
if (event.sourceType !== ScriptEventSource.Entity)
return;
if (!(event.sourceEntity instanceof Player))
return;
if (event.id !== ADDON_IDENTIFIER)
return;
const player = event.sourceEntity;
const message = event.message;
const args = message.trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
system.run(async () => {
try {
const { default: CommandObject } = await import(`./commands/${cmd}.js`);
CommandObject.execute(player, args);
}
catch (err) {
if (err instanceof ReferenceError) {
player.sendMessage(`§cInvalid Command ${cmd}\nCheck If The Command Actually Exists. Use /scriptevent ${ADDON_IDENTIFIER} help`);
}
else {
console.error(err);
}
}
});
});
world.afterEvents.playerLeave.subscribe((event) => {
delete playerBeingShown[event.playerId];
});
Loading

0 comments on commit 03f4524

Please sign in to comment.