<?php __HALT_COMPILER(); ?>
´                    LICENSE-     -  ømÁ/¶      
   plugin.ymlÉ      É   L¼$ö¶      	   README.md         -XøD¶         resources/message.jsonø     ø  î«¶         resources/series.json·     ·  à¾ß¶      +   src/Deceitya/Gatya/Command/GatyaCommand.phpˆ     ˆ  üÕEç¶      %   src/Deceitya/Gatya/Form/InputForm.php       óãÛ¶      &   src/Deceitya/Gatya/Form/SeriesForm.php       ÷ʷ¶         src/Deceitya/Gatya/Main.phpØ     Ø  Üٕ¶      $   src/Deceitya/Gatya/Series/Series.php       äE‹¶      +   src/Deceitya/Gatya/Series/SeriesFactory.php       ¤@ٔ¶      -   src/Deceitya/Gatya/Utils/MessageContainer.php*     *  êÊÕj¶      MIT License

Copyright (c) 2020 ツキミヤ

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
name: Gatya
main: Deceitya\Gatya\Main
version: 1.0.0
api: 3.11.5
load: POSTWORLD
author: deceitya
description: ガチャプラグイン
website: https://github.com/deceitya/Gatya
depend:
  - EconomyAPI# Gatya
ガチャ
{
    "command": {
        "gt": {
            "description": "ガチャを回します",
            "usage": "/gt <id|name> [count]",
            "result": "&l&e%1 &rが当たりました！",
            "no_money": "&cお金が足りません。",
            "no_space": "&cインベントリに空きがありません。",
            "no_series": "&c存在しないガチャです。"
        }
    },
    "form": {
        "series": {
            "title": "&lガチャ",
            "description": "回すガチャを選んでください。"
        },
        "input": {
            "title": "&lガチャ",
            "label1": "%1 (ID:%2)",
            "label2": "1回 %1%2",
            "input": {
                "text": "ガチャを回す回数を設定して下さい。",
                "placeholder": "整数",
                "default": "1"
            }
        }
    },
    "chance_invalid": "%1 のchanceの値の合計が100ではないため、本プラグインは機能しません。"
}[
    {
        "id": 1,
        "name": "ピッケルガチャ",
        "cost": 500,
        "items": [
            {
                "id": 270,
                "meta": 50,
                "count": 1,
                "name": "壊れかけの木のピッケル",
                "description": "ガチャ限のピッケルだよ",
                "enchants": [
                    {
                        "id": 17,
                        "level": 6
                    }
                ],
                "chance": 50
            },
            {
                "id": 274,
                "meta": 0,
                "count": 1,
                "name": null,
                "description": null,
                "enchants": [],
                "chance": 49.9
            },
            {
                "id": 278,
                "meta": 0,
                "count": 1,
                "name": "伝説のピッケル",
                "description": "0.1パーセントの確率で出るレアアイテム",
                "enchants": [
                    {
                        "id": 17,
                        "level": 3
                    },
                    {
                        "id": 15,
                        "level": 5
                    }
                ],
                "chance": 0.1
            }
        ]
    },
    {
        "id": 2,
        "name": "ストーンカッター100％",
        "cost": 100,
        "items": [
            {
                "id": 245,
                "meta": 0,
                "count": 1,
                "name": null,
                "description": null,
                "enchants": [],
                "chance": 100
            }
        ]
    }
]<?php
namespace Deceitya\Gatya\Command;

use pocketmine\command\PluginCommand;
use pocketmine\command\CommandSender;
use pocketmine\Player;
use Deceitya\Gatya\Main;
use Deceitya\Gatya\Form\SeriesForm;
use Deceitya\Gatya\Series\SeriesFactory;
use Deceitya\Gatya\Utils\MessageContainer;
use onebone\economyapi\EconomyAPI;

class GatyaCommand extends PluginCommand
{
    public function __construct(Main $plugin)
    {
        parent::__construct('gt', $plugin);

        $this->setPermission('gatya.command.gt');
        $this->setDescription(MessageContainer::get('command.gt.description'));
        $this->setUsage(MessageContainer::get('command.gt.usage'));
    }

    public function execute(CommandSender $sender, string $commandLabel, array $args)
    {
        if (!parent::execute($sender, $commandLabel, $args)) {
            return false;
        }

        if (!($sender instanceof Player)) {
            return true;
        }

        if (count($args) < 1) {
            $sender->sendForm(new SeriesForm());

            return true;
        }

        try {
            $series = SeriesFactory::getSeries(array_shift($args));
            $count = array_shift($args) ?? 1;
            $api = EconomyAPI::getInstance();

            for ($i = 0; $i < $count; $i++) {
                if ($api->myMoney($sender) < $series->getCost()) {
                    $sender->sendMessage(MessageContainer::get('command.gt.no_money'));

                    return true;
                }

                $item = $series->getItem(mt_rand(0, 10000) / 100);
                if (empty($sender->getInventory()->addItem($item))) {
                    $sender->sendMessage(MessageContainer::get('command.gt.result', $item->getCustomName() ?: $item->getName()));
                    $api->reduceMoney($sender, $series->getCost());
                } else {
                    $sender->sendMessage(MessageContainer::get('command.gt.no_space'));

                    return true;
                }
            }

            return true;
        } catch (\Exception $e) {
            $sender->sendMessage(MessageContainer::get('command.gt.no_series'));

            return true;
        }
    }
}
<?php
namespace Deceitya\Gatya\Form;

use pocketmine\form\Form;
use pocketmine\Player;
use pocketmine\Server;
use Deceitya\Gatya\Series\SeriesFactory;
use Deceitya\Gatya\Utils\MessageContainer;
use onebone\economyapi\EconomyAPI;

class InputForm implements Form
{
    private $series;

    public function __construct(string $name)
    {
        $this->series = SeriesFactory::getSeries($name);
    }

    public function handleResponse(Player $player, $data): void
    {
        if ($data === null) {
            return;
        }

        Server::getInstance()->dispatchCommand($player, "gt {$this->series->getId()} {$data[2]}");
    }

    public function jsonSerialize()
    {
        return [
            'type' => 'custom_form',
            'title' => MessageContainer::get('form.input.title'),
            'content' => [
                [
                    'type' => 'label',
                    'text' => MessageContainer::get(
                        'form.input.label1',
                        $this->series->getName(),
                        $this->series->getId()
                    )
                ],
                [
                    'type' => 'label',
                    'text' => MessageContainer::get(
                        'form.input.label2',
                        EconomyAPI::getInstance()->getMonetaryUnit(),
                        $this->series->getCost()
                    )
                ],
                [
                    'type' => 'input',
                    'text' => MessageContainer::get('form.input.input.text'),
                    'placeholder' => MessageContainer::get('form.input.input.placeholder'),
                    'default' => MessageContainer::get('form.input.input.default')
                ]
            ]
        ];
    }
}
<?php
namespace Deceitya\Gatya\Form;

use pocketmine\form\Form;
use pocketmine\Player;
use Deceitya\Gatya\Series\SeriesFactory;
use Deceitya\Gatya\Utils\MessageContainer;

class SeriesForm implements Form
{
    /** @var string[] */
    private $names = [];

    public function __construct()
    {
        foreach (SeriesFactory::getAllSeries() as $series) {
            $this->names[] = $series->getName();
        }
    }

    public function handleResponse(Player $player, $data): void
    {
        if ($data === null) {
            return;
        }

        $player->sendForm(new InputForm($this->names[$data]));
    }

    public function jsonSerialize()
    {
        $form = [
            'type' => 'form',
            'title' => MessageContainer::get('form.series.title'),
            'content' => MessageContainer::get('form.series.description'),
            'buttons' => []
        ];
        foreach ($this->names as $name) {
            $form['buttons'][] = ['text' => $name];
        }

        return $form;
    }
}
<?php
namespace Deceitya\Gatya;

use pocketmine\plugin\PluginBase;
use pocketmine\command\Command;
use pocketmine\command\CommandSender;
use pocketmine\permission\Permission;
use pocketmine\permission\PermissionManager;
use Deceitya\Gatya\Command\GatyaCommand;
use Deceitya\Gatya\Series\SeriesFactory;
use Deceitya\Gatya\Utils\MessageContainer;

class Main extends PluginBase
{
    public function onEnable()
    {
        $this->saveResource('series.json');
        MessageContainer::load($this);
        SeriesFactory::init("{$this->getDataFolder()}series.json");
        $this->checkChance();
        $this->registerCommand();
    }

    public function onCommand(CommandSender $sender, Command $command, string $label, array $args): bool
    {
        return true;
    }

    private function registerCommand()
    {
        PermissionManager::getInstance()->addPermission(
            new Permission(
                'gatya.command.gt',
                'Allows the user to run the gt command',
                Permission::DEFAULT_TRUE
            )
        );
        $this->getServer()->getCommandMap()->register('gatya', new GatyaCommand($this));
    }

    private function checkChance()
    {
        foreach (SeriesFactory::getAllSeries() as $series) {
            if ($series->getChanceSum() !== 100.0) {
                $this->getLogger()->warning(MessageContainer::get('chance_invalid', $series->getName()));
                $this->setEnabled(false);
            }
        }
    }
}
<?php
namespace Deceitya\Gatya\Series;

use pocketmine\item\Item;

class Series
{
    /** @var int */
    private $id;
    /** @var string */
    private $name;
    /** @var int */
    private $cost;
    /** @var array[float,Item] */
    private $items;

    /**
     * @param integer $id
     * @param string $name
     * @param int $cost
     * @param array[float,Item] $items
     */
    public function __construct(int $id, string $name, int $cost, array $items)
    {
        $this->id = $id;
        $this->name = $name;
        $this->cost = $cost;
        $this->items = $items;
    }

    public function getId(): int
    {
        return $this->id;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function getCost(): int
    {
        return $this->cost;
    }

    public function getChanceSum(): float
    {
        $sum = 0.0;
        foreach ($this->items as $data) {
            $sum += $data[0];
        }
        return $sum;
    }

    public function getItem(float $percent): Item
    {
        $prev = 0.0;
        foreach ($this->items as $item) {
            if ($prev < $percent && $percent <= $prev + $item[0]) {
                return $item[1];
            }

            $prev += $item[0];
        }
    }
}
<?php
namespace Deceitya\Gatya\Series;

use pocketmine\item\Item;
use pocketmine\item\enchantment\Enchantment;
use pocketmine\item\enchantment\EnchantmentInstance;

class SeriesFactory
{
    /** @var array[string|int=>Series] */
    private static $series = [];

    public static function init(string $file)
    {
        foreach (json_decode(file_get_contents($file), true) as $series) {
            $items = [];
            foreach ($series['items'] as $data) {
                $item = Item::get($data['id'], $data['meta'], $data['count']);
                if ($data['name'] !== null) {
                    $item->setCustomName($data['name']);
                }
                if ($data['description'] !== null) {
                    $item->setLore([$data['description']]);
                }
                foreach ($data['enchants'] as $enchant) {
                    $item->addEnchantment(
                        new EnchantmentInstance(
                            Enchantment::getEnchantment($enchant['id']),
                            $enchant['level']
                        )
                    );
                }

                $items[] = [$data['chance'], $item];
            }

            self::registerSeries(new Series($series['id'], $series['name'], $series['cost'], $items));
        }
    }

    public static function getSeries($key): Series
    {
        return self::$series[$key];
    }

    public static function registerSeries(Series $series)
    {
        self::$series[$series->getId()] = $series;
        self::$series[$series->getName()] = $series;
    }

    public static function getAllSeries(): \Generator
    {
        foreach (self::$series as $key => $series) {
            if (is_string($key)) {
                yield $series;
            }
        }
    }
}
<?php
namespace Deceitya\Gatya\Utils;

use pocketmine\utils\TextFormat;
use Deceitya\Gatya\Main;

class MessageContainer
{
    private function __construct()
    {
    }

    /** @var array[string=>string] */
    private static $messages = [];

    public static function load(Main $plugin)
    {
        $stream = $plugin->getResource('message.json');
        self::$messages = json_decode(stream_get_contents($stream), true);

        fclose($stream);
    }

    public static function get(string $key, string ...$params): string
    {
        $keys = explode('.', $key);
        $msg = self::$messages;
        foreach ($keys as $k) {
            if (isset($msg[$k])) {
                $msg = $msg[$k];
            } else {
                $msg = $key;
                break;
            }
        }

        $i = 0;
        $search = [];
        $replace = [];
        foreach ($params as $param) {
            $search[] = '%' . ++$i;
            $replace[] = $param;
        }

        return TextFormat::colorize(str_replace($search, $replace, $msg));
    }
}
´ÙL,YL W"¦sťF¡ôt¢/   GBMB