Pulcedocs
Pulce docs

Руководства

Короткие рецепты для типичных задач плагинов и сервера.

На этой странице

Первый плагин

Реализуйте методы жизненного цикла и зарегистрируйте одну команду. Выполняйте игровые действия через публичные методы, а регистрации оставьте в Init, чтобы перезагрузка очищала ресурсы.

plugin.go
package minimalplugin

import (
	"context"
	"fmt"

	"github.com/pulce-core/Pulce/core/command"
	"github.com/pulce-core/Pulce/core/content"
	"github.com/pulce-core/Pulce/core/gameplay"
	"github.com/pulce-core/Pulce/core/item"
	"github.com/pulce-core/Pulce/core/player"
	"github.com/pulce-core/Pulce/core/plugin"
)

type Plugin struct {
	ctx        plugin.Context
	unregister func()
}

func New() plugin.Plugin { return &Plugin{} }

func init() {
	plugin.MustRegisterFactory("minimalplugin", New)
}

func (p *Plugin) Name() string { return "minimalplugin" }

func (p *Plugin) Init(ctx plugin.Context) error {
	p.ctx = ctx

	if _, err := ctx.RegisterBlock(content.BlockSpec{Name: "minimalplugin:ruby_block"}); err != nil {
		return err
	}
	if _, err := ctx.RegisterItem(content.ItemSpec{Name: "minimalplugin:ruby", MaxCount: 64}); err != nil {
		return err
	}

	unregister, err := ctx.Commands().Register(command.Definition{
		Name: "ruby",
		Handler: p.giveRuby,
	})
	if err != nil {
		return err
	}
	p.unregister = unregister
	return nil
}

func (p *Plugin) Start(context.Context) error { return nil }

func (p *Plugin) Stop(context.Context) error {
	if p.unregister != nil {
		p.unregister()
	}
	return nil
}

func (p *Plugin) giveRuby(ctx context.Context, exec command.Execution) (command.Result, error) {
	_, err := p.ctx.Gameplay().GiveItem(gameplay.InventoryGiveRequest{
		PlayerID: player.ID(exec.Source.PlayerID),
		Stack: item.Stack{
			Item: item.State{Name: "minimalplugin:ruby"},
			Count: 1,
		},
	})
	if err != nil {
		return command.Result{}, err
	}
	return command.Result{Messages: []string{fmt.Sprintf("Gave ruby to %s.", exec.Source.Username)}}, nil
}

Безопасная выдача предметов

Найдите игрока через игровой API, создайте стопку предметов и вызовите Inventory().Give. Сервер проверит действие и отправит изменения клиенту.

give-items.go
playerHandle, ok := ctx.Gameplay().Players().ByName("Steve")
if !ok {
	return fmt.Errorf("player not found")
}

target, ok := ctx.Gameplay().Players().Resolve("Steve") // ID, name, XUID, or UUID
_ = target
_ = ok

_, err := playerHandle.Inventory().Give(item.New("diamond_sword").
	Enchant(item.Sharpness(5)).
	NameTag("Arena Blade").
	Stack())

worldHandle, ok := ctx.Gameplay().Worlds().ByName("Hub")
if !ok {
	return fmt.Errorf("world not found")
}

container := worldHandle.ContainerAt(world.Pos{X: 10, Y: 64, Z: 10}, 27)
_, err = container.Give(item.New("diamond").Count(8).Stack())

Регистрация своего контента

Используйте методы построения описаний для настройки обработчиков блока или предмета, выпадения предметов, параметров контейнера и компонентов Bedrock.

content.go
ctx.RegisterBlock(content.DefineBlock("example:crate").
	Container(27).
	Hardness(4).
	Tool("axe").
	Drop(item.New("example:ruby").Stack()).
	OnInteract(func(event content.BlockContext) error {
		return nil
	}).
	Spec())

ctx.RegisterItem(content.DefineItem("example:wand").
	MaxCount(1).
	Component("minecraft:foil", true).
	OnUseOnBlock(func(event content.ItemContext) error {
		worldHandle, err := event.World()
		if err != nil {
			return err
		}
		return worldHandle.SetBlock(event.Pos, block.New("gold_block").Block())
	}).
	Spec())

ctx.RegisterEffect(content.DefineEffect("example:focus").
	BedrockID(200).
	Spec())