sapdon 3.2.0 → 3.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/package.json +3 -2
  2. package/prod/cli/start.js +36 -5
  3. package/prod/core/index.d.ts +9 -8
  4. package/prod/core/index.js +1 -3
  5. package/prod/oc/index.d.ts +2 -1
  6. package/prod/utils/index.d.ts +2 -1
  7. package/src/templates/js_sapdon/build.config +23 -0
  8. package/src/templates/js_sapdon/main.mjs +4 -0
  9. package/src/templates/js_sapdon/mod.info +7 -0
  10. package/src/templates/js_sapdon/pack_icon.png +0 -0
  11. package/src/templates/js_sapdon/package.json +20 -0
  12. package/src/templates/js_sapdon/res/animations/animation_item.animation.json +34 -0
  13. package/src/templates/js_sapdon/res/animations/large_item.animation.json +27 -0
  14. package/src/templates/js_sapdon/res/models/blocks/crop.geo.json +48 -0
  15. package/src/templates/js_sapdon/res/models/entity/animation/animation_item.geo.json +26 -0
  16. package/src/templates/js_sapdon/res/models/entity/animation/large_item.geo.json +28 -0
  17. package/src/templates/js_sapdon/res/textures/blocks/none.png +0 -0
  18. package/src/templates/js_sapdon/res/textures/blocks/test_log_oak.png +0 -0
  19. package/src/templates/js_sapdon/res/textures/blocks/test_log_top.png +0 -0
  20. package/src/templates/js_sapdon/res/textures/items/masterball.png +0 -0
  21. package/src/templates/js_sapdon/scripts/custom_components/cropComponent.js +50 -0
  22. package/src/templates/js_sapdon/scripts/custom_components/items/gui_book.js +37 -0
  23. package/src/templates/js_sapdon/scripts/custom_components/registry.js +25 -0
  24. package/src/templates/js_sapdon/scripts/index.js +0 -0
  25. package/src/templates/ts_sapdon/build.config +23 -0
  26. package/src/templates/ts_sapdon/main.ts +11 -0
  27. package/src/templates/ts_sapdon/mod.info +7 -0
  28. package/src/templates/ts_sapdon/pack_icon.png +0 -0
  29. package/src/templates/ts_sapdon/package.json +20 -0
  30. package/src/templates/ts_sapdon/res/models/blocks/crop.geo.json +48 -0
  31. package/src/templates/ts_sapdon/res/textures/blocks/test_log_oak.png +0 -0
  32. package/src/templates/ts_sapdon/res/textures/blocks/test_log_top.png +0 -0
  33. package/src/templates/ts_sapdon/res/textures/items/masterball.png +0 -0
  34. package/src/templates/ts_sapdon/scripts/components/cropComponent.ts +44 -0
  35. package/src/templates/ts_sapdon/scripts/components/items/guiBook.ts +36 -0
  36. package/src/templates/ts_sapdon/scripts/components/registry.ts +24 -0
  37. package/src/templates/ts_sapdon/scripts/index.ts +7 -0
  38. package/src/templates/ts_sapdon/tsconfig.json +117 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sapdon",
3
- "version": "3.2.0",
3
+ "version": "3.2.2",
4
4
  "scripts": {
5
5
  "build": "node scripts/build.cjs",
6
6
  "pub": "npm run build && npm publish"
@@ -46,6 +46,7 @@
46
46
  },
47
47
  "files": [
48
48
  "prod/**/*",
49
- "doc/**/*"
49
+ "doc/**/*",
50
+ "src/templates/**/*"
50
51
  ]
51
52
  }
package/prod/cli/start.js CHANGED
@@ -7,11 +7,8 @@ import fs, { readFileSync } from 'fs';
7
7
  import { randomUUID } from 'crypto';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import cp from 'child_process';
10
- import { cacheSync } from '@sapdon/utils/cache.js';
11
10
  import fs$1 from 'fs/promises';
12
- import { serialize } from '@sapdon/utils/index.js';
13
11
  import http from 'http';
14
- import { handleRemoteLogger } from '@sapdon/cli/remoteLogger/server.js';
15
12
  import { rollup } from 'rollup';
16
13
  import commonjs from '@rollup/plugin-commonjs';
17
14
  import { nodeResolve } from '@rollup/plugin-node-resolve';
@@ -112,6 +109,17 @@ function parseJsonWithComments(jsonStr) {
112
109
  return JSON.parse(String(jsonStr).replace(/\/\/.*|\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, "$1"));
113
110
  }
114
111
 
112
+ const caches = new Map();
113
+ function cacheSync(uri, setter) {
114
+ let value = caches.get(uri);
115
+ if (value) {
116
+ return value;
117
+ }
118
+ value = setter(uri);
119
+ caches.set(uri, value);
120
+ return value;
121
+ }
122
+
115
123
  function getBuildConfig() {
116
124
  const pwd = getProjectPath();
117
125
  const configFile = path.join(pwd, 'build.config');
@@ -378,6 +386,9 @@ if (!Symbol.metadata) {
378
386
  //@ts-ignore
379
387
  Symbol.metadata = Symbol('[[metadata]]');
380
388
  }
389
+ function getMetadata(target) {
390
+ return target?.[Symbol.metadata];
391
+ }
381
392
 
382
393
  // 因为无法判断其他代码实现的接口是否真的是RawType,所以用Symbol来标记
383
394
  // 只要不export,其他代码就无法访问这个Symbol, 确保了唯一性
@@ -418,6 +429,21 @@ function jsonEncoderReplacer(_, v) {
418
429
  }
419
430
  throw new Error('Unexpected value');
420
431
  }
432
+ const defaultSerializer = instance => {
433
+ return structuredClone(instance);
434
+ };
435
+ const serializerSymbol = Symbol('serializer');
436
+ const serializerMapping = new WeakMap();
437
+ function serialize(inst) {
438
+ const ctor = Reflect.getPrototypeOf(inst)?.constructor;
439
+ if (!ctor) {
440
+ throw new Error('Cannot serialize an instance of an anonymous class');
441
+ }
442
+ const serializer = getMetadata(ctor)?.[serializerSymbol]
443
+ ?? serializerMapping.get(ctor)
444
+ ?? defaultSerializer;
445
+ return serializer.call(inst, inst);
446
+ }
421
447
  const jsonEncodeDecoder = {
422
448
  encode(value) {
423
449
  return JSON.stringify(value, jsonEncoderReplacer);
@@ -553,6 +579,10 @@ class UISystemRegistryServer {
553
579
  }
554
580
  }
555
581
 
582
+ async function handleRemoteLogger({ level, message, timeStamp, stack }) {
583
+ console[level](message, stack, `\nat ${new Date(timeStamp).toLocaleString()}`);
584
+ }
585
+
556
586
  const clientRegistryData = [];
557
587
  /**
558
588
  * Client
@@ -754,7 +784,7 @@ function getGamePath() {
754
784
  }
755
785
 
756
786
  var name = "sapdon";
757
- var version = "3.2.0";
787
+ var version = "3.2.2";
758
788
  var scripts = {
759
789
  build: "node scripts/build.cjs",
760
790
  pub: "npm run build && npm publish"
@@ -800,7 +830,8 @@ var dependencies = {
800
830
  };
801
831
  var files = [
802
832
  "prod/**/*",
803
- "doc/**/*"
833
+ "doc/**/*",
834
+ "src/templates/**/*"
804
835
  ];
805
836
  var packageJson = {
806
837
  name: name,
@@ -1406,13 +1406,13 @@ declare class ContainerUISystem {
1406
1406
  declare const ServerFormSystem: UISystem;
1407
1407
  declare const form_button_panel: Panel;
1408
1408
  declare class ServerUISystem {
1409
- static "__#1053@#binding_map": Map<any, any>;
1410
- static "__#1053@#binding_title_list": any[];
1409
+ static "__#659@#binding_map": Map<any, any>;
1410
+ static "__#659@#binding_title_list": any[];
1411
1411
  static addBindingTitle(title_name: any): void;
1412
1412
  static getBindingTitleList(): any[];
1413
1413
  static getBindingContentList(): any[];
1414
1414
  static bindingTitlewithContent(title_name: any, content: any): void;
1415
- static "__#1053@#updateServerFormSystem"(): void;
1415
+ static "__#659@#updateServerFormSystem"(): void;
1416
1416
  }
1417
1417
 
1418
1418
  declare class Guidebook {
@@ -1621,15 +1621,15 @@ declare class DataBindingObject {
1621
1621
  }
1622
1622
 
1623
1623
  declare class UISystemRegistry {
1624
- static "__#1050@#ui_system_map": {};
1625
- static "__#1050@#ui_def_list": any[];
1624
+ static "__#656@#ui_system_map": {};
1625
+ static "__#656@#ui_def_list": any[];
1626
1626
  static registerUISystem(ui_system: any): void;
1627
1627
  static addOuterUIdefs(ui_defs: any): void;
1628
1628
  static submit(): void;
1629
1629
  }
1630
1630
  declare class UISystemRegistryServer {
1631
- static "__#1051@#ui_system_map": {};
1632
- static "__#1051@#ui_def_list": any[];
1631
+ static "__#657@#ui_system_map": {};
1632
+ static "__#657@#ui_def_list": any[];
1633
1633
  static getUISystemList(): any[];
1634
1634
  static getUIdefList(): any[];
1635
1635
  static startServer(): void;
@@ -2741,4 +2741,5 @@ declare namespace FlipbookTextures {
2741
2741
  function registerFlipbookTexture(atlas_tile: any, texture: any, ticks_per_frame: any, options?: {}): void;
2742
2742
  }
2743
2743
 
2744
- export { BlockAPI, BlockComponent, Button, ButtonMapping$1 as ButtonMapping, ChestUISystem, CollectionPanel, type ConstructorOf, ContainerUISystem, Control, DataBinding, DataBindingObject, type EncodeDecoder, EntityAPI, Factory, FeatureAPI, FlipbookTextures, type FloatLiteral, Grid, GridProp, Guidebook, type ISerializer, Image, Input, ItemAPI, ItemCategory, ItemComponent, ItemTextureManager, Label, Layout, Matrix, Modifications, Panel, type RawType, RecipeAPI, ScrollView, ScrollingPanel, Serializable, Serializer, ServerFormSystem, ServerUISystem, Sound, Sprite, StackPanel, Text, UIElement, UISystem, UISystemRegistry, UISystemRegistryServer, Vec3, Vec4, type Vector3, type Vector4, decode, defaultSerializer, encode, f64, form_button_panel, getMetadata, getOrCreateMetadata, isRawJSON, jsonEncodeDecoder, jsonEncoderReplacer, registry, serialize, terrainTextureManager };
2744
+ export { BlockAPI, BlockComponent, Button, ButtonMapping$1 as ButtonMapping, ChestUISystem, CollectionPanel, ContainerUISystem, Control, DataBinding, DataBindingObject, EntityAPI, Factory, FeatureAPI, FlipbookTextures, Grid, GridProp, Guidebook, Image, Input, ItemAPI, ItemCategory, ItemComponent, ItemTextureManager, Label, Layout, Matrix, Modifications, Panel, RecipeAPI, ScrollView, ScrollingPanel, Serializable, Serializer, ServerFormSystem, ServerUISystem, Sound, Sprite, StackPanel, Text, UIElement, UISystem, UISystemRegistry, UISystemRegistryServer, Vec3, Vec4, decode, defaultSerializer, encode, f64, form_button_panel, getMetadata, getOrCreateMetadata, isRawJSON, jsonEncodeDecoder, jsonEncoderReplacer, registry, serialize, terrainTextureManager };
2745
+ export type { ConstructorOf, EncodeDecoder, FloatLiteral, ISerializer, RawType, Vector3, Vector4 };
@@ -1,6 +1,4 @@
1
- import { serialize as serialize$1 } from '@sapdon/utils/index.js';
2
1
  import http from 'http';
3
- import '@sapdon/cli/remoteLogger/server.js';
4
2
 
5
3
  class BlockComponent {
6
4
  static setTick(interval_range, looping) {
@@ -1498,7 +1496,7 @@ class GRegistry {
1498
1496
  static register(name, root, path, data) {
1499
1497
  data = data === 'string'
1500
1498
  ? JSON.parse(data)
1501
- : serialize$1(data);
1499
+ : serialize(data);
1502
1500
  clientRegistryData.push({ name, root, path, data });
1503
1501
  }
1504
1502
  static submit() {
@@ -139,4 +139,5 @@ declare class PlayerInputCompatibilityComponent extends BaseComponent {
139
139
  onTick(manager: ComponentManager, en: Optional<Entity>): void;
140
140
  }
141
141
 
142
- export { Actor, BaseComponent, type BasicComponent, type Component, type ComponentCtor, type ComponentDescriptor, ComponentManager, CustomComponent, InputChangeState, Optional, PlayerInputCompatibilityComponent, PlayerInputComponent, RequireComponents, type RequiredComponent, oc };
142
+ export { Actor, BaseComponent, ComponentManager, CustomComponent, InputChangeState, Optional, PlayerInputCompatibilityComponent, PlayerInputComponent, RequireComponents, oc };
143
+ export type { BasicComponent, Component, ComponentCtor, ComponentDescriptor, RequiredComponent };
@@ -38,4 +38,5 @@ declare const f64: (literal: FloatLiteral) => {
38
38
  };
39
39
  declare function isRawJSON(v: any): boolean;
40
40
 
41
- export { type ConstructorOf, type EncodeDecoder, type FloatLiteral, type ISerializer, type RawType, Serializable, Serializer, decode, defaultSerializer, encode, f64, getMetadata, getOrCreateMetadata, isRawJSON, jsonEncodeDecoder, jsonEncoderReplacer, serialize };
41
+ export { Serializable, Serializer, decode, defaultSerializer, encode, f64, getMetadata, getOrCreateMetadata, isRawJSON, jsonEncodeDecoder, jsonEncoderReplacer, serialize };
42
+ export type { ConstructorOf, EncodeDecoder, FloatLiteral, ISerializer, RawType };
@@ -0,0 +1,23 @@
1
+ {
2
+ "formatVersion": 2,
3
+ "buildOptions": {
4
+ "useHMR": true, // 热更新
5
+ "buildMode": "development", // 开发模式 'development' | 'production', production模式下会压缩代码
6
+ "buildEntry": "main.mjs", // Addon构建入口文件
7
+ "useJs": true, // 是否使用js文件
8
+ "scriptEntry": "scripts/index.js", // ScriptApi脚本入口文件
9
+ "scriptOutput": "scripts/index.js", // ScriptApi脚本输出文件 (在 buildDir 目录下)
10
+ "buildDir": "dev/", // 构建输出目录
11
+ "dependencies": [
12
+ {
13
+ "module_name": "@minecraft/server",
14
+ "version": "1.17.0"
15
+ }
16
+ ],
17
+ "resource": {
18
+ "path": "res/", // 资源文件目录
19
+ "resourceHints": true // 是否生成资源提示文件
20
+ }
21
+ },
22
+ "versionType": "release" // mc游戏版本, 会影响开发文件路径
23
+ }
@@ -0,0 +1,4 @@
1
+ import { registry } from '@sapdon/core'
2
+
3
+ // 提交所有注册
4
+ registry.submit()
@@ -0,0 +1,7 @@
1
+ {
2
+ "name":"mod名字",
3
+ "authors":["作者1","作者2"],
4
+ "version":"0.0.1",
5
+ "min_engine_version":"1.19.50",
6
+ "description":"mod介绍",
7
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "sapdon",
3
+ "version": "1.0.0",
4
+ "main": "main.mjs",
5
+ "scripts": {
6
+ "build": "sapdon build ./",
7
+ "postinstall": "sapdon lib"
8
+ },
9
+ "keywords": [
10
+ "bedrock",
11
+ "addon"
12
+ ],
13
+ "author": "",
14
+ "license": "ISC",
15
+ "type": "module",
16
+ "devDependencies": {
17
+ "@minecraft/server": "^1.17.0",
18
+ "@minecraft/server-ui": "^1.3.0"
19
+ }
20
+ }
@@ -0,0 +1,34 @@
1
+ {
2
+ "format_version": "1.8.0",
3
+ "animations": {
4
+ "animation.animation_item.default": {
5
+ "loop": true,
6
+ "bones": {
7
+ "body": {
8
+ "position": [0, 8, 0]
9
+ },
10
+ "rightitem": {
11
+ "rotation": [-80, 0, 0],
12
+ "position": [0, -3, 2]
13
+ }
14
+ }
15
+ },
16
+ "animation.animation_item.rotating": {
17
+ "loop": true,
18
+ "animation_length": 10,
19
+ "bones": {
20
+ "body": {
21
+ "rotation": {
22
+ "0.0": [0, 0, 0],
23
+ "10.0": [0, 360, 0]
24
+ },
25
+ "position": [0, 8, 0]
26
+ },
27
+ "rightitem": {
28
+ "rotation": [-80, 0, 0],
29
+ "position": [0, -3, 2]
30
+ }
31
+ }
32
+ }
33
+ }
34
+ }
@@ -0,0 +1,27 @@
1
+ {
2
+ "format_version": "1.10.0",
3
+ "animations": {
4
+ "animation.large_item.hold": {
5
+ "loop": true,
6
+ "bones": {
7
+ "rightitem": {
8
+ "position": [
9
+ "c.is_first_person ? -6 : 1",
10
+ "c.is_first_person ? 0 : -1",
11
+ "c.is_first_person ? -1 : -6"
12
+ ],
13
+ "rotation": [
14
+ "c.is_first_person ? 45 : 15",
15
+ "c.is_first_person ? -15 : 0",
16
+ "c.is_first_person ? 30 : -165"
17
+ ],
18
+ "scale": [
19
+ "c.is_first_person ? 1 : 0.5",
20
+ "c.is_first_person ? 1 : 0.5",
21
+ "c.is_first_person ? 1 : 0.5"
22
+ ]
23
+ }
24
+ }
25
+ }
26
+ }
27
+ }
@@ -0,0 +1,48 @@
1
+ {
2
+ "format_version": "1.21.20",
3
+ "minecraft:geometry": [
4
+ {
5
+ "description": {
6
+ "identifier": "geometry.crop",
7
+ "texture_width": 16,
8
+ "texture_height": 16
9
+ },
10
+ "bones": [
11
+ {
12
+ "name": "crop",
13
+ "pivot": [0, 0, 0],
14
+ "cubes": [
15
+ {
16
+ "origin": [-8, -1, -4],
17
+ "size": [16, 16, 0],
18
+ "uv": {
19
+ "south": { "uv": [0, 0], "uv_size": [16, 16] }
20
+ }
21
+ },
22
+ {
23
+ "origin": [-8, -1, 4],
24
+ "size": [16, 16, 0],
25
+ "uv": {
26
+ "north": { "uv": [0, 0], "uv_size": [16, 16] }
27
+ }
28
+ },
29
+ {
30
+ "origin": [4, -1, -8],
31
+ "size": [0, 16, 16],
32
+ "uv": {
33
+ "east": { "uv": [16, 0], "uv_size": [-16, 16] }
34
+ }
35
+ },
36
+ {
37
+ "origin": [-4, -1, -8],
38
+ "size": [0, 16, 16],
39
+ "uv": {
40
+ "west": { "uv": [16, 0], "uv_size": [-16, 16] }
41
+ }
42
+ }
43
+ ]
44
+ }
45
+ ]
46
+ }
47
+ ]
48
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "format_version": "1.12.0",
3
+ "minecraft:geometry": [
4
+ {
5
+ "description": {
6
+ "identifier": "geometry.animation_item",
7
+ "texture_width": 32,
8
+ "texture_height": 32,
9
+ "visible_bounds_width": 5,
10
+ "visible_bounds_height": 3.5,
11
+ "visible_bounds_offset": [0, 1.25, 0]
12
+ },
13
+ "bones": [
14
+ {
15
+ "name": "body",
16
+ "pivot": [0, 0, 0]
17
+ },
18
+ {
19
+ "name": "rightitem",
20
+ "parent": "body",
21
+ "pivot": [-0.3, 8, 0]
22
+ }
23
+ ]
24
+ }
25
+ ]
26
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "format_version": "1.16.0",
3
+ "minecraft:geometry": [
4
+ {
5
+ "description": {
6
+ "identifier": "geometry.large_item",
7
+ "texture_width": 16,
8
+ "texture_height": 16,
9
+ "visible_bounds_width": 2,
10
+ "visible_bounds_height": 1.5,
11
+ "visible_bounds_offset": [0, 0.25, 0]
12
+ },
13
+ "bones": [
14
+ {
15
+ "name": "rightitem",
16
+ "pivot": [0, 0, 0],
17
+ "texture_meshes": [
18
+ {
19
+ "texture": "default",
20
+ "position": [0, 0, 0],
21
+ "local_pivot": [8, 0, 8]
22
+ }
23
+ ]
24
+ }
25
+ ]
26
+ }
27
+ ]
28
+ }
@@ -0,0 +1,50 @@
1
+ import { EquipmentSlot, GameMode, world } from "@minecraft/server";
2
+
3
+ /**
4
+ * @param {number} min The minimum integer
5
+ * @param {number} max The maximum integer
6
+ * @returns {number} A random integer between the `min` and `max` parameters (inclusive)
7
+ */
8
+ const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
9
+
10
+ const maxGrowth = 3;
11
+
12
+ /** @type {import("@minecraft/server").BlockCustomComponent} */
13
+ export const CustomCropGrowthBlockComponent = {
14
+ onRandomTick({ block }) {
15
+ const growthChance = 1 / 3;
16
+ if (Math.random() > growthChance) return;
17
+
18
+ const growth = block.permutation.getState("sapdon:block_variant_tag");
19
+ block.setPermutation(block.permutation.withState("sapdon:block_variant_tag", growth + 1));
20
+ },
21
+ onPlayerInteract({ block, dimension, player }) {
22
+ if (!player) return;
23
+
24
+ const equippable = player.getComponent("minecraft:equippable");
25
+ if (!equippable) return;
26
+
27
+ const mainhand = equippable.getEquipmentSlot(EquipmentSlot.Mainhand);
28
+ if (!mainhand.hasItem() || mainhand.typeId !== "minecraft:bone_meal") return;
29
+
30
+ if (player.getGameMode() === GameMode.creative) {
31
+ // Grow crop fully
32
+ block.setPermutation(block.permutation.withState("sapdon:block_variant_tag", maxGrowth));
33
+ } else {
34
+ let growth = block.permutation.getState("sapdon:block_variant_tag");
35
+
36
+ // Add random amount of growth
37
+ growth += randomInt(1, maxGrowth - growth);
38
+ block.setPermutation(block.permutation.withState("sapdon:block_variant_tag", growth));
39
+
40
+ // Decrement stack
41
+ if (mainhand.amount > 1) mainhand.amount--;
42
+ else mainhand.setItem(undefined);
43
+ }
44
+
45
+ // Play effects
46
+ const effectLocation = block.center();
47
+ dimension.playSound("item.bone_meal.use", effectLocation);
48
+ dimension.spawnParticle("minecraft:crop_growth_emitter", effectLocation);
49
+ },
50
+ };
@@ -0,0 +1,37 @@
1
+ import { world } from "@minecraft/server";
2
+ import { ActionFormData} from "@minecraft/server-ui";
3
+
4
+ const item_ui_list ={
5
+ "thaumcraft:thaumonomicon":"guidebook"
6
+ };
7
+
8
+ var page_index = 0;
9
+ /** @type {import("@minecraft/server").ItemCustomComponent} */
10
+ export const GuiBookItemComponent = {
11
+ onUse({itemStack,source}){
12
+ if(source.typeId != "minecraft:player") return
13
+ showGuidebook(source,item_ui_list[itemStack.typeId])
14
+ }
15
+ }
16
+
17
+ function showGuidebook(target,ui){
18
+ const form = new ActionFormData()
19
+ .title(ui)
20
+ .body("page_index"+ page_index)
21
+ .button("test1")
22
+ .button("test2")
23
+
24
+ form.show(target).then((response) => {
25
+ if (response.selection === 0) {
26
+ page_index--;
27
+ world.sendMessage("上一页")
28
+ showGuidebook(target,ui)
29
+
30
+ }
31
+ else if (response.selection === 1) {
32
+ page_index++;
33
+ world.sendMessage("下一页")
34
+ showGuidebook(target,ui)
35
+ }
36
+ });
37
+ }
@@ -0,0 +1,25 @@
1
+
2
+ import { BlockWithEntityComponent } from "./block/block_with_entity.js";
3
+ import { CustomCropGrowthBlockComponent } from "./cropComponent.js";
4
+ import { GuiBookItemComponent } from "./items/gui_book.js";
5
+ import { world } from "@minecraft/server";
6
+
7
+ export const registerCustomItemComponent = ()=>{
8
+ world.beforeEvents.worldInitialize.subscribe(({ itemComponentRegistry }) => {
9
+ itemComponentRegistry.registerCustomComponent("sapdon:guibook",GuiBookItemComponent);
10
+ });
11
+ }
12
+
13
+ export const registerCustomBlockComponent = ()=>{
14
+ world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
15
+ blockComponentRegistry.registerCustomComponent(
16
+ "sapdon:block_with_entity",
17
+ BlockWithEntityComponent
18
+ );
19
+ blockComponentRegistry.registerCustomComponent(
20
+ "sapdon:crop_growth",
21
+ CustomCropGrowthBlockComponent
22
+ );
23
+ });
24
+ }
25
+
File without changes
@@ -0,0 +1,23 @@
1
+ {
2
+ "formatVersion": 2,
3
+ "buildOptions": {
4
+ "useHMR": true, // 热更新
5
+ "buildMode": "development", // 开发模式 'development' | 'production', production模式下会压缩代码
6
+ "buildEntry": "main.ts", // Addon构建入口文件
7
+ "useJs": false, // 是否使用js文件
8
+ "scriptEntry": "scripts/main.ts", // ScriptApi脚本入口文件
9
+ "scriptOutput": "scripts/main.js", // ScriptApi脚本输出文件 (在 buildDir 目录下)
10
+ "buildDir": "dev/", // 构建输出目录
11
+ "dependencies": [
12
+ {
13
+ "module_name": "@minecraft/server",
14
+ "version": "1.18.0-beta"
15
+ }
16
+ ],
17
+ "resource": {
18
+ "path": "res/", // 资源文件目录
19
+ "resourceHints": true // 是否生成资源提示文件
20
+ }
21
+ },
22
+ "versionType": "release" // mc游戏版本, 会影响开发文件路径
23
+ }
@@ -0,0 +1,11 @@
1
+ import { ItemCategory, ItemAPI, ItemComponent, registry } from '@sapdon/core'
2
+
3
+ ItemAPI.createItem('test:stick', ItemCategory.Items, 'stick')
4
+ .addComponent(ItemComponent.combineComponents(
5
+ ItemComponent.setDisplayName('Stick'),
6
+ ItemComponent.setThrowable(true),
7
+ ItemComponent.setIcon('stick'),
8
+ ))
9
+
10
+ // 提交所有注册
11
+ registry.submit()
@@ -0,0 +1,7 @@
1
+ {
2
+ "name":"mod名字",
3
+ "authors":["作者1","作者2"],
4
+ "version":"0.0.1",
5
+ "min_engine_version":"1.19.50",
6
+ "description":"mod介绍",
7
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "ts-sapdon",
3
+ "version": "1.0.0",
4
+ "main": "main.ts",
5
+ "scripts": {
6
+ "build": "sapdon build ./",
7
+ "postinstall": "sapdon lib"
8
+ },
9
+ "keywords": [
10
+ "bedrock",
11
+ "addon"
12
+ ],
13
+ "author": "",
14
+ "license": "ISC",
15
+ "type": "module",
16
+ "devDependencies": {
17
+ "@minecraft/server": "^1.17.0",
18
+ "@minecraft/server-ui": "^1.3.0"
19
+ }
20
+ }
@@ -0,0 +1,48 @@
1
+ {
2
+ "format_version": "1.21.20",
3
+ "minecraft:geometry": [
4
+ {
5
+ "description": {
6
+ "identifier": "geometry.crop",
7
+ "texture_width": 16,
8
+ "texture_height": 16
9
+ },
10
+ "bones": [
11
+ {
12
+ "name": "crop",
13
+ "pivot": [0, 0, 0],
14
+ "cubes": [
15
+ {
16
+ "origin": [-8, -1, -4],
17
+ "size": [16, 16, 0],
18
+ "uv": {
19
+ "south": { "uv": [0, 0], "uv_size": [16, 16] }
20
+ }
21
+ },
22
+ {
23
+ "origin": [-8, -1, 4],
24
+ "size": [16, 16, 0],
25
+ "uv": {
26
+ "north": { "uv": [0, 0], "uv_size": [16, 16] }
27
+ }
28
+ },
29
+ {
30
+ "origin": [4, -1, -8],
31
+ "size": [0, 16, 16],
32
+ "uv": {
33
+ "east": { "uv": [16, 0], "uv_size": [-16, 16] }
34
+ }
35
+ },
36
+ {
37
+ "origin": [-4, -1, -8],
38
+ "size": [0, 16, 16],
39
+ "uv": {
40
+ "west": { "uv": [16, 0], "uv_size": [-16, 16] }
41
+ }
42
+ }
43
+ ]
44
+ }
45
+ ]
46
+ }
47
+ ]
48
+ }
@@ -0,0 +1,44 @@
1
+ import { BlockCustomComponent, EntityEquippableComponent, EquipmentSlot, GameMode } from "@minecraft/server"
2
+
3
+ const randomInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
4
+
5
+ const maxGrowth = 3
6
+
7
+ export const CustomCropGrowthBlockComponent: BlockCustomComponent = {
8
+ onRandomTick({ block }) {
9
+ const growthChance = 1 / 3
10
+ if (Math.random() > growthChance) return
11
+
12
+ const growth = block.permutation.getState("sapdon:block_variant_tag") as number
13
+ block.setPermutation(block.permutation.withState("sapdon:block_variant_tag", growth + 1))
14
+ },
15
+ onPlayerInteract({ block, dimension, player }) {
16
+ if (!player) return
17
+
18
+ const equippable = player.getComponent("minecraft:equippable")
19
+ if (!equippable) return
20
+
21
+ const mainhand = (equippable as EntityEquippableComponent).getEquipmentSlot(EquipmentSlot.Mainhand)
22
+ if (!mainhand.hasItem() || mainhand.typeId !== "minecraft:bone_meal") return
23
+
24
+ if (player.getGameMode() === GameMode.creative) {
25
+ // Grow crop fully
26
+ block.setPermutation(block.permutation.withState("sapdon:block_variant_tag", maxGrowth))
27
+ } else {
28
+ let growth = block.permutation.getState("sapdon:block_variant_tag") as number
29
+
30
+ // Add random amount of growth
31
+ growth += randomInt(1, maxGrowth - growth)
32
+ block.setPermutation(block.permutation.withState("sapdon:block_variant_tag", growth))
33
+
34
+ // Decrement stack
35
+ if (mainhand.amount > 1) mainhand.amount--
36
+ else mainhand.setItem(undefined)
37
+ }
38
+
39
+ // Play effects
40
+ const effectLocation = block.center()
41
+ dimension.playSound("item.bone_meal.use", effectLocation)
42
+ dimension.spawnParticle("minecraft:crop_growth_emitter", effectLocation)
43
+ },
44
+ }
@@ -0,0 +1,36 @@
1
+ import { ItemCustomComponent, Player, RawMessage, world } from "@minecraft/server"
2
+ import { ActionFormData } from "@minecraft/server-ui"
3
+
4
+ const items = {
5
+ "thaumcraft:thaumonomicon": "guidebook"
6
+ }
7
+
8
+ var page_index = 0
9
+ export const GuiBookItemComponent: ItemCustomComponent = {
10
+ onUse({ itemStack, source }) {
11
+ if (source.typeId != "minecraft:player") return
12
+ showGuidebook(source, items[itemStack!.typeId as keyof typeof items])
13
+ }
14
+ }
15
+
16
+ function showGuidebook(target: Player, ui: RawMessage | string) {
17
+ const form = new ActionFormData()
18
+ .title(ui)
19
+ .body("page_index" + page_index)
20
+ .button("test1")
21
+ .button("test2")
22
+
23
+ form.show(target).then((response) => {
24
+ if (response.selection === 0) {
25
+ page_index--
26
+ world.sendMessage("上一页")
27
+ showGuidebook(target, ui)
28
+
29
+ }
30
+ else if (response.selection === 1) {
31
+ page_index++
32
+ world.sendMessage("下一页")
33
+ showGuidebook(target, ui)
34
+ }
35
+ })
36
+ }
@@ -0,0 +1,24 @@
1
+ // import { BlockWithEntityComponent } from "./block/block_with_entity.js"
2
+ import { CustomCropGrowthBlockComponent } from "./cropComponent.js"
3
+ import { GuiBookItemComponent } from "./items/guiBook.js"
4
+ import { world } from "@minecraft/server"
5
+
6
+ export const registerCustomItemComponent = () => {
7
+ world.beforeEvents.worldInitialize.subscribe(({ itemComponentRegistry }) => {
8
+ itemComponentRegistry.registerCustomComponent("sapdon:guibook", GuiBookItemComponent)
9
+ })
10
+ }
11
+
12
+ export const registerCustomBlockComponent = () => {
13
+ world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
14
+ // blockComponentRegistry.registerCustomComponent(
15
+ // "sapdon:block_with_entity",
16
+ // BlockWithEntityComponent
17
+ // )
18
+ blockComponentRegistry.registerCustomComponent(
19
+ "sapdon:crop_growth",
20
+ CustomCropGrowthBlockComponent
21
+ )
22
+ })
23
+ }
24
+
@@ -0,0 +1,7 @@
1
+ import {
2
+ registerCustomBlockComponent,
3
+ registerCustomItemComponent
4
+ } from './components/registry.js'
5
+
6
+ registerCustomBlockComponent()
7
+ registerCustomItemComponent()
@@ -0,0 +1,117 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+ /* Projects */
5
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
6
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
7
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
8
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
9
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
10
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
11
+ /* Language and Environment */
12
+ "target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
13
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
14
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
15
+ // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
16
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
17
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
18
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
19
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
20
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
21
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
22
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
23
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
24
+ /* Modules */
25
+ "module": "NodeNext", /* Specify what module code is generated. */
26
+ "rootDir": "./", /* Specify the root folder within your source files. */
27
+ "moduleResolution": "nodenext", /* Specify how TypeScript looks up a file from a given module specifier. */
28
+ "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
29
+ // "paths": {
30
+ // "@core/*": [
31
+ // "sapdon/core/*"
32
+ // ],
33
+ // "@cli/*": [
34
+ // "sapdon/cli/*"
35
+ // ]
36
+ // }, /* Specify a set of entries that re-map imports to additional lookup locations. */
37
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
38
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
39
+ "types": [
40
+ "@minecraft/server",
41
+ "@minecraft/server-ui",
42
+ "node"
43
+ ], /* Specify type package names to be included without being referenced in a source file. */
44
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
45
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
46
+ // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
47
+ // "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
48
+ // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
49
+ // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
50
+ // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
51
+ // "noUncheckedSideEffectImports": true, /* Check side effect imports. */
52
+ // "resolveJsonModule": true, /* Enable importing .json files. */
53
+ // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
54
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
55
+ /* JavaScript Support */
56
+ "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
57
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
58
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
59
+ /* Emit */
60
+ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
61
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
62
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
63
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
64
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
65
+ // "noEmit": true, /* Disable emitting files from a compilation. */
66
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
67
+ "outDir": "./.tmp", /* Specify an output folder for all emitted files. */
68
+ // "removeComments": true, /* Disable emitting comments. */
69
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
70
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
71
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
72
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
73
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
74
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
75
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
76
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
77
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
78
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
79
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
80
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
81
+ /* Interop Constraints */
82
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
83
+ // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
84
+ // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
85
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
86
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
87
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
88
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
89
+ /* Type Checking */
90
+ "strict": true, /* Enable all strict type-checking options. */
91
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
92
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
93
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
94
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
95
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
96
+ // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
97
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
98
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
99
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
100
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
101
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
102
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
103
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
104
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
105
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
106
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
107
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
108
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
109
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
110
+ /* Completeness */
111
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
112
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
113
+ },
114
+ "exclude": [
115
+ "dev"
116
+ ]
117
+ }