code:
//=============================================================================
// SlotMachine.js
//
// (c)2016 KADOKAWA CORPORATION./YOJI OJIMA
//=============================================================================

/*:
 * @plugindesc Slot Machine scene
 * @author Takeya Kimura
 *
 * @param Variable ID
 * @desc Variable ID for store the coin.
 * @default 11
 *
 * @param Help Text
 * @desc This text is a help message.
 * @default カーソルキーの上でベット、カーソルキーの下でスタート
 *
 * @param Won Text
 * @desc This text is a won message. "Win Coin" will be replaced with the number of coins won.
 * @default おめでとうございます！Win Coin枚獲得です！
 *
 * @param Lost Text
 * @desc This text is a lost message.
 * @default 残念でした。
 *
 * @param Replay Text
 * @desc This text is a replay message.
 * @default もう一度やりますか？
 *
 * @param CoinFull Text
 * @desc This text is a coin full message.
 * @default コイン枚数が制限に達しました。
 *
 * @param Bet Text
 * @desc This text is a bet command.
 * @default ベット
 *
 * @param Spin Text
 * @desc This text is a coin spin command.
 * @default スピン
 *
 * @param Yes Text
 * @desc This text is a coin "yes" command.
 * @default はい
 *
 * @param No Text
 * @desc This text is a "no" command.
 * @default いいえ
 *
 * @requiredAssets img/slotmachine/bet_line_1
 * @requiredAssets img/slotmachine/bet_line_2
 * @requiredAssets img/slotmachine/bet_line_3
 * @requiredAssets img/slotmachine/bg
 * @requiredAssets img/slotmachine/line_base
 * @requiredAssets img/slotmachine/reel
 * @requiredAssets img/slotmachine/scale_x1
 * @requiredAssets img/slotmachine/scale_x10
 * @requiredAssets img/slotmachine/scale_x100
 * @requiredAssets img/slotmachine/win_cursor
 * @requiredAssets audio/me/Victory1
 * @requiredAssets audio/se/Switch2
 *
 * @help
 * Plugin Command:
 *   SlotMachine open               # Open the slot machines
 *   SlotMachine expectation 0.5    # Set the expectation
 *   SlotMachine scale 0            # Set the scale [0 | 1 | 2](scale1 | scale10 | scale100)
 */

/*:ja
 * @plugindesc Slot Machine scene
 * @author Takeya Kimura
 *
 * @param Variable ID
 * @desc 所持コインの数を保管する変数ID
 * @default 11
 *
 * @param Help Text
 * @desc ヘルプメッセージです。
 * @default カーソルキーの上でベット、カーソルキーの下でスタート
 *
 * @param Won Text
 * @desc 勝利時のメッセージ。 "Win Coin"は獲得したコイン数に置換されます。
 * @default おめでとうございます！Win Coin枚獲得です！
 *
 * @param Lost Text
 * @desc 負けた時のメッセージ
 * @default 残念でした。
 *
 * @param Replay Text
 * @desc リプレイ時の選択メッセージ
 * @default もう一度やりますか？
 *
 * @param Coin Full Text
 * @desc コインが最大数に達した時のメッセージ
 * @default コイン枚数が制限に達しました。
 *
 * @param Bet Text
 * @desc ベットコマンドのテキスト
 * @default ベット
 *
 * @param Spin Text
 * @desc スピンコマンドのテキスト
 * @default スピン
 *
 * @param Yes Text
 * @desc はいコマンドのテキスト
 * @default はい
 *
 * @param No Text
 * @desc いいえコマンドのテキスト
 * @default いいえ
 *
 * @requiredAssets img/slotmachine/bet_line_1
 * @requiredAssets img/slotmachine/bet_line_2
 * @requiredAssets img/slotmachine/bet_line_3
 * @requiredAssets img/slotmachine/bg
 * @requiredAssets img/slotmachine/line_base
 * @requiredAssets img/slotmachine/reel
 * @requiredAssets img/slotmachine/scale_x1
 * @requiredAssets img/slotmachine/scale_x10
 * @requiredAssets img/slotmachine/scale_x100
 * @requiredAssets img/slotmachine/win_cursor
 * @requiredAssets audio/me/Victory1
 * @requiredAssets audio/se/Switch2
 *
 * @help
 * Plugin Command:
 *   SlotMachine open               # スロットマシーンを開きます
 *   SlotMachine expectation 0.5    # 期待値を0〜1の間で設定します。1に近づくほど当たりやすくなりますが、確実に当たるわけではありません。
 *   SlotMachine scale 0            # 倍率を設定します0は1倍、1は10倍、2は100倍です。
 */

(function () {

    var parameters = PluginManager.parameters('SlotMachine');
    var variableId = Number(parameters['Variable ID'] || 11);
    var helpMessage = String(parameters['Help Text'] || "カーソルキーの上でベット、カーソルキーの下でスタート");
    var winMessage = String(parameters['Won Text'] || "おめでとうございます！Win Coin枚獲得です！");
    var lostMessage = String(parameters['Lost Text'] || "残念でした。");
    var replayMessage = String(parameters['Replay Text'] || "もう一度やりますか？");
    var coinFullMessage = String(parameters['CoinFull Text'] || "コイン枚数が制限に達しました。");
    var betText = String(parameters['Bet Text'] || "ベット");
    var spinText = String(parameters['Spin Text'] || "スピン");
    var yesText = String(parameters['Yes Text'] || "はい");
    var noText = String(parameters['No Text'] || "いいえ");
    var scale = 1;
    var expectation = 0.5;

    //odds
    //You can set the odds.
    var odds = [];
    odds.push([]);
    odds[0].push(1); //000
    odds[0].push(2); //111
    odds[0].push(5); //222
    odds[0].push(10); //333
    odds[0].push(20); //444
    odds[0].push(100); //555
    odds.push([]);
    odds[1].push(2); //0000
    odds[1].push(10); //1111
    odds[1].push(20); //2222
    odds[1].push(100); //3333
    odds[1].push(200); //4444
    odds[1].push(1000); //5555
    odds.push([]);
    odds[2].push(20); //00000
    odds[2].push(100); //11111
    odds[2].push(200); //22222
    odds[2].push(1000); //33333
    odds[2].push(2000); //44444
    odds[2].push(10000); //55555

    //make reel
    //You can rearrange the order of the reel.
    //The number can not be changed.
    var reel = [];
    reel.push([0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]);
    reel.push([5, 4, 3, 2, 1, 0, 5, 4, 3, 2, 1, 0, 5, 4, 3, 2, 1, 0]);
    reel.push([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 0, 1, 2, 3, 4, 5]);
    reel.push([0, 2, 4, 1, 3, 5, 0, 2, 4, 1, 3, 5, 0, 2, 4, 1, 3, 5]);
    reel.push([0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]);

    function getCoin() {
        return $gameVariables.value(variableId);
    }

    function setCoin(value) {
        return $gameVariables.setValue(variableId, value);
    }

    var _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
    Game_Interpreter.prototype.pluginCommand = function (command, args) {
        _Game_Interpreter_pluginCommand.call(this, command, args);
        if (command === "SlotMachine") {
            switch (args[0]) {
                case "open":
                    SceneManager.push(Scene_SlotMachine);
                    break;
                case "expectation":
                    expectation = Number(args[1]);
                    break;
                case "scale":
                    switch (args[1]) {
                        case "0":
                            scale = 1;
                            break;
                        case "1":
                            scale = 10;
                            break;
                        case "2":
                            scale = 100;
                            break;
                        default:
                            scale = 1;
                            break;
                    }
                    break;
            }
        }
    };

    //-----------------------------------------------------------------------------
    // SLTReelSprite
    //
    // Slot Machine Reel Sprite

    function SLTReelSprite() {
        this.initialize.apply(this, arguments);
    }

    SLTReelSprite.prototype = Object.create(Sprite.prototype);
    SLTReelSprite.prototype.constructor = SLTReelSprite;

    SLTReelSprite.STOP = 0;
    SLTReelSprite.SPINNING = 1;
    SLTReelSprite.SPIN = 2;
    SLTReelSprite.STOPPING = 3;
    SLTReelSprite.FRAME_SPINNING = 40;
    SLTReelSprite.FRAME_SPIN = 60;
    SLTReelSprite.FRAME_STOPPING = 40;

    SLTReelSprite.prototype.initialize = function (bitmap) {
        Sprite.prototype.initialize.call(this, bitmap);
        this._numSpot = 18;
        this._spotHeight = 54;
        this._winSpot = 0;
        this._scrollY = 0;
        this._speedHigh = 30;
        this._speedLow = 4;
        this._status = 0;
        this._spinFrame = 0;
        this._spinEndFrame = SLTReelSprite.FRAME_SPIN;
    };

    Object.defineProperty(SLTReelSprite.prototype, 'status', {
        get: function () {
            return this._status;
        },
        configurable: true
    });

    SLTReelSprite.prototype.update = function () {
        Sprite.prototype.update.call(this);

        switch (this._status) {

            case SLTReelSprite.STOP:
                break;

            case SLTReelSprite.SPINNING:
                if (this._spinFrame > SLTReelSprite.FRAME_SPINNING) {
                    this._status = SLTReelSprite.SPIN;
                    break;
                }
                this._scrollY = (this._scrollY + this._speedLow) % (this._numSpot * this._spotHeight);
                this.setFrame(
                    0,
                    this._spotHeight * this._numSpot * 2 - this._scrollY - this._spotHeight * 2,
                    116,
                    this._spotHeight * 3
                );
                this._spinFrame++;
                break;

            case SLTReelSprite.SPIN:
                if (this._spinFrame > this._spinEndFrame + SLTReelSprite.FRAME_SPINNING) {
                    this._status = SLTReelSprite.STOPPING;
                    this._scrollY = this._winSpot * this._spotHeight - this._spotHeight * 3;
                    break;
                }
                this._scrollY = (this._scrollY + this._speedHigh) % (this._numSpot * this._spotHeight);
                this.setFrame(
                    0,
                    this._spotHeight * this._numSpot * 2 - this._scrollY - this._spotHeight * 2,
                    116,
                    this._spotHeight * 3
                );
                this._spinFrame++;
                break;

            case SLTReelSprite.STOPPING:
                this._scrollY = (this._scrollY + this._speedLow) % (this._numSpot * this._spotHeight);
                if (this._scrollY > this._winSpot * this._spotHeight) {
                    this._scrollY = this._winSpot * this._spotHeight;
                    this._status = SLTReelSprite.STOP;
                    AudioManager.playSe({ "name": "Switch2", "volume": 90, "pitch": 100, "pan": 0 });
                }
                this.setFrame(
                    0,
                    this._spotHeight * this._numSpot * 2 - this._scrollY - this._spotHeight * 2,
                    116,
                    this._spotHeight * 3
                );
                break;
        }
    };

    SLTReelSprite.prototype.setSpot = function (spot) {
        if (0 <= spot && spot < this._numSpot) {
            this._scrollY = this._spotHeight * spot;
            this.setFrame(
                0,
                this._spotHeight * this._numSpot * 2 - this._scrollY - this._spotHeight * 2,
                116,
                this._spotHeight * 3
            );
        }
    };

    SLTReelSprite.prototype.setWinSpot = function (spot) {
        this._winSpot = spot;
    };

    SLTReelSprite.prototype.setSpinEndFrame = function (frame) {
        this._spinEndFrame = frame;
    };

    SLTReelSprite.prototype.spin = function () {
        if (this._status === SLTReelSprite.STOP) {
            this._status = SLTReelSprite.SPINNING;
            this._spinFrame = 0;
        }
    };

    //-----------------------------------------------------------------------------
    // LotLineSprite
    //
    // This Sprite is draw lot line for the slot machines.

    function LotLineSprite() {
        this.initialize.apply(this, arguments);
    }

    LotLineSprite.prototype = Object.create(Sprite.prototype);
    LotLineSprite.prototype.constructor = LotLineSprite;

    LotLineSprite.prototype.initialize = function (bitmap) {
        Sprite.prototype.initialize.call(this, bitmap);

        var b1 = ImageManager.loadBitmap("img/slotmachine/", "bet_line_1");
        var b2 = ImageManager.loadBitmap("img/slotmachine/", "bet_line_2");
        var b3 = ImageManager.loadBitmap("img/slotmachine/", "bet_line_3");
        this._line1Sprite = new Sprite(b1);
        this._line2Sprite = new Sprite(b2);
        this._line3Sprite = new Sprite(b3);
        this._line1Sprite.x = 0;
        this._line1Sprite.y = 54;
        this._line2Sprite.x = 0;
        this._line2Sprite.y = 0;
        this._line3Sprite.x = 0;
        this._line3Sprite.y = 111;
        this.addChild(this._line1Sprite);
        this.addChild(this._line2Sprite);
        this.addChild(this._line3Sprite);
    };

    LotLineSprite.prototype.enableLine = function (line) {
        if (line === 0) {
            this._line1Sprite.visible = true;
        }
        else if (line === 1) {
            this._line2Sprite.visible = true;
        }
        else if (line === 2) {
            this._line3Sprite.visible = true;
        }
    };

    LotLineSprite.prototype.clear = function () {
        this._line1Sprite.visible = false;
        this._line2Sprite.visible = false;
        this._line3Sprite.visible = false;
    };

    //-----------------------------------------------------------------------------
    // InstructionCursorSprite
    //
    // Cursor indicating the winning

    function InstructionCursorSprite() {
        this.initialize.apply(this, arguments);
    }

    InstructionCursorSprite.prototype = Object.create(Sprite.prototype);
    InstructionCursorSprite.prototype.constructor = InstructionCursorSprite;

    InstructionCursorSprite.prototype.initialize = function (bitmap) {
        Sprite.prototype.initialize.call(this, bitmap);

        this._counter = 0;
    };

    InstructionCursorSprite.FRAME_BLINK = 10;
    InstructionCursorSprite.FRAME_BLINK_END = 190;

    InstructionCursorSprite.prototype.blink = function () {
        this._counter = 1;
    };

    InstructionCursorSprite.prototype.update = function () {
        Sprite.prototype.update.call(this);

        if (this._counter > 0) {
            if (this._counter > InstructionCursorSprite.FRAME_BLINK_END + 1) {
                this._counter = 0;
            }
            else {
                var s = this._counter / InstructionCursorSprite.FRAME_BLINK >> 0;
                this.visible = s % 2 === 0;
                this._counter++;
            }
        }
    };

    /**
     * @method drawImage
     * @param bitmap    source bitmap
     * @param sx        source x
     * @param sy        source y
     * @param sw        source width
     * @param sh        source height
     * @param dx        destination x
     * @param dy        destination y
     */
    Bitmap.prototype.drawImage = function (bitmap, sx, sy, sw, sh, dx, dy) {
        this._context.drawImage(bitmap.canvas, sx, sy, sw, sh, dx, dy, sw, sh);
        this._setDirty();
    };

    //-----------------------------------------------------------------------------
    // Scene_SlotMachine
    //
    // Will play the slot machine.

    function Scene_SlotMachine() {
        this.initialize.apply(this, arguments);
    }

    Scene_SlotMachine.prototype = Object.create(Scene_MenuBase.prototype);
    Scene_SlotMachine.prototype.constructor = Scene_SlotMachine;

    Scene_SlotMachine.COIN_MAX_VALUE = 99999999;
    Scene_SlotMachine.ODDS_MAX_VALUE = 100000;

    Scene_SlotMachine.prototype.initialize = function () {
        Scene_MenuBase.prototype.initialize.call(this);

        this._bet = 0;
        this._coin = getCoin();
        this._winSpot = null;
        this._spinStart = false;
        this._rollCount = 0;
        this._winCoin = 0;
        this._correctCoin = 0;
        this._winStep = 0;
        this._winMessage = "";

        //Winning percentage is calculated by the odds
        this._probability = [];
        this._probability.push([]);
        this._probability[0].push(0.70); //00
        this._probability[0].push(0.63); //11
        this._probability[0].push(0.54); //22
        this._probability[0].push(0.44); //33
        this._probability[0].push(0.38); //44
        this._probability[0].push(0.31); //55

        this._probability.push([]);
        this._probability[1].push((1 / this._probability[0][0]) *
            expectation * (1 / odds[0][0])); //000
        this._probability[1].push((1 / this._probability[0][1]) *
            expectation * (1 / odds[0][1])); //111
        this._probability[1].push((1 / this._probability[0][2]) *
            expectation * (1 / odds[0][2])); //222
        this._probability[1].push((1 / this._probability[0][3]) *
            expectation * (1 / odds[0][3])); //333
        this._probability[1].push((1 / this._probability[0][4]) *
            expectation * (1 / odds[0][4])); //444
        this._probability[1].push((1 / this._probability[0][5]) *
            expectation * (1 / odds[0][5])); //555

        this._probability.push([]);
        this._probability[2].push((1 / (this._probability[0][0] * this._probability[1][0])) *
            expectation * (1 / odds[1][0])); //0000
        this._probability[2].push((1 / (this._probability[0][1] * this._probability[1][1])) *
            expectation * (1 / odds[1][1])); //1111
        this._probability[2].push((1 / (this._probability[0][2] * this._probability[1][2])) *
            expectation * (1 / odds[1][2])); //2222
        this._probability[2].push((1 / (this._probability[0][3] * this._probability[1][3])) *
            expectation * (1 / odds[1][3])); //3333
        this._probability[2].push((1 / (this._probability[0][4] * this._probability[1][4])) *
            expectation * (1 / odds[1][4])); //4444
        this._probability[2].push((1 / (this._probability[0][5] * this._probability[1][5])) *
            expectation * (1 / odds[1][5])); //5555

        this._probability.push([]);
        this._probability[3].push((1 / (this._probability[0][0] * this._probability[1][0] * this._probability[2][0])) *
            expectation * (1 / odds[2][0])); //00000
        this._probability[3].push((1 / (this._probability[0][1] * this._probability[1][1] * this._probability[2][1])) *
            expectation * (1 / odds[2][1])); //11111
        this._probability[3].push((1 / (this._probability[0][2] * this._probability[1][2] * this._probability[2][2])) *
            expectation * (1 / odds[2][2])); //22222
        this._probability[3].push((1 / (this._probability[0][3] * this._probability[1][3] * this._probability[2][3])) *
            expectation * (1 / odds[2][3])); //33333
        this._probability[3].push((1 / (this._probability[0][4] * this._probability[1][4] * this._probability[2][4])) *
            expectation * (1 / odds[2][4])); //44444
        this._probability[3].push((1 / (this._probability[0][5] * this._probability[1][5] * this._probability[2][5])) *
            expectation * (1 / odds[2][5])); //55555

        //Interval Spin
        //this._startingTimer = null;
        //this._currentStartingReel = 0;

        if (this._coin > Scene_SlotMachine.COIN_MAX_VALUE) {
            this._coin = Scene_SlotMachine.COIN_MAX_VALUE;
        }
    };

    Scene_SlotMachine.prototype.create = function () {
        this.createBackground();
        this._backgroundSprite.bitmap = ImageManager.loadBitmap("img/slotmachine/", "bg");
        this.createReels();
        this.createBetLine();
        this.createScale();
        this.updateActor();
        this.createWindowLayer();
        this.createHelpWindow();
        this.createInstruction();
        this.createSlotMachine();
        this.createSlotCommand();
        this.createReplayCommand();

        this.refreshStatus();

        if (this._coin < scale) {
            this._slotCommandWindow.disableBet();
        }
    };

    Scene_SlotMachine.prototype.start = function () {
        this.makeReel();
        this._instructionWindow.refresh();
        this._slotMachineWindow.refresh();
        this._helpWindow.setText(helpMessage);
    };

    Scene_SlotMachine.prototype.makeReel = function () {
        for (var i = 0; i < 5; i++) {
            for (var j = 0; j < 18; j++) {
                for (var k = 0; k < 3; k++) {
                    this._reels[i].bitmap.drawImage(
                        this._reelBitmap,
                        reel[i][j] * 116,
                        0,
                        116,
                        54,
                        0,
                        (54 * 18 * 3) - j * 54 - k * (18 * 54) - 54);
                }
            }

            this._reels[i].setSpot(Math.random() * 18 >> 0);
        }
    };

    Scene_SlotMachine.prototype.isSpinning = function () {
        var returnValue = false;
        for (var i = 0; i < 5; i++) {
            returnValue = returnValue || this._reels[i].status !== SLTReelSprite.STOP;
        }
        return returnValue;
    };

    Scene_SlotMachine.prototype.isWinCounting = function () {
        return this._winCoin > 0;
    };

    Scene_SlotMachine.prototype.createHelpWindow = function () {
        Scene_MenuBase.prototype.createHelpWindow.call(this);
        this._helpWindow.y = Graphics.boxHeight - this._helpWindow.height;
    };

    Scene_SlotMachine.prototype.createInstruction = function () {
        this._instructionWindow = new Window_SlotInstruction(0, 0, Graphics.boxWidth, 26 * 6 + 18 * 2);
        this._instructionWindow.setOdds(odds);
        this.addWindow(this._instructionWindow);
    };

    Scene_SlotMachine.prototype.createSlotMachine = function () {
        this._slotMachineWindow = new Window_SlotMachine(0, this._instructionWindow.height, Graphics.boxWidth, 200);
        this._slotMachineWindow.coin = this._coin;
        this._slotMachineWindow.bet = this._bet;
        this.addWindow(this._slotMachineWindow);
    };

    Scene_SlotMachine.prototype.createSlotCommand = function () {
        this._slotCommandWindow = new Window_SlotCommand(0, 0);
        this._slotCommandWindow.setHandler('bet', this.betCommand.bind(this));
        this._slotCommandWindow.setHandler('spin', this.spinCommand.bind(this));
        this._slotCommandWindow.setHandler('cancel', this.cancelCommand.bind(this));
        this.addWindow(this._slotCommandWindow);
        this._slotCommandWindow.y = this._helpWindow.y - this._slotCommandWindow.height;
    };

    Scene_SlotMachine.prototype.createReplayCommand = function () {
        this._replayCommandWindow = new Window_ReplayCommand(0, 0);
        this._replayCommandWindow.setHandler('yes', this.replayCommand.bind(this));
        this._replayCommandWindow.setHandler('no', this.cancelCommand.bind(this));
        this._replayCommandWindow.setHandler('cancel', this.cancelCommand.bind(this));
        this.addWindow(this._replayCommandWindow);
        this._replayCommandWindow.x = Graphics.boxWidth - this._replayCommandWindow.width;
        this._replayCommandWindow.y = this._helpWindow.y - this._replayCommandWindow.height;
    };

    Scene_SlotMachine.prototype.createReels = function () {
        this._reelBitmap = ImageManager.loadBitmap("img/slotmachine/", "reel");
        this._reels = [];
        for (var i = 0; i < 5; i++) {
            var sprite = new SLTReelSprite(new Bitmap(116, 54 * 18 * 3));
            this._reels.push(sprite);
            sprite.x = 110 + i * 120;
            sprite.y = 222;
            sprite.setSpinEndFrame(SLTReelSprite.FRAME_SPIN + i * 40);
            sprite.setFrame(0, 0, 116, 54 * 3);
            this.addChild(sprite);
        }
    };

    Scene_SlotMachine.prototype.createBetLine = function () {
        var bitmap = ImageManager.loadBitmap("img/slotmachine/", "line_base");
        this._betLine = new LotLineSprite(bitmap);
        this._betLine.x = 43;
        this._betLine.y = 227;
        this._betLine.clear();
        this.addChild(this._betLine);
    };

    Scene_SlotMachine.prototype.createScale = function () {
        var bitmap;
        if (scale === 10) {
            bitmap = ImageManager.loadBitmap("img/slotmachine/", "scale_x10");
        }
        else if (scale === 100) {
            bitmap = ImageManager.loadBitmap("img/slotmachine/", "scale_x100");
        }
        else {
            bitmap = ImageManager.loadBitmap("img/slotmachine/", "scale_x1");
        }
        this._scale = new Sprite(bitmap);
        this._scale.x = 719;
        this._scale.y = 212;
        this.addChild(this._scale);
    };

    Scene_SlotMachine.prototype.cancelCommand = function () {
        this._bet = 0;
        this.refreshStatus();
        setCoin(this._coin);
        this.popScene();
    };

    Scene_SlotMachine.prototype.betCommand = function () {
        if (this._bet < 3) {
            this._bet++;
            this._slotCommandWindow.enableSpin();
        }
        if (this._bet > 2) {
            this._slotCommandWindow.disableBet();
        }
        if (this._coin - this._bet * scale < scale) {
            this._slotCommandWindow.disableBet();
        }

        this.refreshStatus();

        this._slotCommandWindow.activate();
    };

    Scene_SlotMachine.prototype.spinCommand = function () {
        this._coin -= this._bet * scale;
        this._slotCommandWindow.deactivate();
        this._slotCommandWindow.close();
        this._helpWindow.close();

        this._winSpot = this.drawLot();

        var t = "";
        var i;
        for (i = 0; i < 5; i++) {
            t += reel[i][this._winSpot[i]];
        }

        this._rollCount++;

        //Interval Spin
        //this._currentStartingReel = 0;
        //this._startingTimer = setInterval(function(){
        //    this._reels[this._currentStartingReel].spin();
        //    this._currentStartingReel++;
        //    console.log("this._currentStartingReel", this._currentStartingReel)
        //    if (this._currentStartingReel > 4) {
        //        clearInterval(this._startingTimer);
        //        this._startingTimer = null;
        //    }
        //}.bind(this), 200);

        this._spinStart = true;
        this._reels[0].setWinSpot(this._winSpot[0]);
        this._reels[1].setWinSpot(this._winSpot[1]);
        this._reels[2].setWinSpot(this._winSpot[2]);
        this._reels[3].setWinSpot(this._winSpot[3]);
        this._reels[4].setWinSpot(this._winSpot[4]);
        for (i = 0; i < 5; i++) {
            this._reels[i].spin();
        }
    };

    Scene_SlotMachine.prototype.result = function () {
        this._rollCount = 0;

        var win, tmp;
        win = this.judge(this._winSpot);
        tmp = win;
        if (this._coin + win > Scene_SlotMachine.COIN_MAX_VALUE) {
            win = Scene_SlotMachine.COIN_MAX_VALUE - this._coin;
        }
        this._winCoin = this._correctCoin = win;

        var time = 60 * 10;
        if (this._winCoin < time) {
            this._winStep = 1;
        }
        else {
            this._winStep = this._winCoin / time >> 0;
        }

        if (this._winCoin > 0) {
            this._winMessage = winMessage;
            var reg = /Win Coin/gi;
            this._winMessage = this._winMessage.replace(reg, String(tmp));
            this._helpWindow.setText(this._winMessage);
            this._helpWindow.open();
            AudioManager.playMe({ "name": "Victory1", "volume": 90, "pitch": 100, "pan": 0 });
        }
        else {
            this._helpWindow.setText(lostMessage + '\n' + replayMessage);
            this._helpWindow.open();
            this._replayCommandWindow.open();
            this._replayCommandWindow.activate();
        }
    };

    Scene_SlotMachine.prototype.judge = function (spot) {

        var result1 = [];
        result1.push(reel[0][(spot[0] + 1) % reel[0].length]);
        result1.push(reel[1][(spot[1] + 1) % reel[1].length]);
        result1.push(reel[2][(spot[2] + 1) % reel[2].length]);
        result1.push(reel[3][(spot[3] + 1) % reel[3].length]);
        result1.push(reel[4][(spot[4] + 1) % reel[4].length]);
        var result2 = [];
        result2.push(reel[0][spot[0]]);
        result2.push(reel[1][spot[1]]);
        result2.push(reel[2][spot[2]]);
        result2.push(reel[3][spot[3]]);
        result2.push(reel[4][spot[4]]);
        var result3 = [];
        result3.push(reel[0][(this._winSpot[0] - 1 + reel[0].length) % reel[0].length]);
        result3.push(reel[1][(this._winSpot[1] - 1 + reel[1].length) % reel[1].length]);
        result3.push(reel[2][(this._winSpot[2] - 1 + reel[2].length) % reel[2].length]);
        result3.push(reel[3][(this._winSpot[3] - 1 + reel[3].length) % reel[3].length]);
        result3.push(reel[4][(this._winSpot[4] - 1 + reel[4].length) % reel[4].length]);

        var returnValue = 0;
        var cursorArray = this._makeCursorArray();

        //line1
        var i, base;
        var win = 0;
        base = result1[0];
        if (this._bet > 1) {
            for (i = 1; i < 5; i++) {
                if (base !== result1[i]) {
                    break;
                }
            }
            i--;
            if (i > 1) {
                win = scale * odds[i - 2][base];
                cursorArray[i - 2][base] = true;
                returnValue += win;
            }
        }

        //line2
        win = 0;
        base = result2[0];
        if (this._bet > 0) {
            for (i = 1; i < 5; i++) {
                if (base !== result2[i]) {
                    break;
                }
            }
            i--;
            if (i > 1) {
                win = scale * odds[i - 2][base];
                cursorArray[i - 2][base] = true;
                returnValue += win;
            }
        }

        //line3
        win = 0;
        base = result3[0];
        if (this._bet > 2) {
            for (i = 1; i < 5; i++) {
                if (base !== result3[i]) {
                    break;
                }
            }
            i--;
            if (i > 1) {
                win = scale * odds[i - 2][base];
                cursorArray[i - 2][base] = true;
                returnValue += win;
            }
        }

        this._instructionWindow.blinkCursor(cursorArray);

        return returnValue;
    };

    Scene_SlotMachine.prototype.drawLot = function () {
        var i, j, l;
        var s;
        var spot = [];

        spot.push(Math.random() * reel[0].length >> 0);
        spot.push(Math.random() * reel[1].length >> 0);
        spot.push(Math.random() * reel[2].length >> 0);
        spot.push(Math.random() * reel[3].length >> 0);
        spot.push(Math.random() * reel[4].length >> 0);

        //2〜5reel
        var l1, l2, l3;
        var r;
        var target1 = true;
        var target2 = true;
        var target3 = true;
        for (i = 1; i < 5; i++) {

            for (j = 0; j < reel[i].length; j++) {
                if (this.isWin(spot, i)) {
                    spot[i] = (spot[i] + 1) % reel[i].length;
                }
                else {
                    break;
                }
            }

            l = reel[i - 1].length;
            l1 = reel[i - 1][(spot[i - 1] + 1 + l) % l];
            l2 = reel[i - 1][(spot[i - 1] + 0 + l) % l];
            l3 = reel[i - 1][(spot[i - 1] - 1 + l) % l];

            l = reel[i].length;

            r = Math.random();
            if (r < this._probability[i - 1][l2] && target2) {
                s = reel[i].indexOf(l2);
                if (s >= 0) {
                    spot[i] = (s + 0 + l) % l;
                    target1 = false;
                    target3 = false;
                }
                else {
                    console.error("Illegal lottery. r:", i, "l2:", l2);
                }
            }

            r = Math.random();
            if (r < this._probability[i - 1][l1] && target1) {
                s = reel[i].indexOf(l1);
                if (s >= 0) {
                    spot[i] = (s - 1 + l) % l;
                    target2 = false;
                    target3 = false;
                }
                else {
                    console.error("Illegal lottery. r:", i, "l1:", l1);
                }
            }

            r = Math.random();
            if (r < this._probability[i - 1][l3] && target3) {
                s = reel[i].indexOf(l3);
                if (s >= 0) {
                    spot[i] = (s + 1 + l) % l;
                    target1 = false;
                    target2 = false;
                }
                else {
                    console.error("Illegal lottery. r:", i, "l3:", l3);
                }
            }
        }

        return spot;
    };

    /**
     *
     * @param spot
     * @param r
     * @return {boolean}
     */
    Scene_SlotMachine.prototype.isWin = function (spot, r) {
        return !!(
            reel[r - 1][(spot[r - 1] + 1) % reel[r - 1].length] === reel[r][(spot[r] + 1) % reel[r].length] ||
            reel[r - 1][(spot[r - 1] + 0) % reel[r - 1].length] === reel[r][(spot[r] + 0) % reel[r].length] ||
            reel[r - 1][(spot[r - 1] - 1) % reel[r - 1].length] === reel[r][(spot[r] - 1) % reel[r].length]
        );
    };

    Scene_SlotMachine.prototype.correct = function () {
        this._coin += this._correctCoin;
        this._correctCoin = 0;
        if (this._coin >= Scene_SlotMachine.COIN_MAX_VALUE) {
            this._helpWindow.setText(coinFullMessage + '\n' + replayMessage);
        }
        else {
            this._helpWindow.setText(this._winMessage + '\n' + replayMessage);
        }
        this._winMessage = "";
        this._replayCommandWindow.open();
        this._replayCommandWindow.activate();
    };

    Scene_SlotMachine.prototype.replayCommand = function () {
        this._slotCommandWindow.enableBet();
        this._slotCommandWindow.disableSpin();
        if (this._coin < scale) {
            this._slotCommandWindow.disableBet();
        }
        this._slotCommandWindow.select(0);
        this._replayCommandWindow.close();
        this._slotCommandWindow.open();
        this._slotCommandWindow.activate();
        this._helpWindow.setText(helpMessage);

        this._bet = 0;
        this.refreshStatus();
    };

    Scene_SlotMachine.prototype.refreshStatus = function () {
        this._slotMachineWindow.bet = this._bet * scale;
        this._slotMachineWindow.coin = this._coin - this._bet * scale;

        if (this._bet === 0) {
            this._betLine.clear();
        }
        else {
            this._betLine.enableLine(this._bet - 1);
        }
    };

    Scene_SlotMachine.prototype.update = function () {
        Scene_MenuBase.prototype.update.call(this);

        var result = 0;
        if (this._spinStart && !this.isSpinning()) {
            this._spinStart = false;
            this.result();
        }
        else if (this.isWinCounting()) {
            if (this._winCoin <= this._winStep) {
                this._winCoin = 0;
                result = this._coin + this._correctCoin;
                this._slotMachineWindow.coin = result;
                this.correct();
            }
            else {
                this._winCoin -= this._winStep;
                result = this._coin + this._correctCoin - this._winCoin;
                this._slotMachineWindow.coin = result;
            }
        }

        if (Input.isRepeated('up') && this._slotCommandWindow.active) {
            if (this._slotCommandWindow.isAllowBet) {
                SoundManager.playOk();
                this.betCommand();
            }
            else {
                SoundManager.playBuzzer();
            }
        }
        if (Input.isRepeated('down') && this._slotCommandWindow.active) {
            if (this._slotCommandWindow.isAllowSpin && !this._spinStart) {
                SoundManager.playOk();
                this.spinCommand();
            }
        }
    };

    Scene_SlotMachine.prototype._makeCursorArray = function () {
        var returnValue = [];
        for (var i = 0; i < 3; i++) {
            returnValue.push([]);
            for (var j = 0; j < 6; j++) {
                returnValue[i].push(false);
            }
        }
        return returnValue;
    };

    //-----------------------------------------------------------------------------
    // Window_SlotInstruction
    //
    // This window is instruction card for the slot machines.

    function Window_SlotInstruction() {
        this.initialize.apply(this, arguments);
    }

    Window_SlotInstruction.prototype = Object.create(Window_Base.prototype);
    Window_SlotInstruction.prototype.constructor = Window_SlotInstruction;

    Window_SlotInstruction.prototype.initialize = function (x, y, width, height) {
        Window_Base.prototype.initialize.call(this, x, y, width, height);

        this._cursol = [[], [], []];
        var b = ImageManager.loadBitmap("img/slotmachine/", "win_cursor");

        var cx = 47;
        var cy = 32;
        var cw = 224;
        for (var i = 2; i >= 0; i--) {
            for (var j = 5; j >= 0; j--) {
                var sprite = new InstructionCursorSprite(b);
                this.addChild(sprite);
                sprite.x = cx + i * (cw + 20);
                sprite.y = cy + j * 24;
                this._cursol[2 - i].push(sprite);
            }
        }
        this.clearCursor();
    };

    Window_SlotInstruction.prototype.lineHeight = function () {
        return 24;
    };

    Window_SlotInstruction.prototype.refresh = function () {
        this.setBackgroundType(2);
        this.contents.clear();

        if (this._odds) {
            this.contents.fontSize = 22;
            var x = 51 - 18;
            var y = 14;
            var w = 224;
            this.drawText(this._odds[2][5], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[2][4], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[2][3], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[2][2], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[2][1], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[2][0], x, y, w, "right");

            x += w + 20;
            y = 14;
            this.drawText(this._odds[1][5], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[1][4], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[1][3], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[1][2], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[1][1], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[1][0], x, y, w, "right");

            x += w + 20;
            y = 14;
            this.drawText(this._odds[0][5], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[0][4], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[0][3], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[0][2], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[0][1], x, y, w, "right");
            y += this.lineHeight();
            this.drawText(this._odds[0][0], x, y, w, "right");
        }
        this.contents.fontSize = this.standardFontSize();

    };

    Window_SlotInstruction.prototype.setOdds = function (odds) {
        this._odds = odds;
    };

    Window_SlotInstruction.prototype.clearCursor = function () {
        for (var i = 0; i < 3; i++) {
            for (var j = 0; j < 6; j++) {
                this._cursol[i][j].visible = false;
            }
        }
    };

    Window_SlotInstruction.prototype.blinkCursor = function (array) {
        for (var i = 0; i < 3; i++) {
            for (var j = 0; j < 6; j++) {
                if (array[i][j]) this._cursol[i][j].blink();
            }
        }
    };

    //-----------------------------------------------------------------------------
    // Window_SlotMachine
    //
    // This window is the slot machine body.

    function Window_SlotMachine() {
        this.initialize.apply(this, arguments);
    }

    Window_SlotMachine.prototype = Object.create(Window_Base.prototype);
    Window_SlotMachine.prototype.constructor = Window_SlotMachine;

    Window_SlotMachine.prototype.initialize = function (x, y, width, height) {
        Window_Base.prototype.initialize.call(this, x, y, width, height);

        this._lastCoin = 0;
        this._lastBet = 0;
        this._coin = 0;
        this._bet = 0;
    };

    /**
     * The bitmap used for the coin.
     *
     * @property coinContents
     * @type Bitmap
     */
    Object.defineProperty(Window_SlotMachine.prototype, 'coinContents', {
        get: function () {
            return this._windowCoinSprite.bitmap;
        },
        set: function (value) {
            this._windowCoinSprite.bitmap = value;
        },
        configurable: true
    });

    /**
     * The bitmap used for the bet.
     *
     * @property betContents
     * @type Bitmap
     */
    Object.defineProperty(Window_SlotMachine.prototype, 'betContents', {
        get: function () {
            return this._windowBetSprite.bitmap;
        },
        set: function (value) {
            this._windowBetSprite.bitmap = value;
        },
        configurable: true
    });

    /**
     * The coin.
     *
     * @property coin
     * @type Number
     */
    Object.defineProperty(Window_SlotMachine.prototype, 'coin', {
        get: function () {
            return this._coin;
        },
        set: function (value) {
            this._coin = value;
        },
        configurable: true
    });

    /**
     * The bet.
     *
     * @property bet
     * @type Number
     */
    Object.defineProperty(Window_SlotMachine.prototype, 'bet', {
        get: function () {
            return this._bet;
        },
        set: function (value) {
            this._bet = value;
        },
        configurable: true
    });

    Window_SlotMachine.prototype.updateBackground = function () {
        Window_Base.prototype.updateBackground.call(this);
        this.setBackgroundType(2);
    };

    Window_SlotMachine.prototype.start = function () {
    };

    Window_SlotMachine.prototype.createContents = function () {
        Window_Base.prototype.createContents.call(this);

        this.coinContents = new Bitmap(this.contents.measureTextWidth("99999999"), this.lineHeight());
        this.betContents = new Bitmap(this.contents.measureTextWidth("999"), this.lineHeight());
    };

    /**
     * @method _createAllParts
     * @private
     */
    Window_SlotMachine.prototype._createAllParts = function () {
        Window_Base.prototype._createAllParts.call(this);

        this._windowCoinSprite = new Sprite();
        this.addChild(this._windowCoinSprite);
        this._windowCoinSprite.move(320, 213);

        this._windowBetSprite = new Sprite();
        this.addChild(this._windowBetSprite);
        this._windowBetSprite.move(566, 213);
    };

    Window_SlotMachine.prototype.refresh = function () {
        this.setBackgroundType(2);
        this.refreshCoin();
        this.refreshBet();
    };

    Window_SlotMachine.prototype.update = function () {
        Window_Base.prototype.update.call(this);

        if (this._lastCoin !== this._coin) {
            this.refreshCoin();
            this._lastCoin = this._coin;
        }

        if (this._lastBet !== this._bet) {
            this.refreshBet();
            this._lastBet = this._bet;
        }
    };

    Window_SlotMachine.prototype.refreshCoin = function () {
        this.coinContents.clear();
        this.drawCoinText(this._coin, 0, 0, this.contents.measureTextWidth("99999999"), "right");
    };

    Window_SlotMachine.prototype.refreshBet = function () {
        this.betContents.clear();
        this.drawBetText(this._bet, 0, 0, this.contents.measureTextWidth("999"), "right");
    };

    Window_SlotMachine.prototype.drawCoinText = function (text, x, y, maxWidth, align) {
        this.coinContents.drawText(text, x, y, maxWidth, this.lineHeight(), align);
    };

    Window_SlotMachine.prototype.drawBetText = function (text, x, y, maxWidth, align) {
        this.betContents.drawText(text, x, y, maxWidth, this.lineHeight(), align);
    };

    //-----------------------------------------------------------------------------
    // Window_SlotCommand
    //
    // This window is command window for the slot machines.

    function Window_SlotCommand() {
        this.initialize.apply(this, arguments);
    }

    Window_SlotCommand.prototype = Object.create(Window_HorzCommand.prototype);
    Window_SlotCommand.prototype.constructor = Window_SlotCommand;

    Window_SlotCommand.prototype.initialize = function (x, y) {
        this._betAllow = true;
        this._spinAllow = false;
        Window_HorzCommand.prototype.initialize.call(this, x, y);
    };

    Object.defineProperty(Window_SlotCommand.prototype, 'isAllowBet', {
        get: function () {
            return this._betAllow;
        },
        configurable: true
    });

    Object.defineProperty(Window_SlotCommand.prototype, 'isAllowSpin', {
        get: function () {
            return this._spinAllow;
        },
        configurable: true
    });

    Window_SlotCommand.prototype.enableBet = function () {
        this._betAllow = true;
        this.refresh();
    };

    Window_SlotCommand.prototype.disableBet = function () {
        this._betAllow = false;
        this.refresh();
    };

    Window_SlotCommand.prototype.enableSpin = function () {
        this._spinAllow = true;
        this.refresh();
    };

    Window_SlotCommand.prototype.disableSpin = function () {
        this._spinAllow = false;
        this.refresh();
    };

    Window_SlotCommand.prototype.makeCommandList = function () {
        this.addCommand(betText, 'bet', this._betAllow);
        this.addCommand(spinText, 'spin', this._spinAllow);
        this.addCommand(TextManager.cancel, 'cancel');
    };

    Window_SlotCommand.prototype.windowWidth = function () {
        return Graphics.boxWidth;
    };

    Window_SlotCommand.prototype.maxCols = function () {
        return 3;
    };

    //-----------------------------------------------------------------------------
    // Window_ReplayCommand
    //
    // This window is replay command window for the slot machines.

    function Window_ReplayCommand() {
        this.initialize.apply(this, arguments);
    }

    Window_ReplayCommand.prototype = Object.create(Window_Command.prototype);
    Window_ReplayCommand.prototype.constructor = Window_ReplayCommand;

    Window_ReplayCommand.prototype.initialize = function (x, y) {
        Window_HorzCommand.prototype.initialize.call(this, x, y);
        this.openness = 0;
    };

    Window_ReplayCommand.prototype.makeCommandList = function () {
        this.addCommand(yesText, 'yes');
        this.addCommand(noText, 'no');
    };

})();


code:
/*=============================================================================
 StateAfterDeath.js
----------------------------------------------------------------------------
 (C)2018 Triacontane
 This software is released under the MIT License.
 http://opensource.org/licenses/mit-license.php
----------------------------------------------------------------------------
 Version
 1.0.2 2021/09/16 戦闘不能後継続ステートをすでに戦闘不能のバトラーに付与したときにも付与できるよう修正
 1.0.1 2018/08/12 継続ステートが戦闘不能後にターン数で解除されなくなっていた問題を修正
 1.0.0 2018/08/12 初版
----------------------------------------------------------------------------
 [Blog]   : https://triacontane.blogspot.jp/
 [Twitter]: https://twitter.com/triacontane/
 [GitHub] : https://github.com/triacontane/
=============================================================================*/

/*:
 * @plugindesc StateAfterDeathPlugin
 * @author triacontane
 *
 * @param states
 * @desc 戦闘不能後も継続するステートの配列の一覧です。
 * @type state[]
 * @default []
 *
 * @help StateAfterDeath.js
 *
 * 戦闘不能後も解除されず継続するステートを作成できます。
 * パラメータから対象となるステートを指定してください。
 *
 * このプラグインにはプラグインコマンドはありません。
 *
 * This plugin is released under the MIT License.
 */
/*:ja
 * @plugindesc 戦闘不能後継続ステートプラグイン
 * @author トリアコンタン
 *
 * @param states
 * @text 対象ステート
 * @desc 戦闘不能後も継続するステートの配列の一覧です。
 * @type state[]
 * @default []
 *
 * @help StateAfterDeath.js
 *
 * 戦闘不能後も解除されず継続するステートを作成できます。
 * パラメータから対象となるステートを指定してください。
 *
 * このプラグインにはプラグインコマンドはありません。
 *
 * 利用規約：
 *  作者に無断で改変、再配布が可能で、利用形態（商用、18禁利用等）
 *  についても制限はありません。
 *  このプラグインはもうあなたのものです。
 */

(function () {
    'use strict';

    /**
     * Create plugin parameter. param[paramName] ex. param.commandPrefix
     * @param pluginName plugin name(EncounterSwitchConditions)
     * @returns {Object} Created parameter
     */
    var createPluginParameter = function (pluginName) {
        var paramReplacer = function (key, value) {
            if (value === 'null') {
                return value;
            }
            if (value[0] === '"' && value[value.length - 1] === '"') {
                return value;
            }
            try {
                return JSON.parse(value);
            } catch (e) {
                return value;
            }
        };
        var parameter = JSON.parse(JSON.stringify(PluginManager.parameters(pluginName), paramReplacer));
        PluginManager.setParameters(pluginName, parameter);
        return parameter;
    };

    var param = createPluginParameter('StateAfterDeath');
    if (!param.states) {
        param.states = [];
    }

    var _Game_BattlerBase_die = Game_BattlerBase.prototype.die;
    Game_BattlerBase.prototype.die = function () {
        var stillStates = this._states.filter(function (stateId) {
            return param.states.contains(stateId);
        });
        var stillStateTurns = {};
        stillStates.forEach(function (stateId) {
            stillStateTurns[stateId] = this._stateTurns[stateId];
        }, this);
        _Game_BattlerBase_die.apply(this, arguments);
        this._states = this._states.concat(stillStates);
        this._stateTurns = stillStateTurns;
    };

    const _Game_BattlerBase_isAlive = Game_BattlerBase.prototype.isAlive;
    Game_BattlerBase.prototype.isAlive = function () {
        const result = _Game_BattlerBase_isAlive.apply(this, arguments);
        return this._ignoreDeath ? true : result;
    };

    const _Game_Battler_isStateAddable = Game_Battler.prototype.isStateAddable;
    Game_Battler.prototype.isStateAddable = function (stateId) {
        if (param.states.contains(stateId)) {
            this._ignoreDeath = true;
        }
        const result = _Game_Battler_isStateAddable.apply(this, arguments);
        this._ignoreDeath = false;
        return result;
    };
})();

repo_name: dazed/translations

license: unknown


code:
//=============================================================================
// Storage.js
//=============================================================================
/*:
 * @plugindesc シンプルな預かり所を追加します。
 * @author 翠
 * @help プラグインコマンド ｢Storage｣をイベントに記述してください。
 *
 * @param 預かり数
 * @desc 預けられる最大の数
 * @default 999
 *
 * @param 倉庫リストの区切り位置
 * @desc 倉庫リストの：の位置
 * 預かり数2桁なら00
 * 預かり数3桁なら000
 * @default 000
 *
 * @param 預けるコマンドの名称
 * @desc
 * @default 預ける
 *
 * @param 引き出すコマンドの名称
 * @desc
 * @default 引き出す
 *
 * @param 大事な物カテゴリ表示フラグ
 * @desc
 * @default false
 *
 * @param 数値ウィンドウ横幅
 * @desc
 * @default 400
 *
 * @param 数値ウィンドウ縦幅
 * @desc
 * @default 76
 *
 * @param 数値ウィンドウ縦位置補正
 * @desc
 * @default 24
 *
*/

var $gameStorage = null;
var Mot = Mot || {};
Mot.Storage = Mot.Storage || {};
Mot.Storage.DataManager_createGameObjects = DataManager.createGameObjects;
DataManager.createGameObjects = function () {
    Mot.Storage.DataManager_createGameObjects.call(this);
    $gameStorage = new Game_Storage();
};

Mot.Storage.DataManager_makeSaveContents = DataManager.makeSaveContents;
DataManager.makeSaveContents = function () {
    var contents = Mot.Storage.DataManager_makeSaveContents.call(this);
    contents.storage = $gameStorage;
    return contents;
};
Mot.Storage.DataManager_extractSaveContents = DataManager.extractSaveContents;
DataManager.extractSaveContents = function (contents) {
    Mot.Storage.DataManager_extractSaveContents.call(this, contents);
    $gameStorage = contents.storage;
};

function Game_Storage() {
    this.initialize.apply(this, arguments);
}
(function () {
    var parameters = PluginManager.parameters('Storage');
    var l_pos = String(parameters['倉庫リストの区切り位置'] || '000');
    var s_val = String(parameters['引き出すコマンドの名称'] || '預ける');
    var p_val = String(parameters['預けるコマンドの名称'] || '引き出す');
    var c_vis = String(parameters['大事な物カテゴリ表示フラグ'] || 'false');
    var maxst = Number(parameters['預かり数'] || 999);
    var num_w = Number(parameters['数値ウィンドウ横幅'] || 400);
    var num_h = Number(parameters['数値ウィンドウ縦幅'] || 76);
    var num_y = Number(parameters['数値ウィンドウ縦位置補正'] || 24);

    var _Game_Interpreter_pluginCommand =
        Game_Interpreter.prototype.pluginCommand;
    Game_Interpreter.prototype.pluginCommand = function (command, args) {
        _Game_Interpreter_pluginCommand.call(this, command, args);
        if (command === 'Storage') {
            SceneManager.push(Scene_Storage);
        }
    };
    Game_Storage.prototype = Object.create(Game_Unit.prototype);
    Game_Storage.prototype.constructor = Game_Storage;

    Game_Storage.prototype.initialize = function () {
        Game_Unit.prototype.initialize.call(this);
        this._lastItem = new Game_Item();
        this.initAllItems();
    };

    Game_Storage.prototype.initAllItems = function () {
        this._items = {};
        this._weapons = {};
        this._armors = {};
    };

    Game_Storage.prototype.items = function () {
        var list = [];
        for (var id in this._items) {
            list.push($dataItems[id]);
        }
        return list;
    };

    Game_Storage.prototype.weapons = function () {
        var list = [];
        for (var id in this._weapons) {
            list.push($dataWeapons[id]);
        }
        return list;
    };

    Game_Storage.prototype.armors = function () {
        var list = [];
        for (var id in this._armors) {
            list.push($dataArmors[id]);
        }
        return list;
    };
    Game_Storage.prototype.equipItems = function () {
        return this.weapons().concat(this.armors());
    };

    Game_Storage.prototype.allItems = function () {
        return this.items().concat(this.equipItems());
    };

    Game_Storage.prototype.itemContainer = function (item) {
        if (!item) {
            return null;
        } else if (DataManager.isItem(item)) {
            return this._items;
        } else if (DataManager.isWeapon(item)) {
            return this._weapons;
        } else if (DataManager.isArmor(item)) {
            return this._armors;
        } else {
            return null;
        }
    };

    Game_Storage.prototype.numItems = function (item) {
        var container = this.itemContainer(item);
        return container ? container[item.id] || 0 : 0;
    };

    Game_Storage.prototype.maxItems = function (item) {
        return maxst;
    };

    Game_Storage.prototype.hasMaxItems = function (item) {
        return this.numItems(item) >= this.maxItems(item);
    };

    Game_Storage.prototype.hasItem = function (item, includeEquip) {
        if (includeEquip === undefined) {
            includeEquip = false;
        }
        if (this.numItems(item) > 0) {
            return true;
        } else if (includeEquip && this.isAnyMemberEquipped(item)) {
            return true;
        } else {
            return false;
        }
    };

    Game_Party.prototype.lastItem = function () {
        return this._lastItem.object();
    };

    Game_Party.prototype.setLastItem = function (item) {
        this._lastItem.setObject(item);
    };

    Game_Storage.prototype.isAnyMemberEquipped = function (item) {
        return this.members().some(function (actor) {
            return actor.equips().contains(item);
        });
    };

    Game_Storage.prototype.gainItem = function (item, amount, includeEquip) {
        var container = this.itemContainer(item);
        if (container) {
            var lastNumber = this.numItems(item);
            var newNumber = lastNumber + amount;
            container[item.id] = newNumber.clamp(0, this.maxItems(item));
            if (container[item.id] === 0) {
                delete container[item.id];
            }
            $gameMap.requestRefresh();
        }
    };

    Game_Storage.prototype.loseItem = function (item, amount, includeEquip) {
        this.gainItem(item, -amount, includeEquip);
    };

    //-----------------------------------------------------------------------------
    // Scene_Storage
    //-----------------------------------------------------------------------------

    function Scene_Storage() {
        this.initialize.apply(this, arguments);
    }

    Scene_Storage.prototype = Object.create(Scene_ItemBase.prototype);
    Scene_Storage.prototype.constructor = Scene_Storage;

    Scene_Storage.prototype.initialize = function () {
        Scene_ItemBase.prototype.initialize.call(this);
        this.sMode = null;
    };

    Scene_Storage.prototype.create = function () {
        Scene_ItemBase.prototype.create.call(this);
        this.createHelpWindow();
        this.createCoiceWindow();
        this.createCategoryWindow();
        this.createSItemWindow();
        this.createPItemWindow();
        this.createNumberWindow();
    };

    Scene_Storage.prototype.createCategoryWindow = function () {
        this._categoryWindow = new Window_ItemCategory();
        this._categoryWindow.setHelpWindow(this._helpWindow);
        this._categoryWindow.y = this._helpWindow.height;
        this._categoryWindow.setHandler('ok', this.selectStorage.bind(this));
        this._categoryWindow.setHandler('cancel', this.popScene.bind(this));
        this.addWindow(this._categoryWindow);
    };

    Scene_Storage.prototype.createCoiceWindow = function () {
        this._coiceWindow = new Window_Coice();
        this._coiceWindow.setHelpWindow(this._helpWindow);
        this._coiceWindow.y = this._helpWindow.height;
        this._coiceWindow.setHandler('ok', this.storageOk.bind(this));
        this._coiceWindow.setHandler('cancel', this.returnCategory.bind(this));
        this.addWindow(this._coiceWindow);
        this._coiceWindow.deactivate();

    };
    Scene_Storage.prototype.createSItemWindow = function () {
        var wy = this._categoryWindow.y + this._categoryWindow.height;
        var wh = Graphics.boxHeight - wy;
        this._sitemWindow = new Window_ItemList_Storage(0, wy, Graphics.boxWidth / 2, wh);
        this._sitemWindow.setHelpWindow(this._helpWindow);
        this._sitemWindow.setHandler('ok', this.onItemOk.bind(this));
        this._sitemWindow.setHandler('cancel', this.returnCoice.bind(this));
        this.addWindow(this._sitemWindow);
        this._categoryWindow.setSItemWindow(this._sitemWindow);
    };
    Scene_Storage.prototype.createPItemWindow = function () {
        var wy = this._categoryWindow.y + this._categoryWindow.height;
        var wh = Graphics.boxHeight - wy;
        var wx = this._sitemWindow.width;
        this._pitemWindow = new Window_ItemList_Paty(wx, wy, Graphics.boxWidth / 2, wh);
        this._pitemWindow.setHelpWindow(this._helpWindow);
        this._pitemWindow.setHandler('ok', this.onItemOk.bind(this));
        this._pitemWindow.setHandler('cancel', this.returnCoice.bind(this));
        this.addWindow(this._pitemWindow);
        this._categoryWindow.setPItemWindow(this._pitemWindow);
    };

    Scene_Storage.prototype.createNumberWindow = function () {
        var wy = (Graphics.boxHeight / 2) - (num_h + num_y);
        var wx = (Graphics.boxWidth - num_w) / 2;
        this._numberWindow = new Window_StorageNumber(wx, wy, num_w);
        this._numberWindow.hide();
        this._numberWindow.setHandler('ok', this.onNumberOk.bind(this));
        this._numberWindow.setHandler('cancel', this.onNumberCancel.bind(this));
        this.addWindow(this._numberWindow);
    };

    Scene_Storage.prototype.selectStorage = function () {
        this._categoryWindow.deactivate();
        this._categoryWindow.hide();
        this._coiceWindow.activate();
        this._coiceWindow.show();

    };

    Scene_Storage.prototype.storageOk = function () {
        this.sMode = (this._coiceWindow._index == 0) ? this._pitemWindow : this._sitemWindow;
        this.sMode.activate();
        this.sMode.select(0);
    };

    Scene_Storage.prototype.returnCategory = function () {
        this._categoryWindow.activate();
        this._categoryWindow.show();
        this._coiceWindow.deactivate();
        this._coiceWindow.hide();
    };

    Scene_Storage.prototype.onItemOk = function () {
        this._numberWindow.setup(this.sMode.getitem(), this.sMode.getnum(), this._coiceWindow._index);
        this._numberWindow.setCurrencyUnit(true);
        this._numberWindow.show();
        this._numberWindow.activate();
    };

    Scene_Storage.prototype.returnCoice = function () {
        this.sMode.deselect();
        this.sMode.deactivate();
        this._coiceWindow.activate();
    };

    Scene_Storage.prototype.onCategoryOk = function () {
        this._itemWindow.activate();
        this._itemWindow.selectLast();
    };

    Scene_Storage.prototype.onNumberOk = function () {
        var item = this._numberWindow.tradeItem();
        if (this._coiceWindow._index == 0) {
            $gameParty.loseItem(item[0], item[1]);
            $gameStorage.gainItem(item[0], item[1]);
        } else {
            $gameParty.gainItem(item[0], item[1]);
            $gameStorage.loseItem(item[0], item[1]);
        }
        SoundManager.playOk();
        this._sitemWindow.refresh();
        this._pitemWindow.refresh();

        this.sMode.activate();
        this._numberWindow.hide();
        this._numberWindow.deactivate();
    };

    Scene_Storage.prototype.onNumberCancel = function () {
        this.sMode.activate();
        this._numberWindow.hide();
        this._numberWindow.deactivate();
    };

    //-----------------------------------------------------------------------------
    // Window_Coice
    //-----------------------------------------------------------------------------

    function Window_Coice() {
        this.initialize.apply(this, arguments);
    }

    Window_Coice.prototype = Object.create(Window_HorzCommand.prototype);
    Window_Coice.prototype.constructor = Window_Coice;

    Window_Coice.prototype.initialize = function () {
        Window_HorzCommand.prototype.initialize.call(this, 0, 0);
    };

    Window_Coice.prototype.windowWidth = function () {
        return Graphics.boxWidth;
    };

    Window_Coice.prototype.maxCols = function () {
        return 2;
    };

    Window_Coice.prototype.makeCommandList = function () {
        this.addCommand(p_val, 'gain');
        this.addCommand(s_val, 'lose');
    };

    //-----------------------------------------------------------------------------
    // Window_ItemCategory
    //-----------------------------------------------------------------------------

    function Window_ItemCategory() {
        this.initialize.apply(this, arguments);
    }

    Window_ItemCategory.prototype = Object.create(Window_HorzCommand.prototype);
    Window_ItemCategory.prototype.constructor = Window_ItemList;

    Window_ItemCategory.prototype.initialize = function () {
        Window_HorzCommand.prototype.initialize.call(this, 0, 0);
    };

    Window_ItemCategory.prototype.windowWidth = function () {
        return Graphics.boxWidth;
    };

    Window_ItemCategory.prototype.maxCols = function () {
        if (c_vis == 'true') {
            return 4;
        } else {
            return 3;
        }
    };

    Window_ItemCategory.prototype.update = function () {
        Window_HorzCommand.prototype.update.call(this);
        if (this._sitemWindow) {
            this._sitemWindow.setCategory(this.currentSymbol());
        }
        if (this._pitemWindow) {
            this._pitemWindow.setCategory(this.currentSymbol());
        }
    };

    Window_ItemCategory.prototype.makeCommandList = function () {
        this.addCommand(TextManager.item, 'item');
        this.addCommand(TextManager.weapon, 'weapon');
        this.addCommand(TextManager.armor, 'armor');
        if (c_vis == 'true') {
            this.addCommand(TextManager.keyItem, 'keyItem');
        };
    };

    Window_ItemCategory.prototype.setItemWindow = function (itemWindow) {
        this._sitemWindow = itemWindow;
        this._pitemWindow = itemWindow;
        this.update();
    };
    Window_ItemCategory.prototype.setSItemWindow = function (itemWindow) {
        this._sitemWindow = itemWindow;
        this.update();
    };
    Window_ItemCategory.prototype.setPItemWindow = function (itemWindow) {
        this._pitemWindow = itemWindow;
        this.update();
    };

    //-----------------------------------------------------------------------------
    // Window_ItemList_Paty
    //-----------------------------------------------------------------------------

    function Window_ItemList_Paty() {
        this.initialize.apply(this, arguments);
    }

    Window_ItemList_Paty.prototype = Object.create(Window_ItemList.prototype);
    Window_ItemList_Paty.prototype.constructor = Window_ItemList;

    Window_ItemList_Paty.prototype.maxCols = function () {
        return 1;
    };

    Window_ItemList_Paty.prototype.isCurrentItemEnabled = function () {
        return this.item();
    };
    Window_ItemList_Paty.prototype.isEnabled = function (item) {
        return true;
    };

    Window_ItemList_Paty.prototype.makeItemList = function () {
        this._data = $gameParty.allItems().filter(function (item) {
            return this.includes(item);
        }, this);
        if (this.includes(null)) {
            this._data.push(null);
        }
    };

    Window_ItemList_Paty.prototype.selectLast = function () {
        var index = this._data.indexOf($gameParty.lastItem());
        this.select(index >= 0 ? index : 0);
    };

    Window_ItemList_Paty.prototype.drawItemNumber = function (item, x, y, width) {
        if (this.needsNumber()) {
            this.drawText(':', x, y, width - this.textWidth('00'), 'right');
            this.drawText($gameParty.numItems(item), x, y, width, 'right');
        }
    };
    Window_ItemList_Paty.prototype.getitem = function () {
        var index = this.index();
        var item = this._data[index];
        return this._data && index >= 0 ? this._data[index] : null;
    };
    Window_ItemList_Paty.prototype.getnum = function () {
        var index = this.index();
        var item = this._data[index];
        return $gameParty.numItems(item)
    };

    //-----------------------------------------------------------------------------
    // Window_ItemList_Storage
    //-----------------------------------------------------------------------------

    function Window_ItemList_Storage() {
        this.initialize.apply(this, arguments);
    }

    Window_ItemList_Storage.prototype = Object.create(Window_ItemList.prototype);
    Window_ItemList_Storage.prototype.constructor = Window_ItemList_Storage;

    Window_ItemList_Storage.prototype.maxCols = function () {
        return 1;
    };

    Window_ItemList_Storage.prototype.isCurrentItemEnabled = function () {
        return this.item();
    };

    Window_ItemList_Storage.prototype.isEnabled = function (item) {
        return true
    };

    Window_ItemList_Storage.prototype.makeItemList = function () {
        this._data = $gameStorage.allItems().filter(function (item) {
            return this.includes(item);
        }, this);
        if (this.includes(null)) {
            this._data.push(null);
        }
    };

    Window_ItemList_Storage.prototype.selectLast = function () {
        var index = this._data.indexOf($gameStorage.lastItem());
        this.select(index >= 0 ? index : 0);
    };

    Window_ItemList_Storage.prototype.drawItemNumber = function (item, x, y, width) {
        if (this.needsNumber()) {
            this.drawText(':', x, y, width - this.textWidth(l_pos), 'right');
            this.drawText($gameStorage.numItems(item), x, y, width, 'right');
        }
    };

    Window_ItemList_Storage.prototype.getitem = function () {
        var index = this.index();
        var item = this._data[index];
        return this._data && index >= 0 ? this._data[index] : null;
    };
    Window_ItemList_Storage.prototype.getnum = function () {
        var index = this.index();
        var item = this._data[index];
        return $gameStorage.numItems(item)
    };
    //-----------------------------------------------------------------------------
    // Window_StorageNumber
    //-----------------------------------------------------------------------------

    function Window_StorageNumber() {
        this.initialize.apply(this, arguments);
    }

    Window_StorageNumber.prototype = Object.create(Window_ShopNumber.prototype);
    Window_StorageNumber.prototype.constructor = Window_StorageNumber;

    Window_StorageNumber.prototype.initialize = function (x, y, height) {
        var width = this.windowWidth();
        Window_Selectable.prototype.initialize.call(this, x, y, width, num_h);
        this._item = null;
        this._max = 1;
        this._number = 1;
        this._currencyUnit = TextManager.currencyUnit;
    };

    Window_StorageNumber.prototype.windowWidth = function () {
        return num_w;
    };

    Window_StorageNumber.prototype.setup = function (item, max, mode) {
        this._item = item;
        this._max = Math.floor(max);
        this._mode = mode;
        this._gameob = (mode == 0 ? $gameStorage : $gameParty);
        this._number = (this._gameob.maxItems() == this._gameob.numItems(this._item)) ? 0 : 1;
        this.refresh();
    };

    Window_StorageNumber.prototype.refresh = function () {
        this.contents.clear();
        this.drawItemName(this._item, 0, 0);
        this.drawMultiplicationSign();
        this.drawNumber();
    };

    Window_StorageNumber.prototype.changeNumber = function (amount) {
        var lastNumber = this._number;
        var maxtemp = (this._mode == 0 ? this._gameob.maxItems() : this._gameob.maxItems());
        var temp = (this._number + amount).clamp(1, this._max);
        if ((this._gameob.numItems(this._item) + temp) <= maxtemp) {
            this._number = temp;
        } else {
            this._number = (maxtemp - this._gameob.numItems(this._item));
        }
        if (this._number !== lastNumber) {
            SoundManager.playCursor();
            this.refresh();
        }
    };

    Window_StorageNumber.prototype.tradeItem = function () {
        return [this._item, this._number];
    };

    Window_StorageNumber.prototype.itemY = function () {
        return 0
    };

    Window_StorageNumber.prototype.maxDigits = function () {
        return 2;
    };

})();


code:
//=============================================================================
// Swimming&Diving.js
// by Tsukimi
// Last Updated: 2017.11.21
//=============================================================================

/*:
 * @plugindesc Swimming and diving System
 * @author Tsukimi
 *
 * @param diving/surface Region 1
 * @desc diving/surface Region 1 (0 = don't use)
 * @type number
 * @min 0
 * @max 255
 * @default 21
 *
 * @param diving/surface Region 2
 * @desc diving/surface Region 2 (0 = don't use)
 * @type number
 * @min 0
 * @max 255
 * @default 22
 *
 * @param diving/surface Region 3
 * @desc diving/surface Region 3 (0 = don't use)
 * @type number
 * @min 0
 * @max 255
 * @default 23
 *
 * @param diving/surface Region 4
 * @desc diving/surface Region 4 (0 = don't use)
 * @type number
 * @min 0
 * @max 255
 * @default 0
 *
 * @param diving/surface Region 5
 * @desc diving/surface Region 5 (0 = don't use)
 * @type number
 * @min 0
 * @max 255
 * @default 0
 * @param diving/surface Region 6
 * @desc diving/surface Region 6 (0 = don't use)
 * @type number
 * @min 0
 * @max 255
 * @default 0
 *
 * @param diving/surface Region 7
 * @desc diving/surface Region 7 (0 = don't use)
 * @type number
 * @min 0
 * @max 255
 * @default 0
 * @param diving/surface Region 8
 * @desc diving/surface Region 8 (0 = don't use)
 * @type number
 * @min 0
 * @max 255
 * @default 0
 *
 * @param diving/surface Region 9
 * @desc diving/surface Region 9 (0 = don't use)
 * @type number
 * @min 0
 * @max 255
 * @default 0
 *
 * @help
 *
 * Plugin Command:
 */

/*:ja
 * @plugindesc 遊泳＆ダイビング　システム
 * @author ツキミ
 *
 * @param 選択肢自動表示
 * @desc 条件が満たされると選択肢を自動表示するかどうか。
 * スイッチによる制御も可能。　記入例：true / false / 12
 * @default true
 *
 * @param 水中減速
 * @desc 水の抵抗力による減速（デフォルト移動速度は4）
 * @type number
 * @min 0
 * @max 2
 * @decimals 1
 * @default 0.3
 *
 * @param 水面歩行画像変更
 * @desc 水面にいる時に自動で 「元ファイル名_swim」の画像に変更
 * 例：actor.png→ actor_swim.png　※フォロワーにも有効
 * @type boolean
 * @default false
 *
 * @param 水中歩行画像変更
 * @desc 水中にいる時に自動で 「元ファイル名_swim」の画像に変更
 * 例：actor.png→ actor_swim.png　※フォロワーにも有効
 * @type boolean
 * @default false
 *
 * @param ------- 選択肢の文字列 設定
 * @desc
 *
 * @param 「水の中に入る」選択肢の文字列
 * @desc 「水の中に入る」選択肢の文字列
 * @default 　水の中に入る
 *
 * @param 「水の中から出る」選択肢の文字列
 * @desc 「水の中から出る」選択肢の文字列
 * @default 　水の中から出る
 *
 * @param 「潜る」選択肢の文字列
 * @desc 「潜る」選択肢の文字列
 * @default 　潜る
 *
 * @param 「浮上する」選択肢の文字列
 * @desc 「浮上する」選択肢の文字列
 * @default 　浮上する
 *
 * @param 「何もしない」選択肢の文字列
 * @desc 「何もしない」選択肢の文字列
 * @default 　何もしない
 *
 * @param ------- SE 設定
 * @desc
 *
 * @param 水面に入るSE
 * @desc 水の中に入るSE (.ogg, .m4a ←不要)
 * 「,」で区切ってピッチも指定可能
 * @default Dive
 *
 * @param 水面から出るSE
 * @desc 水面から出る入るSE (.ogg, .m4a ←不要)
 * 「,」で区切ってピッチも指定可能
 * @default Water1
 *
 * @param 潜る/浮上するSE
 * @desc 潜る/浮上するSE (.ogg, .m4a ←不要)
 * 「,」で区切ってピッチも指定可能
 * @default Water2,75
 *
 * @param ------- リージョンID 設定
 * @desc
 *
 * @param 潜る/浮上するリージョンID 1
 * @desc 潜る/浮上することを触発するリージョンID 1 (0 = 不使用)
 * @type number
 * @min 0
 * @max 255
 * @default 21
 *
 * @param 潜る/浮上するリージョンID 2
 * @desc 潜る/浮上することを触発するリージョンID 2 (0 = 不使用)
 * @type number
 * @min 0
 * @max 255
 * @default 22
 *
 * @param 潜る/浮上するリージョンID 3
 * @desc 潜る/浮上することを触発するリージョンID 3 (0 = 不使用)
 * @type number
 * @min 0
 * @max 255
 * @default 23
 *
 * @param 潜る/浮上するリージョンID 4
 * @desc 潜る/浮上することを触発するリージョンID 4 (0 = 不使用)
 * @type number
 * @min 0
 * @max 255
 * @default 0
 *
 * @param 潜る/浮上するリージョンID 5
 * @desc 潜る/浮上することを触発するリージョンID 5 (0 = 不使用)
 * @type number
 * @min 0
 * @max 255
 * @default 0
 *
 * @param 潜る/浮上するリージョンID 6
 * @desc 潜る/浮上することを触発するリージョンID 6 (0 = 不使用)
 * @type number
 * @min 0
 * @max 255
 * @default 0
 *
 * @param 潜る/浮上するリージョンID 7
 * @desc 潜る/浮上することを触発するリージョンID 7 (0 = 不使用)
 * @type number
 * @min 0
 * @max 255
 * @default 0
 *
 * @param 潜る/浮上するリージョンID 8
 * @desc 潜る/浮上することを触発するリージョンID 8 (0 = 不使用)
 * @type number
 * @min 0
 * @max 255
 * @default 0
 *
 * @param 潜る/浮上するリージョンID 9
 * @desc 潜る/浮上することを触発するリージョンID 9 (0 = 不使用)
 * @type number
 * @min 0
 * @max 255
 * @default 0
 *
 * @param ------- 詳細設定
 * @desc
 *
 * @param 水面強制通行リージョンID
 * @desc カスタマイズ用、強制通行リージョンID (0 = 不使用)
 * 「,」区切りで複数入力可能
 * @default 0
 *
 * @param 水面下部分の透明度
 * @desc 水上にいる時、下半身の透明度
 * @type number
 * @min 0
 * @max 255
 * @default 96
 *
 * @param 水面下部分の高さ
 * @desc 水面にいる時、半透明になる部分の高さ
 * @type number
 * @min 0
 * @default 20
 *
 *
 * @help
 *
 * Swimming&Diving.js 遊泳＆ダイビング システム
 *
 * 遊泳の通行可タイルは基本的に乗り物の船と同じですが、
 * マップ設計の自由度を増やすために、強制通行リージョンを敷くと
 * 無理矢理通れます。
 * ただし、イベントの衝突判定は行われています。
 *
 *
 * 潜る/浮上の転送先の指定方法：
 * 　マップのメモに
 * 　<Dive"リージョンID":"マップID","マップX","マップY"(,"向き")>
 * 　<Surface"リージョンID":"マップID","マップX","マップY"(,"向き")>
 * 　お置く。
 * 　　　例：
 * 　　　<Dive23:16,34,25>
 *         - リージョン23で決定キーを押すと、ダイビングで マップ16の(34,25)に転送する
 * 　　　<Surface21:5,15,23,2>
 *         - リージョン21で決定キーを押すと、浮上で マップ5の(15,23)に転送する、向きは下
 *
 *
 * 水上イベント
 * 　イベントの移動範囲を水上に制限する（陸上に上がれない）
 *  イベントのメモに<Swimming>を置く
 * 　　　例：
 * 　　　　<Swimming>
 *
 *
 *
 * プラグインコマンド:
 * 　testSwim
 * 　　このコマンドを実行すると、水の中に入れるか/水から出れるかの判定を行い、
 * 　　できる場合はその行動を実行します。
 * 　　　例：testSwim
 *
 * 　testDive
 * 　　このコマンドを実行すると、この位置で潜れるか/浮上できるかの判定を行い、
 * 　　できる場合はその行動を実行します。
 * 　　　例：testDive
 *
 * 　testSwimDive
 * 　　上述の両者を同時に判定し、実行可能の行動が片方だけの場合、その片方
 * 　　の行動を実行します。
 * 　　両方実行可能の場合は選択肢を出します。
 * 　　　例：testSwimDive
 *
 * 　askSwimDive
 * 　　上のコマンドとほぼ同じですが、行動する前に必ず選択肢を出します。
 * 　　　例：askSwimDive
 *
 * 　forceWaterLayer [数字]
 * 　　水の深度を強制設定します。
 * 　　water Layer：地面は０，水面は１、潜る度に１増えます
 * 　　テレポートなどの時に使用してください。
 * 　　　例：forceWaterLayer 0
 *
 * -----------------
 * オススメ併用プラグイン：KMS_WaterMapEffect　（水中のエフェクト）
 *
 */

var Imported = Imported || {};
Imported.TKM_Swimming = true;
var $TKMvar = $TKMvar || {};
$TKMvar.swimming = {};

(function () {

    var pluginName = 'Swimming&Diving';
    var getParam = function (paramNames) {
        if (!Array.isArray(paramNames)) paramNames = [paramNames];
        for (var i = 0; i < paramNames.length; i++) {
            var name = PluginManager.parameters(pluginName)[paramNames[i]];
            if (name) return name;
        }
        return null;
    };

    $TKMvar.swimming.diveRegionID = [];
    // PARAMETER
    var parameters = PluginManager.parameters(pluginName);
    var temp = 0;
    for (var i = 1; i <= 9; i++) {
        temp = Number(getParam(['diving/surface Region ' + i, '潜る/浮上するリージョンID ' + i])) || 0;
        if (temp !== 0) $TKMvar.swimming.diveRegionID.push(temp);
    }

    temp = getParam(['水面に入るSE']); temp = temp.split(',');
    $TKMvar.swimming.inPoolSE = {};
    $TKMvar.swimming.inPoolSE.pitch = (temp.length === 1 ? 100 : Number(temp.pop())).clamp(50, 150);
    $TKMvar.swimming.inPoolSE.se = temp.join('');

    temp = getParam(['水面から出るSE']); temp = temp.split(',');
    $TKMvar.swimming.outPoolSE = {};
    $TKMvar.swimming.outPoolSE.pitch = temp.length === 1 ? 100 : Number(temp.pop());
    $TKMvar.swimming.outPoolSE.se = temp.join('');

    temp = getParam(['潜る/浮上するSE']); temp = temp.split(',');
    $TKMvar.swimming.diveSE = {};
    $TKMvar.swimming.diveSE.pitch = temp.length === 1 ? 100 : Number(temp.pop());
    $TKMvar.swimming.diveSE.se = temp.join('');

    $TKMvar.swimming.charString = {};
    $TKMvar.swimming.charString.inWater = getParam(['「水の中に入る」選択肢の文字列']);
    $TKMvar.swimming.charString.outWater = getParam(['「水の中から出る」選択肢の文字列']);
    $TKMvar.swimming.charString.dive = getParam(['「潜る」選択肢の文字列']);
    $TKMvar.swimming.charString.surface = getParam(['「浮上する」選択肢の文字列']);
    $TKMvar.swimming.charString.nothing = getParam(['「何もしない」選択肢の文字列']);

    $TKMvar.swimming.forceThroughID = new Set();
    var temp = getParam(['水面強制通行リージョンID']).split(',');
    for (var i = 0; i < temp.length; i++) {
        var num = Number(temp[i]);
        if (num) $TKMvar.swimming.forceThroughID.add(num);
    }

    $TKMvar.swimming.autoAsk = getParam(['選択肢自動表示']);

    var doAutoAsk = function (ask) {
        if (ask === "true") return true;
        if (ask === "false") return false;
        return $gameSwitches.value(Number(ask) || 1);
    };

    $TKMvar.swimming.slowMove = Number(getParam(['水中減速'])) || 0;

    $TKMvar.swimming.autoImgOnWater = getParam(['水面歩行画像変更']) === "true" ? true : false;
    $TKMvar.swimming.autoImgInWater = getParam(['水中歩行画像変更']) === "true" ? true : false;

    temp = Number(getParam(['水面下部分の透明度']));
    $TKMvar.swimming.lowerBodyOpacity = isNaN(temp) ? 32 : temp;

    temp = Number(getParam(['水面下部分の高さ']));
    $TKMvar.swimming.lowerBodyHeight = isNaN(temp) ? 20 : temp;

    // PLUGIN COMMAND
    var _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
    Game_Interpreter.prototype.pluginCommand = function (command, args) {
        _Game_Interpreter_pluginCommand.call(this, command, args);

        if (command.toUpperCase() === 'TESTSWIM') {
            $gamePlayer.testSwim();
        }
        else if (command.toUpperCase() === 'TESTDIVE') {
            $gamePlayer.testDive();
        }
        else if (command.toUpperCase() === 'TESTSWIMDIVE') {

            var pool = false, dive = false;

            if (!$gamePlayer.isSwimming() || $gamePlayer._waterLayer === 0) { // 水の中に入る？
                if (!!$gamePlayer.isJumpIntoWaterOk()) {
                    pool = true;
                }
            }
            else if ($gamePlayer._waterLayer === 1) {
                if (!!$gamePlayer.isGetupFromWaterOk()) { // 水の中から出る？
                    pool = true;
                }
            }

            var divingInfo = $gamePlayer.isGetDivingInfoOk();
            if (!!divingInfo) { // 潜る/浮上する？
                dive = true;
            }

            if (pool && dive) $gameMap.askSwimDive();
            else if (pool) $gamePlayer.testSwim();
            else if (dive) $gamePlayer.justDiveTo(divingInfo);

        }
        else if (command.toUpperCase() === 'ASKSWIMDIVE') {
            $gameMap.askSwimDive();
        }
        else if (command.toUpperCase() === 'FORCEWATERLAYER') {
            var waterLayer = Number(args[0]);
            if (!isNaN(waterLayer) && waterLayer >= 0) {
                $gamePlayer._waterLayer = waterLayer;
                if (waterLayer === 0) $gamePlayer._isSwimming = false;
                else $gamePlayer._isSwimming = true;
                $gamePlayer.refreshBushDepth();
            }
        }
    };

    // 便利な機能
    var _Game_CharacterBase_initMembers = Game_CharacterBase.prototype.initMembers;
    Game_CharacterBase.prototype.initMembers = function () {
        _Game_CharacterBase_initMembers.apply(this, arguments);
        this._fadingAdd = 0;
    };

    Game_CharacterBase.prototype.fadeOut = function (fadeSpeed) {
        this._fadingAdd = -fadeSpeed;
    };

    Game_CharacterBase.prototype.fadeIn = function (fadeSpeed) {
        this._fadingAdd = fadeSpeed;
    };

    var _Game_CharacterBase_update = Game_CharacterBase.prototype.update;
    Game_CharacterBase.prototype.update = function () {
        _Game_CharacterBase_update.apply(this, arguments);
        this.updateFade();
    };

    Game_CharacterBase.prototype.updateFade = function () {
        this._opacity = (this._opacity + this._fadingAdd).clamp(0, 255);
        if (this._opacity === 0 || this._opacity === 255) this._fadingAdd = 0;
    };

    Game_CharacterBase.prototype.isFading = function () {
        return (this._fadingAdd === 0);
    };

    // キャラが水中にいるときの表現設定

    var _Game_Character_initMembers = Game_Character.prototype.initMembers;
    Game_Character.prototype.initMembers = function () {
        _Game_Character_initMembers.apply(this, arguments);
        this._isSwimming = false;
        this._waterLayer = 0;
    };

    Game_Character.prototype.isSwimming = function () {
        return this._isSwimming;
    };

    Game_Character.prototype.refreshBushDepth = function () {
        Game_CharacterBase.prototype.refreshBushDepth.apply(this, arguments);
        if (!!this.isSwimming() && this._waterLayer === 1) {
            this._bushDepth = $TKMvar.swimming.lowerBodyHeight;
        }
    };

    Game_Character.prototype.isMapPassable = function (x, y, d) {
        var result = Game_CharacterBase.prototype.isMapPassable.apply(this, arguments);
        if (!!this.isSwimming() && this._waterLayer === 1) {
            var x2 = $gameMap.roundXWithDirection(x, d);
            var y2 = $gameMap.roundYWithDirection(y, d);
            var forceThroughOK = $TKMvar.swimming.forceThroughID.has($gameMap.regionId(x2, y2)) && (!this.isCollidedWithCharacters(x2, y2));
            return $gameMap.isBoatPassable(x2, y2) || forceThroughOK;
        }
        return result;
    };

    var _Game_Event_initialize = Game_Event.prototype.initialize;
    Game_Event.prototype.initialize = function () {
        _Game_Event_initialize.apply(this, arguments);
        if (this._mapId === $gameMap.mapId()) {
            if (!!$dataMap.events[this._eventId].meta["Swimming"]) {
                this._isSwimming = true;
                this._waterLayer = 1;
                this.refreshBushDepth();
            }
        }
    }

    // 水の抵抗力
    Game_Character.prototype.realMoveSpeed = function () {
        var result = Game_CharacterBase.prototype.realMoveSpeed.apply(this, arguments);
        return result - (!!this.isSwimming() ? $TKMvar.swimming.slowMove : 0);
    };

    var _Sprite_Character_createHalfBodySprites = Sprite_Character.prototype.createHalfBodySprites;
    Sprite_Character.prototype.createHalfBodySprites = function () {
        _Sprite_Character_createHalfBodySprites.apply(this, arguments);
        if (this._character._waterLayer === 1 && !!this._lowerBody) this._lowerBody.opacity = $TKMvar.swimming.lowerBodyOpacity;
    };

    // 自動メッセージ
    var _Game_Player_triggerButtonAction = Game_Player.prototype.triggerButtonAction;
    Game_Player.prototype.triggerButtonAction = function () {
        if (_Game_Player_triggerButtonAction.apply(this, arguments)) return true;
        if (Input.isTriggered('ok') && doAutoAsk($TKMvar.swimming.autoAsk)) {
            if ($gameMap.askSwimDive()) {
                return true;
            }
        }
        return false;
    };

    var _Game_Player_triggerTouchActionD1 = Game_Player.prototype.triggerTouchActionD1;
    Game_Player.prototype.triggerTouchActionD1 = function () {
        if (_Game_Player_triggerTouchActionD1.apply(this, arguments)) return true;
        if (TouchInput.isTriggered() && doAutoAsk($TKMvar.swimming.autoAsk)) {
            if ($gameMap.askSwimDive()) {
                return true;
            }
        }
        return false;
    };

    var _Game_Player_triggerTouchActionD2 = Game_Player.prototype.triggerTouchActionD2;
    Game_Player.prototype.triggerTouchActionD2 = function () {
        if (_Game_Player_triggerTouchActionD2.apply(this, arguments)) return true;
        if (TouchInput.isTriggered() && doAutoAsk($TKMvar.swimming.autoAsk)) {
            if ($gameMap.askSwimDive()) {
                return true;
            }
        }
        return false;
    };

    // プレイヤー、フォロワー画像変更

    Game_Player.prototype.characterName = function () {
        var result = Game_CharacterBase.prototype.characterName.apply(this, arguments);
        var needChange = this.isSwimming() && (($TKMvar.swimming.autoImgOnWater && this._waterLayer === 1) || ($TKMvar.swimming.autoImgInWater && this._waterLayer > 1));
        if (needChange && result !== "") result = result + "_swim";
        return result;
    };

    Game_Follower.prototype.characterName = function () {
        var result = Game_CharacterBase.prototype.characterName.apply(this, arguments);
        var needChange = this.isSwimming() && (($TKMvar.swimming.autoImgOnWater && this._waterLayer === 1) || ($TKMvar.swimming.autoImgInWater && this._waterLayer > 1));
        if (needChange && result !== "") result = result + "_swim";
        return result;
    };

    Game_Follower.prototype.isSwimming = function () {
        return $gamePlayer.isSwimming();
    };

    var _Game_Follower_update = Game_Follower.prototype.update;
    Game_Follower.prototype.update = function () {
        _Game_Follower_update.apply(this, arguments);
        if (this._waterLayer !== $gamePlayer._waterLayer) {
            this._isSwimming = $gamePlayer.isSwimming();
            this._waterLayer = $gamePlayer._waterLayer;
            this.refreshBushDepth();
        }
    }
    // フォロワーのrealMoveSpeed は $gamPlayer.realMoveSpeed() - 0.3 - 0.3 と二重減速しちゃったので、
    // 修正
    Game_Follower.prototype.realMoveSpeed = function () {
        return this._moveSpeed;
    }

    //プレイヤーが水に飛び込む、水中に潜る、浮上する　など

    Game_Player.prototype.testSwim = function () {
        var d = this.direction();
        var jumpX = d === 6 ? 1 : d === 4 ? -1 : 0;
        var jumpY = d === 2 ? 1 : d === 8 ? -1 : 0;

        if (!this.isSwimming() || this._waterLayer === 0) {
            if (!this.isJumpIntoWaterOk()) {
                return false;
            }
            var se = $TKMvar.swimming.inPoolSE.se;
            var pitch = $TKMvar.swimming.inPoolSE.pitch;
            var list = [{ "code": 205, "indent": 0, "parameters": [-1, { "list": [{ "code": 14, "parameters": [jumpX, jumpY], "indent": null }, { "code": 44, "parameters": [{ "name": se, "volume": 90, "pitch": pitch, "pan": 0 }], "indent": null }, { "code": 45, "parameters": ["this._isSwimming = true; this._waterLayer = 1; this.refreshBushDepth();"], "indent": null }, { "code": 0 }], "repeat": false, "skippable": false, "wait": true }] }];

            if (!!$gameMap._interpreter.isRunning()) {
                var int = $gameMap._interpreter;
                while (!!int._childInterpreter) int = int._childInterpreter;
                int.setupChild(list, 0);
            }
            else {
                $gameMap._interpreter.setup(list, 0);
            }
            return true;
        }
        else if (this._waterLayer === 1) {
            if (!this.isGetupFromWaterOk()) {
                return false;
            }

            var se = $TKMvar.swimming.outPoolSE.se;
            var pitch = $TKMvar.swimming.outPoolSE.pitch;
            var list = [{ "code": 205, "indent": 0, "parameters": [-1, { "list": [{ "code": 44, "parameters": [{ "name": se, "volume": 90, "pitch": pitch, "pan": 0 }], "indent": null }, { "code": 45, "parameters": ["this._isSwimming = false; this._waterLayer = 0; this.refreshBushDepth();"], "indent": null }, { "code": 14, "parameters": [jumpX, jumpY], "indent": null }, { "code": 0 }], "repeat": false, "skippable": false, "wait": true }] }];

            if (!!$gameMap._interpreter.isRunning()) {
                var int = $gameMap._interpreter;
                while (!!int._childInterpreter) int = int._childInterpreter;
                int.setupChild(list, 0);
            }
            else {
                $gameMap._interpreter.setup(list, 0);
            }
            return true;
        }

    };

    Game_Player.prototype.testDive = function () {
        var info = this.isGetDivingInfoOk();
        if (!!info) this.justDiveTo(info);
    };

    Game_Player.prototype.justDiveTo = function (info) {

        var isSurfacing = info.isSurfacing;
        var dest = info.dest;
        if (dest.length <= 3) dest.push(0);

        var se = $TKMvar.swimming.diveSE.se;
        var pitch = $TKMvar.swimming.diveSE.pitch;

        var list = []; // diving event page
        this.diveHideFollowers(list);
        //play SE
        list.push({ "code": 250, "indent": 0, "parameters": [{ "name": se, "volume": 90, "pitch": pitch, "pan": 0 }] });
        list.push({ "code": 355, "indent": 0, "parameters": ["$gamePlayer._stopScroll = true;"] });
        // diving Effect
        if (!isSurfacing && this._waterLayer !== 1) list.push({ "code": 355, "indent": 0, "parameters": ["$gamePlayer._y += 2.5; $gamePlayer.resetStopCount(); $gamePlayer.fadeOut(10);"] });
        else if (isSurfacing) list.push({ "code": 355, "indent": 0, "parameters": ["$gamePlayer._y -= 2.5; $gamePlayer.resetStopCount(); $gamePlayer.fadeOut(10);"] });

        list.push({ "code": 221, "indent": 0, "parameters": [] }); // Screen fade Out
        list.push({ "code": 355, "indent": 0, "parameters": ["$gamePlayer._opacity = 0;"] });
        list.push({ "code": 201, "indent": 0, "parameters": [0, dest[0], dest[1], dest[2], dest[3], 0] }); // trasfer
        list.push({ "code": 230, "indent": 0, "parameters": [15] }); // wait
        if (isSurfacing && this._waterLayer === 2) {
            var sePlayed2 = true;
            list.push({ "code": 355, "indent": 0, "parameters": ["$gamePlayer._opacity = 255; $gamePlayer._waterLayer -= 1; $gamePlayer.refreshBushDepth(); $gamePlayer._stopScroll = false;"] }); // special up to water Surface
            list.push({ "code": 250, "indent": 0, "parameters": [{ "name": se, "volume": 90, "pitch": pitch, "pan": 0 }] }); // play SE again
            this.diveShowFollowers(list);
        }
        list.push({ "code": 222, "indent": 0, "parameters": [] }); // Screen fade In

        if (!sePlayed2) list.push({ "code": 250, "indent": 0, "parameters": [{ "name": se, "volume": 90, "pitch": pitch, "pan": 0 }] }); // play SE again

        if (!isSurfacing) {

            list.push({ "code": 205, "indent": 0, "parameters": [-1, { "list": [{ "code": 45, "parameters": ["this.fadeIn(6); this._realY -= 2; this.resetStopCount(); this._waterLayer += 1; this.refreshBushDepth();"], "indent": null }, { "code": 45, "parameters": ["this._stopScroll = false"] }, { "code": 0 }], "repeat": false, "skippable": false, "wait": true }] });
        }
        else if (isSurfacing && this._waterLayer !== 2) {
            list.push({ "code": 205, "indent": 0, "parameters": [-1, { "list": [{ "code": 45, "parameters": ["this.fadeIn(6); this._realY += 2; this.resetStopCount(); this._waterLayer -= 1; this.refreshBushDepth();"], "indent": null }, { "code": 45, "parameters": ["this._stopScroll = false"] }, { "code": 0 }], "repeat": false, "skippable": false, "wait": true }] });
        }
        this.diveShowFollowers(list);

        // run
        if (!!$gameMap._interpreter.isRunning()) {
            var int = $gameMap._interpreter;
            while (!!int._childInterpreter) int = int._childInterpreter;
            int.setupChild(list, 0);
        }
        else {
            $gameMap._interpreter.setup(list, 0);
        }
    };

    Game_Player.prototype.isGetDivingInfoOk = function () {
        // check if is swimming
        if (!this.isSwimming() || this._waterLayer <= 0) return false;

        // check if region setted
        var x = this.x;
        var y = this.y;
        var Rid = $gameMap.regionId(x, y);

        var match = 0;
        for (var i = 0; i < $TKMvar.swimming.diveRegionID.length; i++) {
            if (Rid === $TKMvar.swimming.diveRegionID[i]) { match = Rid; break; }
        }
        if (!match) return false;

        // check if tag set
        if (!!$dataMap && (!!$dataMap.meta["Dive" + match] || !!$dataMap.meta["Surface" + match])) {
            var isSurfacing = false;
            var dest;
            if (!!$dataMap.meta["Surface" + match]) {
                isSurfacing = true;
                dest = $dataMap.meta["Surface" + match];
            }
            else dest = $dataMap.meta["Dive" + match];

            if (typeof (dest) === "boolean") return false;

            // can't surface at the surface of water
            if (isSurfacing && this._waterLayer === 1) return false;

            dest = dest.split(',');
            for (var i = 0; i < dest.length; i++) dest[i] = Number(dest[i]) || 0;

            var returnObject = { "isSurfacing": isSurfacing, "dest": dest };

            return returnObject;

        }
        else return false;
    };

    Game_Player.prototype.isJumpIntoWaterOk = function () {
        var x = this.x;
        var y = this.y;
        var d = this.direction();

        var x2 = $gameMap.roundXWithDirection(x, d);
        var y2 = $gameMap.roundYWithDirection(y, d);
        var forceThroughOK = $TKMvar.swimming.forceThroughID.has($gameMap.regionId(x2, y2));

        if (!$gameMap.isValid(x2, y2)) {
            return false;
        }
        if (!$gameMap.isBoatPassable(x2, y2) && !forceThroughOK) {
            return false;
        }
        if (this.isCollidedWithCharacters(x2, y2)) {
            return false;
        }
        return true;
    };

    Game_Player.prototype.isGetupFromWaterOk = function () {
        var x = this.x;
        var y = this.y;
        var d = this.direction();

        var x2 = $gameMap.roundXWithDirection(x, d);
        var y2 = $gameMap.roundYWithDirection(y, d);
        var forceThroughOK = $TKMvar.swimming.forceThroughID.has($gameMap.regionId(x2, y2));

        if (!$gameMap.isValid(x2, y2)) {
            return false;
        }
        if (!$gameMap.isPassable(x2, y2, this.reverseDir(d)) || forceThroughOK) {
            return false;
        }
        if (this.isCollidedWithCharacters(x2, y2)) {
            return false;
        }

        return true;
    };

    Game_Map.prototype.askSwimDive = function () {

        var commandArray = [];
        var pool = false;
        var dive = false;

        if (!$gamePlayer.isSwimming() || $gamePlayer._waterLayer === 0) { // 水の中に入る？
            if (!!$gamePlayer.isJumpIntoWaterOk()) {
                commandArray.push($TKMvar.swimming.charString.inWater);
                pool = true;
            }
        }
        else if ($gamePlayer._waterLayer === 1) {
            if (!!$gamePlayer.isGetupFromWaterOk()) { // 水の中から出る？
                commandArray.push($TKMvar.swimming.charString.outWater);
                pool = true;
            }
        }

        var divingInfo = $gamePlayer.isGetDivingInfoOk();
        if (!!divingInfo) { // 潜る/浮上するする？
            dive = true;
            if (divingInfo.isSurfacing) commandArray.push($TKMvar.swimming.charString.surface);
            else commandArray.push($TKMvar.swimming.charString.dive);
        }
        if (commandArray.length === 0) return false;

        commandArray.push($TKMvar.swimming.charString.nothing);
        var length = commandArray.length;
        var list = [];
        list.push({ "code": 102, "indent": 0, "parameters": [commandArray, length - 1, 0, 1, 0] });

        list.push({ "code": 402, "indent": 0, "parameters": [0, commandArray[0]] });
        list.push({ "code": 230, "indent": 1, "parameters": [15] });

        if (pool) list.push({ "code": 355, "indent": 1, "parameters": ["$gamePlayer.testSwim();"] });
        else list.push({ "code": 355, "indent": 1, "parameters": ["$gamePlayer.justDiveTo(" + JSON.stringify(divingInfo) + ");"] });

        list.push({ "code": 0, "indent": 1, "parameters": [] });
        list.push({ "code": 402, "indent": 0, "parameters": [1, commandArray[1]] });
        if (length === 3) {
            list.push({ "code": 230, "indent": 1, "parameters": [15] });
            list.push({ "code": 355, "indent": 1, "parameters": ["$gamePlayer.justDiveTo(" + JSON.stringify(divingInfo) + ");"] });
            list.push({ "code": 0, "indent": 1, "parameters": [] });
            list.push({ "code": 402, "indent": 0, "parameters": [2, commandArray[2]] });
        }
        list.push({ "code": 0, "indent": 1, "parameters": [] });
        list.push({ "code": 404, "indent": 0, "parameters": [] });

        // run
        if (!!this._interpreter.isRunning()) {
            var int = this._interpreter;
            while (!!int._childInterpreter) int = int._childInterpreter;
            int.setupChild(list, 0);
        }
        else {
            this._interpreter.setup(list, 0);
        }
        return true;
    };

    Game_Player.prototype.diveHideFollowers = function (list) {
        if (this._followers._visible === true) {
            var curIndent = 0;
            if (list.length > 0) curIndent = list[list.length - 1].indent;
            list.push({ "code": 217, "indent": curIndent, "parameters": [] });
            list.push({ "code": 216, "indent": curIndent, "parameters": [1] });
            $gameTemp._divingHidedFollowers = true;
        }
    }

    Game_Player.prototype.diveShowFollowers = function (list) {
        if (!!$gameTemp._divingHidedFollowers) {
            var curIndent = list[list.length - 1].indent;
            list.push({ "code": 216, "indent": curIndent, "parameters": [0] });
            $gameTemp._divingHidedFollowers = undefined;
        }
    }

    var _Game_Player_updateScroll = Game_Player.prototype.updateScroll;
    Game_Player.prototype.updateScroll = function (lastScrolledX, lastScrolledY) {
        if (!!this._stopScroll) return;
        _Game_Player_updateScroll.apply(this, arguments);
    };

})();