code:
//=============================================================================
// MPP_ActiveTimeBattle.js
//=============================================================================
// Copyright (c) 2017 Mokusei Penguin
// Released under the MIT license
// http://opensource.org/licenses/mit-license.php
//=============================================================================

/*:
 * @plugindesc 【ver.1.5】戦闘システムをアクティブタイムバトルに変更します。
 * @author 木星ペンギン
 *
 * @help ●パーティコマンド
 *  アクターコマンド選択中か、誰もコマンド入力を行っていない状態で
 *  キャンセルキーを押すとパーティコマンドを開くことができます。
 *
 *  パーティコマンドを開いている間は、どの戦闘モードでも時間が止まります。
 *  一時停止の代わりです。
 *
 * ●バトルイベントの実行
 *  イベント実行中にも時間は止まります。
 *
 * ●戦闘モード（0:アクティブ, 1:ウェイト, 2:ストップ）
 * 　アクティブ：常に時間が流れます。
 * 　ウェイト　：スキルやアイテム、対象選択中は時間が止まります。
 * 　　　　　　　アクターコマンド入力中は時間が流れます。
 * 　ストップ　：コマンド入力中は常に時間が止まります。
 * 　　　　　　　アクターコマンド入力中に加速ボタンを押すと時間が流れます。
 *  ※どのモードでもパーティコマンド選択中、イベント実行中は時間が止まります。
 *
 * ●ATゲージ
 *  ATゲージの最大値は
 *   1.パーティメンバーの敏捷性の平均値（敵は含まない）
 *   2.オプションによるプレイヤーの設定
 *   3.プラグインコマンドで設定した基準値
 *  によって決定されます。
 *
 *  ATゲージの増加量は
 *   キャラクターの敏捷性 + 増加値
 *  です。
 *  プラグインコマンドで設定できる[増加値]が大きいほど、
 *  敏捷性の影響が小さくなります。
 *
 * ●加速ボタン
 *  ゲームパッドではXボタン、キーボードではShift、
 *  マウスではステータスウィンドウより上をクリックし続けることで加速します。
 *  ただし、メッセージウィンドウが表示されている場合は加速しません。
 *
 * ●コマンド入力を行うアクターの切り替え
 *  ゲームパッドではLB/RBボタン、キーボードではQ、Page up/W、Page down、
 *  マウスではステータスウィンドウを左クリックすることで
 *  クリックした対象に切り替えることができます。
 *  （正確には左クリックを離した際に切り替わります）
 *
 * ●ステータスウィンドウのスクロール
 *  マウスで左クリックしたままウィンドウの上下にマウスを動かすと
 *  スクロールさせることができます。
 *  パーティメンバーがステータスウィンドウに収まらない場合の処置です。
 *
 * ●逃走
 *  戦闘可能なキャラ全員が逃走に必要なATをためると逃走判定を行います。
 *  逃走に失敗しても逃走状態は解除されません。
 *  パーティコマンドで戦うを選択すると解除されます。
 *
 *  [逃走状態で逃走モーションを行うかどうか]でtrueを設定した場合、
 *  逃走状態にある間アクターは逃走モーションを行います。
 *  デフォルトでは後ろ向きに走るモーションがないので注意してください。
 *
 * ●スキルの詠唱時間
 *  アイテムやスキルの速度補正をマイナスにすることで、詠唱時間が発生します。
 *  速度補正を-1するごとに約0.5秒の詠唱時間となります。
 *  詠唱が終わった時点で、行動順リストに入ります。
 *
 *  詠唱時間はオプションの戦闘速度の設定によって上下します。
 *  [戦闘速度の基準値]を変えても変化しません。
 *
 * ●複数回行動
 *  特徴の行動回数追加によって２回以上の行動が可能になった際の動作は保証しません。
 *  １回行動になるようにしてください。
 *
 * ================================
 * 制作 : 木星ペンギン
 * URL : http://woodpenguin.blog.fc2.com/
 *
 * @param === Option ===
 *
 * @param ATB Mode Default
 * @desc 戦闘モードのデフォルト値
 * (0:アクティブ, 1:ウェイト, 2:ストップ)
 * @default 1
 *
 * @param ATB Mode Name
 * @desc オプションで表示する戦闘モードの項目名
 * 空の場合オプションには追加されません
 * @default 戦闘モード
 *
 * @param ATB Mode Status
 * @desc オプションで表示する戦闘モードのステータス名
 * （カンマで区切ってください）
 * @default アクティブ,ウェイト
 *
 * @param ATB Speed Default
 * @desc 戦闘速度のデフォルト値(0～4)
 * @default 2
 *
 * @param ATB Speed Name
 * @desc オプションで表示する戦闘速度の項目名
 * 空の場合オプションには追加されません
 * @default 戦闘速度
 *
 * @param ATB Speed Status
 * @desc オプションで表示する戦闘速度のステータス名
 * （カンマで区切ってください）
 * @default 1,2,3,4,5
 *
 * @param === Battle ===
 *
 * @param ATB Speed Base
 * @desc 戦闘速度の基準値
 * ゲーム内での変更はできない制作者側の設定
 * @default 6
 *
 * @param AT Increment
 * @desc ATゲージの増加値
 * @default 10
 *
 * @param Reset AT Die?
 * @desc 戦闘不能時にATゲージをリセットするかどうか？
 * @default true
 *
 * @param Need Escape At
 * @desc 逃走に必要なATゲージの割合(0～100)
 * @default 100
 *
 * @param Escape AT Cost
 * @desc 逃走失敗時に消費されるATゲージの割合(0～100)
 * @default 75
 *
 * @param Escape Anime?
 * @desc 逃走状態で逃走モーションを行うかどうか (true/false)
 * @default false
 *
 * @param Input Step Forward?
 * @desc コマンド入力中に前進するかどうか (true/false)
 * @default false
 *
 * @param ATB Fast Eneble?
 * @desc 加速ボタンの有効/無効 (true/false)
 * @default true
 *
 * @param ATB Fast Rate
 * @desc 加速ボタンを押したときの加速度
 * @default 3
 *
 * @param Fast Log Eneble?
 * @desc 戦闘ログ早送りの有効/無効 (true/false)
 * 戦闘ログ早送りはツクールデフォルトの機能です
 * @default true
 *
 * @param === HelpWindow ===
 *
 * @param Help Window Pos
 * @desc ヘルプウィンドウの位置（-1:非表示, 0:上, 1:ステータスの上）
 * @default 1
 *
 * @param Help Window Row
 * @desc ヘルプウィンドウの行数
 * @default 1
 *
 * @param === StatusWindow ===
 *
 * @param Status Window Pos
 * @desc ステータスウィンドウの位置（0:左寄せ, 1:中央, 2:右寄せ）
 * @default 2
 *
 * @param === AT Gauge ===
 *
 * @param AT Gauge Name
 * @desc ATゲージ名
 *
 * @param AT Gauge Width
 * @desc ATゲージの幅
 * @default 60
 *
 * @param AT Gauge Height
 * @desc ATゲージの高さ
 * @default 12
 *
 * @param AT Charge Color1
 * @desc ATゲージ増加中の色1(RGBで指定)
 * @default 192,192,192
 *
 * @param AT Charge Color2
 * @desc ATゲージ増加中の色2(RGBで指定)
 * @default 255,255,255
 *
 * @param AT Max Color1
 * @desc ATゲージMaxの色1(RGBで指定)
 * @default 192,192,192
 *
 * @param AT Max Color2
 * @desc ATゲージMaxの色2(RGBで指定)
 * @default 255,255,192
 *
 * @param Chanting View?
 * @desc 詠唱ゲージを表示するかどうか
 * @default true
 *
 * @param AT Chanting Color1
 * @desc 詠唱ゲージの色1(RGBで指定)
 * @default 128,32,0
 *
 * @param AT Chanting Color2
 * @desc 詠唱ゲージの色2(RGBで指定)
 * @default 255,64,0
 *
 * @param Escaping Change?
 * @desc 逃走中にゲージの色を変更するかどうか
 * @default true
 *
 * @param AT Escaping Color1
 * @desc 詠唱ゲージの色1(RGBで指定)
 * @default 192,192,192
 *
 * @param AT Escaping Color2
 * @desc 詠唱ゲージの色2(RGBで指定)
 * @default 192,192,255
 *
 */

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

(function () {

    var MPPlugin = { params: PluginManager.parameters('MPP_ActiveTimeBattle') };
    MPPlugin.BtStWiA_Plugin = $plugins.some(function (plugin) {
        return (plugin.name === 'MPP_BtStWindowEX_TypeA' && plugin.status);
    });

    //=== Option ===
    MPPlugin.atbMode = Number(MPPlugin.params['ATB Mode Default'] || 0).clamp(0, 2);
    MPPlugin.atbModeName = MPPlugin.params['ATB Mode Name'];
    MPPlugin.atbModeStatus = (MPPlugin.params['ATB Mode Status'] || 'アクティブ,ウェイト').split(",");
    MPPlugin.atbSpeed = Number(MPPlugin.params['ATB Speed Default'] || 2).clamp(0, 4);
    MPPlugin.atbSpeedName = (MPPlugin.params['ATB Speed Name']);
    MPPlugin.atbSpeedStatus = (MPPlugin.params['ATB Speed Status'] || '1,2,3,4,5').split(",");

    //=== Battle ===
    MPPlugin.atbSpeedBase = Number(MPPlugin.params['ATB Speed Base'] || 6);
    MPPlugin.atIncrement = Number(MPPlugin.params['AT Increment'] || 10);
    MPPlugin.resetAtDie = !!eval(MPPlugin.params['Reset AT Die?']);
    MPPlugin.needEscapeAt = Number(MPPlugin.params['Need Escape At'] || 100).clamp(0, 100);
    MPPlugin.escapeAtCost = Number(MPPlugin.params['Escape At Cost'] || 75).clamp(0, 100);
    MPPlugin.escapeAnime = !!eval(MPPlugin.params['Escape Anime?']);
    MPPlugin.inputStepForward = !!eval(MPPlugin.params['Input Step Forward?']);
    MPPlugin.atbFastEneble = !!eval(MPPlugin.params['ATB Fast Eneble?']);
    MPPlugin.atbFastRate = Number(MPPlugin.params['ATB Fast Rate'] || 3).clamp(0, 10);
    MPPlugin.fastLogEneble = !!eval(MPPlugin.params['Fast Log Eneble?']);

    //=== HelpWindow ===
    MPPlugin.helpWindowPos = Number(MPPlugin.params['Help Window Pos'] || 1).clamp(-1, 1);
    MPPlugin.helpWindowRow = Number(MPPlugin.params['Help Window Row'] || 1).clamp(0, 2);

    //=== StatusWindow ===
    MPPlugin.stWindowPos = Number(MPPlugin.params['Status Window Pos'] || 1).clamp(0, 2);

    //=== AT Gauge ===
    MPPlugin.atGaugeName = MPPlugin.params['AT Gauge Name'] || '';
    MPPlugin.atGaugeWidth = Number(MPPlugin.params['AT Gauge Width'] || 84);
    MPPlugin.atGaugeHeight = Number(MPPlugin.params['AT Gauge Height'] || 12);
    MPPlugin.atChargeColor1 = 'rgb(%1)'.format(MPPlugin.params['AT Charge Color1'] || '192,192,192');
    MPPlugin.atChargeColor2 = 'rgb(%1)'.format(MPPlugin.params['AT Charge Color2'] || '255,255,255');
    MPPlugin.atMaxColor1 = 'rgb(%1)'.format(MPPlugin.params['AT Max Color1'] || '192,192,192');
    MPPlugin.atMaxColor2 = 'rgb(%1)'.format(MPPlugin.params['AT Max Color2'] || '255,255,192');
    MPPlugin.chantingView = !!eval(MPPlugin.params['Chanting View?']);
    MPPlugin.atChantingColor1 = 'rgb(%1)'.format(MPPlugin.params['AT Chanting Color1'] || '128,32,0');
    MPPlugin.atChantingColor2 = 'rgb(%1)'.format(MPPlugin.params['AT Chanting Color2'] || '255,64,0');
    MPPlugin.EscapingChange = !!eval(MPPlugin.params['Escaping Change?']);
    MPPlugin.atEscapingColor1 = 'rgb(%1)'.format(MPPlugin.params['AT Escaping Color1'] || '192,192,192');
    MPPlugin.atEscapingColor2 = 'rgb(%1)'.format(MPPlugin.params['AT Escaping Color2'] || '192,192,255');

    var Alias = {};

    //=============================================================================
    // Option
    //=============================================================================

    //-----------------------------------------------------------------------------
    // ConfigManager

    ConfigManager.atbMode = MPPlugin.atbMode;
    ConfigManager.atbSpeed = MPPlugin.atbSpeed;

    //521
    Alias.CoMa_mp01_makeData = ConfigManager.makeData;
    ConfigManager.makeData = function () {
        var config = Alias.CoMa_mp01_makeData.call(this);
        config.atbMode = this.atbMode;
        config.atbSpeed = this.atbSpeed;
        return config;
    };

    //532
    Alias.CoMa_applyData = ConfigManager.applyData;
    ConfigManager.applyData = function (config) {
        Alias.CoMa_applyData.call(this, config);
        this.atbMode = this.readAtbValue(config, 'atbMode', 0);
        this.atbSpeed = this.readAtbValue(config, 'atbSpeed', 2);
    };

    ConfigManager.readAtbValue = function (config, name, def) {
        return (config[name] || def);
    };

    //-----------------------------------------------------------------------------
    // Window_Options

    //36
    Alias.WiOp_addGeneralOptions = Window_Options.prototype.addGeneralOptions;
    Window_Options.prototype.addGeneralOptions = function () {
        Alias.WiOp_addGeneralOptions.call(this);
        if (MPPlugin.atbModeName) {
            this.addCommand(MPPlugin.atbModeName, 'atbMode');
        }
        if (MPPlugin.atbSpeedName) {
            this.addCommand(MPPlugin.atbSpeedName, 'atbSpeed');
        }
    };

    //62
    Alias.WiOp_statusText = Window_Options.prototype.statusText;
    Window_Options.prototype.statusText = function (index) {
        var symbol = this.commandSymbol(index);
        var value = this.getConfigValue(symbol);
        switch (symbol) {
            case 'atbMode':
                return MPPlugin.atbModeStatus[value];
            case 'atbSpeed':
                return MPPlugin.atbSpeedStatus[value];
            default:
                return Alias.WiOp_statusText.call(this, index);
        }
    };

    //84
    Alias.WiOp_processOk = Window_Options.prototype.processOk;
    Window_Options.prototype.processOk = function () {
        var index = this.index();
        var symbol = this.commandSymbol(index);
        var value = this.getConfigValue(symbol);
        switch (symbol) {
            case 'atbMode':
                value++;
                if (value >= MPPlugin.atbModeStatus.length) {
                    value = 0;
                }
                value = value.clamp(0, MPPlugin.atbModeStatus.length - 1);
                this.changeValue(symbol, value);
                break;
            case 'atbSpeed':
                value++;
                if (value >= MPPlugin.atbSpeedStatus.length) {
                    value = 0;
                }
                value = value.clamp(0, MPPlugin.atbSpeedStatus.length - 1);
                this.changeValue(symbol, value);
                break;
            default:
                Alias.WiOp_processOk.call(this);
                break;
        }
    };

    //100
    Alias.WiOp_cursorRight = Window_Options.prototype.cursorRight;
    Window_Options.prototype.cursorRight = function (wrap) {
        var index = this.index();
        var symbol = this.commandSymbol(index);
        var value = this.getConfigValue(symbol);
        switch (symbol) {
            case 'atbMode':
                value++;
                value = value.clamp(0, MPPlugin.atbModeStatus.length - 1);
                this.changeValue(symbol, value);
                break;
            case 'atbSpeed':
                value++;
                value = value.clamp(0, MPPlugin.atbSpeedStatus.length - 1);
                this.changeValue(symbol, value);
                break;
            default:
                Alias.WiOp_cursorRight.call(this, wrap);
                break;
        }
    };

    //113
    Alias.WiOp_cursorLeft = Window_Options.prototype.cursorLeft;
    Window_Options.prototype.cursorLeft = function (wrap) {
        var index = this.index();
        var symbol = this.commandSymbol(index);
        var value = this.getConfigValue(symbol);
        switch (symbol) {
            case 'atbMode':
                value--;
                value = value.clamp(0, MPPlugin.atbModeStatus.length - 1);
                this.changeValue(symbol, value);
                break;
            case 'atbSpeed':
                value--;
                value = value.clamp(0, MPPlugin.atbSpeedStatus.length - 1);
                this.changeValue(symbol, value);
                break;
            default:
                Alias.WiOp_cursorLeft.call(this, wrap);
                break;
        }
    };

    //=============================================================================
    // Battle
    //=============================================================================

    //-----------------------------------------------------------------------------
    // BattleManager

    //10
    Alias.BaMa_setup = BattleManager.setup;
    BattleManager.setup = function (troopId, canEscape, canLose) {
        Alias.BaMa_setup.call(this, troopId, canEscape, canLose);
        var rate = (7 - ConfigManager.atbSpeed) * MPPlugin.atbSpeedBase * 16;
        this._maxAt = Math.max(Math.round($gameParty.agility() * rate), 10);
        this._refreshHandler = null;
        this._waitHandler = null;
        this._escaping = false;
    };

    BattleManager.maxAt = function () {
        return this._maxAt;
    };

    BattleManager.setEscaping = function (escaping) {
        this._escaping = escaping;
        $gameParty.requestMotionRefresh();
    };

    BattleManager.isEscaping = function () {
        return this._escaping;
    };

    BattleManager.needEscapeAt = function () {
        return MPPlugin.needEscapeAt / 100;
    };

    BattleManager.escapeAtCost = function () {
        return MPPlugin.escapeAtCost / 100;
    };

    //113
    Alias.BaMa_update = BattleManager.update;
    BattleManager.update = function () {
        this.updateATB();
        this.updateCmdActor();
        Alias.BaMa_update.call(this);
    };

    BattleManager.updateATB = function () {
        if (Graphics.frameCount % 2 === 0 && !this.isAtbWait()) {
            var rate = this.isFastForward() ? MPPlugin.atbFastRate : 1;
            this.allBattleMembers().forEach(function (battler) {
                battler.updateATB(rate);
                if (battler.isMadeAction()) {
                    this.addActionBattler(battler);
                }
            }, this);
        }
    };

    BattleManager.updateCmdActor = function () {
        if (this.isEvantWait() || this.isBattleEnd()) {
            return this.clearActor();
        }
        if (!this.isAtbWait() && !this.actor()) {
            var members = $gameParty.battleMembers();
            for (var i = 0; i < members.length; i++) {
                if (members[i].isStandby()) {
                    return this.changeActor(i);
                }
            }
        } else if (this.actor() && !this.actor().isStandby()) {
            this.clearActor();
        }
    };

    BattleManager.addActionBattler = function (battler) {
        this._actionBattlers.push(battler);
        battler.setDecided(2);
    };

    BattleManager.deleteDeactiveBattler = function () {
        this._actionBattlers = this._actionBattlers.filter(function (battler) {
            if (battler.atRate() === 1) {
                return true;
            } else {
                battler.setDecided(0);
                return false;
            }
        });
        if (this.actor() && !this.actor().isStandby()) {
            this.clearActor();
        }
    };

    BattleManager.isFastForward = function () {
        if (!MPPlugin.atbFastEneble || this.isEvantWait()) {
            return false;
        } else if (Input.isPressed('shift')) {
            return true;
        } else {
            return TouchInput.y < this._statusWindow.y && TouchInput.isPressed();
        }
    };

    BattleManager.isEvantWait = function () {
        return $gameTroop.isEventRunning() || $gameMessage.isBusy();
    };

    BattleManager.isAtbWait = function () {
        return (this.isEvantWait() || this._waitHandler());
    };

    //1989
    Alias.BaMa_startBattle = BattleManager.startBattle;
    BattleManager.startBattle = function () {
        Alias.BaMa_startBattle.call(this);
        this.setupAllBattlerAt();
        this.startTurn();
    };

    BattleManager.setupAllBattlerAt = function () {
        if (this._preemptive) {
            $gameParty.members().forEach(function (member) {
                member.setAt(1);
            });
        } else if (this._surprise) {
            $gameTroop.members().forEach(function (member) {
                member.setAt(1);
            });
        } else {
            $gameParty.members().forEach(function (member) {
                member.setAt(0.8 * Math.random());
            });
            $gameTroop.members().forEach(function (member) {
                member.setAt(0.8 * Math.random());
            });
        }
        this.refreshStatus();
    };

    //253
    BattleManager.selectNextCommand = function () {
        var members = $gameParty.battleMembers();
        if (this.actor() && this.actor().isStandby()) {
            var actionState = 'undecided';
        } else {
            var actionState = 'waiting';
        }
        for (var i = 1; i < members.length; i++) {
            var n = (this._actorIndex + i).mod(members.length);
            if (members[n].isStandby() && members[n].canInput()) {
                return this.changeActor(n, actionState);
            }
        }
        return this.changeActor(-1, actionState);
    };

    //265
    BattleManager.selectPreviousCommand = function () {
        var members = $gameParty.battleMembers();
        if (this.actor() && this.actor().isStandby()) {
            var actionState = 'undecided';
        } else {
            var actionState = 'waiting';
        }
        for (var i = 1; i < members.length; i++) {
            var n = (this._actorIndex - i).mod(members.length);
            if (members[n].isStandby() && members[n].canInput()) {
                return this.changeActor(n, actionState);
            }
        }
        return this.changeActor(-1, actionState);
    };

    //276
    BattleManager.refreshStatus = function () {
        this._refreshHandler();
    };

    //280
    BattleManager.startTurn = function () {
        this._phase = 'turn';
        //this.clearActor();
        //$gameTroop.increaseTurn();
        //this.makeActionOrders();
        $gameParty.requestMotionRefresh();
        this._logWindow.startTurn();
    };

    //289
    BattleManager.updateTurn = function () {
        $gameParty.requestMotionRefresh();
        if (!this._subject) {
            this._subject = this.getNextSubject();
            if (this._subject) {
                this._subject.onTurnEnd();
                this.refreshStatus();
                this._logWindow.displayAutoAffectedStatus(this._subject);
                this._logWindow.displayRegeneration(this._subject);
                return;
            }
        }
        if (this._subject) {
            this.processTurn();
        } else {
            this.endTurn();
        }
    };

    //301
    BattleManager.processTurn = function () {
        var subject = this._subject;
        var action = subject.currentAction();
        if (action) {
            action.prepare();
            if (action.isValid()) {
                this.startAction();
            }
            subject.removeCurrentAction();
        } else {
            $gameTroop.increaseTurn();
            subject.onAllActionsEnd();
            subject.setAt(0);
            this.refreshStatus();
            this._logWindow.displayAutoAffectedStatus(subject);
            this._logWindow.displayCurrentState(subject);
            this._logWindow.displayRegeneration(subject);
            this.endTurn();
        }
    };

    //320
    BattleManager.endTurn = function () {
        this._phase = 'turnEnd';
        this._subject = null;
    };

    //332
    BattleManager.updateTurnEnd = function () {
        if (!this._escaping || !$gameParty.canEscape() || !this.processEscape()) {
            this.startTurn();
        }
    };

    //336
    Alias.BaMa_getNextSubject = BattleManager.getNextSubject;
    BattleManager.getNextSubject = function () {
        if (this.isAtbWait() || this._logWindow.isBusy()) return null;
        return Alias.BaMa_getNextSubject.call(this);
    };

    //515
    BattleManager.processEscape = function () {
        $gameParty.performEscape();
        SoundManager.playEscape();
        var success = this._preemptive ? true : (Math.random() < this._escapeRatio);
        if (success) {
            this.displayEscapeSuccessMessage();
            this._escaped = true;
            this.processAbort();
        } else {
            this.displayEscapeFailureMessage();
            this._escapeRatio += 0.1;
            //$gameParty.clearActions();
            //this.startTurn();
            $gameParty.escapeFailure();
        }
        return success;
    };

    //532
    Alias.BaMa_processAbort = BattleManager.processAbort;
    BattleManager.processAbort = function () {
        this.clearActor();
        Alias.BaMa_processAbort.call(this);
    };

    //-----------------------------------------------------------------------------
    // Game_BattlerBase

    //2849
    Alias.GaBa_initMembers = Game_BattlerBase.prototype.initMembers;
    Game_BattlerBase.prototype.initMembers = function () {
        Alias.GaBa_initMembers.call(this);
        this._at = 0;
        this._ct = 0;
        this._maxCt = 0;
        this._turnCount = 0;
        this._decided = 0;
    };

    //2307
    Alias.GaBa_die = Game_BattlerBase.prototype.die;
    Game_BattlerBase.prototype.die = function () {
        Alias.GaBa_die.call(this);
        if (MPPlugin.resetAtDie) {
            this._at = 0;
        } else {
            this._at = Math.min(this._at, BattleManager.maxAt() - 1);
        }
        this._ct = 0;
        this._maxCt = 0;
        this._decided = 0;
    };

    Game_BattlerBase.prototype.onMadeAction = function () {
        this.setDecided(1);
        var action = this.currentAction();
        if (action) {
            var item = action.item();
            if (item) {
                this._maxCt = Math.max(item.speed * (ConfigManager.atbSpeed - 7) * 3, 0);
            }
        }
    };

    Game_BattlerBase.prototype.setDecided = function (decided) {
        this._decided = decided;
    };

    Game_BattlerBase.prototype.setAt = function (rate) {
        this._at = Math.floor(BattleManager.maxAt() * rate);
        this._at = this._at.clamp(0, BattleManager.maxAt() - 1);
    };

    Game_BattlerBase.prototype.atRate = function () {
        return BattleManager.maxAt() > 0 ? this._at / BattleManager.maxAt() : 0;
    };

    Game_BattlerBase.prototype.castRate = function () {
        if (this._maxCt > 0) {
            return this._ct / this._maxCt;
        } else {
            return -1;
        }
    };

    Game_BattlerBase.prototype.isStandby = function () {
        return this._decided === 0 && this.atRate() === 1;
    };

    Game_BattlerBase.prototype.decided = function () {
        return this._decided;
    };

    Game_BattlerBase.prototype.isMadeAction = function () {
        return this._decided === 1 && this._ct === this._maxCt;
    };

    //-----------------------------------------------------------------------------
    // Game_Battler

    //144
    Alias.GaBa_clearActions = Game_Battler.prototype.clearActions;
    Game_Battler.prototype.clearActions = function () {
        Alias.GaBa_clearActions.call(this);
        this._ct = 0;
        this._maxCt = 0;
    };

    //419
    Alias.GaBa_onBattleStart = Game_Battler.prototype.onBattleStart;
    Game_Battler.prototype.onBattleStart = function () {
        Alias.GaBa_onBattleStart.call(this);
        this._ct = 0;
        this._maxCt = 0;
        this._turnCount = 0;
        this._decided = 0;
    };

    //427
    Alias.GaBa_onAllActionsEnd = Game_Battler.prototype.onAllActionsEnd;
    Game_Battler.prototype.onAllActionsEnd = function () {
        Alias.GaBa_onAllActionsEnd.call(this);
        this.regenerateAll();
        this._turnCount++;
        this._ct = 0;
        this._maxCt = 0;
        this.setDecided(0);
        this.setActionState('undecided');
    };

    //433
    Alias.GaBa_onTurnEnd = Game_Battler.prototype.onTurnEnd;
    Game_Battler.prototype.onTurnEnd = function () {
        if ($gameParty.inBattle()) {
            this.clearResult();
            //this.regenerateAll();
            this.updateStateTurns();
            this.updateBuffTurns();
            this.removeStatesAuto(2);
        } else {
            Alias.GaBa_onTurnEnd.call(this);
        }
    };

    Game_Battler.prototype.canEscape = function () {
        return this.atRate() >= BattleManager.needEscapeAt();
    };

    Game_Battler.prototype.escapeFailure = function () {
        if (this.atRate() === 1 && BattleManager.escapeAtCost() > 0) {
            this.clearActions();
        }
        this.setAt(this.atRate() - BattleManager.escapeAtCost());
    };

    Game_Battler.prototype.updateATB = function (rate) {
        if (!this.isAlive()) {
            return;
        }
        if (this._at < BattleManager.maxAt()) {
            this._at += (this.agi + MPPlugin.atIncrement) * rate;
            if (this._at >= BattleManager.maxAt()) {
                this._at = BattleManager.maxAt();
                this.makeActions();
            }
        } else if (this._ct < this._maxCt) {
            this._ct = Math.min(this._ct + rate, this._maxCt);
        }
    };

    Game_Battler.prototype.atGaugeRate = function () {
        if (MPPlugin.chantingView && this.castRate() >= 0) {
            return this.castRate();
        } else {
            return this.atRate();
        }
    };

    Game_Battler.prototype.atGaugeColor1 = function () {
        var color = this.atGaugeColorEx1();
        if (color) return color;
        return (this.atRate() < 1 ? MPPlugin.atChargeColor1 : MPPlugin.atMaxColor1);
    };

    Game_Battler.prototype.atGaugeColorEx1 = function () {
        if (MPPlugin.chantingView && this.castRate() >= 0) {
            return MPPlugin.atChantingColor1;
        } else if (MPPlugin.EscapingChange && this.isActor() &&
            BattleManager.isEscaping() && this.isAlive()) {
            return MPPlugin.atEscapingColor1;
        }
        return null;
    };

    Game_Battler.prototype.atGaugeColor2 = function () {
        var color = this.atGaugeColorEx2();
        if (color) return color;
        return (this.atRate() < 1 ? MPPlugin.atChargeColor2 : MPPlugin.atMaxColor2);
    };

    Game_Battler.prototype.atGaugeColorEx2 = function () {
        if (MPPlugin.chantingView && this.castRate() >= 0) {
            return MPPlugin.atChantingColor2;
        } else if (MPPlugin.EscapingChange && this.isActor() &&
            BattleManager.isEscaping() && this.isAlive()) {
            return MPPlugin.atEscapingColor2;
        }
        return null;
    };

    //-----------------------------------------------------------------------------
    // Game_Actor

    Game_Actor.prototype.onRestrict = function () {
        Game_Battler.prototype.onRestrict.call(this);
        if ($gameParty.inBattle() && !this._active && this.isAlive() &&
            this._at === BattleManager.maxAt()) {
            this.makeActions();
        }
    };

    //710
    Alias.GaAc_makeAutoBattleActions = Game_Actor.prototype.makeAutoBattleActions;
    Game_Actor.prototype.makeAutoBattleActions = function () {
        Alias.GaAc_makeAutoBattleActions.call(this);
        this.onMadeAction();
    };

    //725
    Alias.GaAc_makeConfusionActions = Game_Actor.prototype.makeConfusionActions;
    Game_Actor.prototype.makeConfusionActions = function () {
        Alias.GaAc_makeConfusionActions.call(this);
        this.onMadeAction();
    };

    //732
    Alias.GaAc_makeActions = Game_Actor.prototype.makeActions;
    Game_Actor.prototype.makeActions = function () {
        Alias.GaAc_makeActions.call(this);
        if (!this.canInput()) {
            this.onMadeAction();
        }
    };

    //-----------------------------------------------------------------------------
    // Game_Enemy

    //4463
    Game_Enemy.prototype.meetsTurnCondition = function (param1, param2) {
        var n = this._turnCount;
        if (param2 === 0) {
            return n === param1;
        } else {
            return n >= param1 && n % param2 === param1 % param2;
        }
    };

    //4527
    Alias.GaEn_makeActions = Game_Enemy.prototype.makeActions;
    Game_Enemy.prototype.makeActions = function () {
        Alias.GaEn_makeActions.call(this);
        this.onMadeAction();
    };

    //-----------------------------------------------------------------------------
    // Game_Unit

    Game_Unit.prototype.selectAll = function () {
        this.members().forEach(function (member) {
            member.select();
        });
    };

    Game_Unit.prototype.select = function (activeMember) {
        this.members().forEach(function (member) {
            if (member === activeMember) {
                member.select();
            } else {
                member.deselect();
            }
        });
    };

    //-----------------------------------------------------------------------------
    // Game_Party

    Game_Party.prototype.canEscape = function () {
        return this.aliveMembers().every(function (member) {
            return member.canEscape();
        });
    };

    Game_Party.prototype.escapeFailure = function () {
        this.aliveMembers().forEach(function (member) {
            member.escapeFailure();
        });
        BattleManager.deleteDeactiveBattler();
    };

    //-----------------------------------------------------------------------------
    // Window_BattleLog

    //4840
    Alias.WiBaLo_isFastForward = Window_BattleLog.prototype.isFastForward;
    Window_BattleLog.prototype.isFastForward = function () {
        return (MPPlugin.fastLogEneble && Alias.WiBaLo_isFastForward.call(this));
    };

    //-----------------------------------------------------------------------------
    // Window_BattleStatus

    Window_BattleStatus.prototype.setActorCmdWindow = function (actorCmdWindow) {
        this._actorCmdWindow = actorCmdWindow;
    };

    Window_BattleStatus.prototype.processTouch = function () {
        if (this.isOpen() && this.isActorCmdEnabled()) {
            if (TouchInput.isTriggered() && this.isTouchedInsideFrame()) {
                this._touching = true;
                this.updateInputData();
            }
            if (this._touching) {
                if (TouchInput.isPressed()) {
                    this.onTouch(false);
                } else {
                    if (this.isTouchedInsideFrame()) {
                        this.onTouch(true);
                    }
                    this._touching = false;
                }
            }
        }
    };

    Window_BattleStatus.prototype.onTouch = function (triggered) {
        var lastTopRow = this.topRow();
        var x = this.canvasToLocalX(TouchInput.x);
        var y = this.canvasToLocalY(TouchInput.y);
        var hitIndex = this.hitTest(x, y);
        if (hitIndex >= 0) {
            if (triggered && this.isTouchOkEnabled()) {
                var actor = $gameParty.battleMembers()[hitIndex];
                if (actor && actor.isStandby()) {
                    this.select(hitIndex);
                    this.processOk();
                }
            }
        } else if (this._stayCount >= 10) {
            if (y < this.padding) {
                this.scrollUp();
            } else if (y >= this.height - this.padding) {
                this.scrollDown();
            }
        }
        if (this.topRow() !== lastTopRow) {
            SoundManager.playCursor();
        }
    };

    Window_BattleStatus.prototype.isActorCmdEnabled = function () {
        return this._actorCmdWindow &&
            (this._actorCmdWindow.active || !this._actorCmdWindow.isOpen());
    };

    Window_BattleStatus.prototype.processOk = function () {
        this.updateInputData();
        this.deactivate();
        this.callOkHandler();
    };

    Window_BattleStatus.prototype.isCursorMovable = function () {
        return false;
    };

    if (!MPPlugin.BtStWiA_Plugin) {

        Window_BattleStatus.prototype.update = function () {
            Window_Selectable.prototype.update.call(this);
            this.updateAtGauge();
        };

        Window_BattleStatus.prototype.updateAtGauge = function () {
            if (this.isOpen() && this.isDrawAt() && Graphics.frameCount % 2 === 0) {
                var topIndex = this.topIndex();
                var width = MPPlugin.atGaugeWidth;
                var height = this.lineHeight();
                for (var i = 0; i < this.maxPageItems(); i++) {
                    var index = topIndex + i;
                    if (index < this.maxItems()) {
                        var rect = this.gaugeAreaRect(index);
                        var actor = $gameParty.battleMembers()[index];
                        this.contents.clearRect(rect.x + 234, rect.y, width, height);
                        this.drawActorAt(actor, rect.x + 234, rect.y, width);
                    }
                }
            }
        };

    } //if (!MPPlugin.BtStWiA_Plugin)

    Window_BattleStatus.prototype.isDrawAt = function () {
        return MPPlugin.atGaugeWidth > 0;
    };

    //5500
    Alias.WiBaSt_gaugeAreaWidth = Window_BattleStatus.prototype.gaugeAreaWidth;
    Window_BattleStatus.prototype.gaugeAreaWidth = function () {
        if (this.isDrawAt()) {
            return 234 + MPPlugin.atGaugeWidth;
        } else {
            return Alias.WiBaSt_gaugeAreaWidth.call(this);
        }
    };

    //5517
    Alias.WiBaSt_drawGaugeAreaWithTp = Window_BattleStatus.prototype.drawGaugeAreaWithTp;
    Window_BattleStatus.prototype.drawGaugeAreaWithTp = function (rect, actor) {
        if (this.isDrawAt()) {
            this.drawActorHp(actor, rect.x + 0, rect.y, 108);
            this.drawActorMpTp(actor, rect.x + 123, rect.y, 96);
            this.drawActorAt(actor, rect.x + 234, rect.y, MPPlugin.atGaugeWidth);
        } else {
            Alias.WiBaSt_drawGaugeAreaWithTp.call(this, rect, actor);
        }
    };

    //5523
    Alias.WiBaSt_drawGaugeAreaWithoutTp = Window_BattleStatus.prototype.drawGaugeAreaWithoutTp;
    Window_BattleStatus.prototype.drawGaugeAreaWithoutTp = function (rect, actor) {
        if (this.isDrawAt()) {
            this.drawActorHp(actor, rect.x + 0, rect.y, 108);
            this.drawActorMp(actor, rect.x + 123, rect.y, 96);
            this.drawActorAt(actor, rect.x + 234, rect.y, MPPlugin.atGaugeWidth);
        } else {
            Alias.WiBaSt_drawGaugeAreaWithoutTp.call(this, rect, actor);
        }
    };

    Window_BattleStatus.prototype.drawActorMpTp = function (actor, x, y, width) {
        width = (width || 186) - 10;
        this.drawGauge(x + 10, y, width, actor.tpRate(),
            this.tpGaugeColor1(), this.tpGaugeColor2());
        this.drawGauge(x, y - 8, width, actor.mpRate(),
            this.mpGaugeColor1(), this.mpGaugeColor2());
        this.contents.fontSize = 24;
        this.changeTextColor(this.systemColor());
        this.contents.drawText(TextManager.mpA, x, y + 1, 32, 24);
        this.contents.drawText(TextManager.tpA, x + 22, y + 10, 32, 24);
        this.contents.fontSize = this.standardFontSize();
    };

    Window_BattleStatus.prototype.drawActorAt = function (actor, x, y, width) {
        width = width || 60;
        var color1 = actor.atGaugeColor1();
        var color2 = actor.atGaugeColor2();
        this.drawAtGauge(x, y, width, actor.atGaugeRate(), color1, color2);
        this.changeTextColor(this.systemColor());
        this.drawText(MPPlugin.atGaugeName, x, y, 44);
    };

    Window_BattleStatus.prototype.drawAtGauge = function (x, y, width, rate, color1, color2) {
        var height = MPPlugin.atGaugeHeight;
        var fillW = Math.floor(width * rate);
        var gaugeY = y + this.lineHeight() - height - 2;
        this.contents.fillRect(x, gaugeY, width, height, this.gaugeBackColor());
        this.contents.gradientFillRect(x, gaugeY, fillW, height, color1, color2);
        this.contents.paintOpacity = 255 * (width * rate % 1);
        this.contents.fillRect(x + fillW, gaugeY, 1, height, color2);
        this.contents.paintOpacity = 255;
    };

    //-----------------------------------------------------------------------------
    // Window_BattleActor

    Window_BattleActor.prototype.processTouch = function () {
        Window_Selectable.prototype.processTouch.call(this);
    };

    Window_BattleActor.prototype.onTouch = function (triggered) {
        Window_Selectable.prototype.onTouch.call(this, triggered);
    };

    Window_BattleActor.prototype.processOk = function () {
        Window_Selectable.prototype.processOk.call(this);
    };

    Window_BattleActor.prototype.isCursorMovable = function () {
        return Window_Selectable.prototype.isCursorMovable.call(this);
    };

    Window_BattleActor.prototype.isDrawAt = function () {
        return false;
    };

    Window_BattleActor.prototype.selectForItem = function () {
        var actor = BattleManager.actor();
        var action = actor.inputtingAction();
        this.setCursorFixed(false);
        this.setCursorAll(false);
        if (action.isForUser()) {
            this.setCursorFixed(true);
            this.select(actor.index());
        } else if (action.isForAll()) {
            this.setCursorAll(true);
            this.select(0);
        } else {
            this.select(actor.index());
        }
    };

    //5558
    Alias.WiBaAc_select = Window_BattleActor.prototype.select;
    Window_BattleActor.prototype.select = function (index) {
        Alias.WiBaAc_select.call(this, index);
        if (this._cursorAll) {
            $gameParty.selectAll();
        }
    };

    //-----------------------------------------------------------------------------
    // Window_BattleEnemy

    Window_BattleEnemy.prototype.isCurrentItemEnabled = function () {
        return !!this.enemy();
    };

    //58
    Window_BattleEnemy.prototype.show = function () {
        //this.refresh();
        //this.select(0);
        Window_Selectable.prototype.show.call(this);
    };

    Window_BattleEnemy.prototype.selectForItem = function () {
        var actor = BattleManager.actor();
        var action = actor.inputtingAction();
        this.setCursorAll(false);
        if (action.isForAll()) {
            this.setCursorAll(true);
        }
        this.select(0);
    };

    //69
    Alias.WiBaEn_refresh = Window_BattleEnemy.prototype.refresh;
    Window_BattleEnemy.prototype.refresh = function () {
        Alias.WiBaEn_refresh.call(this);
        if (this.index() >= 0) {
            this.select(this._index.clamp(0, this.maxItems() - 1));
        }
    };

    //74
    Alias.WiBaEn_select = Window_BattleEnemy.prototype.select;
    Window_BattleEnemy.prototype.select = function (index) {
        Alias.WiBaEn_select.call(this, index);
        if (this._cursorAll) {
            $gameTroop.selectAll();
        }
    };

    //-----------------------------------------------------------------------------
    // Window_BattleSkill

    Window_BattleSkill.prototype.setStatusWindow = function (statusWindow) {
        this._statusWindow = statusWindow;
    };

    Window_BattleSkill.prototype.setActor = function (actor) {
        Window_SkillList.prototype.setActor.call(this, actor);
        if (this._statusWindow) {
            this._statusWindow.setActor(actor);
        }
    };

    //5662
    Alias.WiBaSk_show = Window_BattleSkill.prototype.show;
    Window_BattleSkill.prototype.show = function () {
        if (this._statusWindow) {
            this._statusWindow.show();
        }
        Alias.WiBaSk_show.call(this);
    };

    //5668
    Alias.WiBaSk_hide = Window_BattleSkill.prototype.hide;
    Window_BattleSkill.prototype.hide = function () {
        if (this._statusWindow) {
            this._statusWindow.hide();
        }
        Alias.WiBaSk_hide.call(this);
    };

    //-----------------------------------------------------------------------------
    // Window_AtbSkillStatus

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

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

    Window_AtbSkillStatus.prototype.setActor = function (actor) {
        if (this._actor !== actor) {
            this._actor = actor;
            this.refresh();
        }
    };

    Window_AtbSkillStatus.prototype.refresh = function () {
        this.contents.clear();
        if (this._actor) {
            if ($dataSystem.optDisplayTp) {
                this.drawActorMp(this._actor, 0, 0, this.contentsWidth());
                this.drawActorTp(this._actor, 0, this.lineHeight(), this.contentsWidth());
            } else {
                this.drawActorMp(this._actor, 0, 0, this.contentsWidth());
            }
        }
    };

    //-----------------------------------------------------------------------------
    // Sprite_Actor

    //777
    Alias.SpAc_updateTargetPosition = Sprite_Actor.prototype.updateTargetPosition;
    Sprite_Actor.prototype.updateTargetPosition = function () {
        if (MPPlugin.inputStepForward || !this._actor.isInputting()) {
            Alias.SpAc_updateTargetPosition.call(this);
        }
    };

    //844
    Alias.SpAc_refreshMotion = Sprite_Actor.prototype.refreshMotion;
    Sprite_Actor.prototype.refreshMotion = function () {
        var actor = this._actor;
        if (MPPlugin.escapeAnime && actor) {
            var stateMotion = actor.stateMotionIndex();
            if (actor.isActing()) {
            } else if (stateMotion === 3) {
            } else if (stateMotion === 2) {
            } else if (BattleManager.isEscaping()) {
                return this.startMotion('escape');
            }
        }
        Alias.SpAc_refreshMotion.call(this);
    };

    //-----------------------------------------------------------------------------
    // Scene_Battle

    //22
    Alias.ScBa_start = Scene_Battle.prototype.start;
    Scene_Battle.prototype.start = function () {
        BattleManager._refreshHandler = this.refreshStatus.bind(this);
        BattleManager._waitHandler = this.isAtbWait.bind(this);
        Alias.ScBa_start.call(this);
    };

    Scene_Battle.prototype.isAtbWait = function () {
        if (!this._partyCommandWindow.isClosed()) return true;
        if (ConfigManager.atbMode > 0) {
            if (this._skillWindow.visible || this._itemWindow.visible ||
                this._actorWindow.visible || this._enemyWindow.visible) {
                return true;
            }
        }
        if (ConfigManager.atbMode > 1) {
            if (!this._actorCommandWindow.isClosed() && !BattleManager.isFastForward()) {
                return true;
            }
        }
        return false;
    };

    //41
    Scene_Battle.prototype.updateBattleProcess = function () {
        //if (!this.isAnyInputWindowActive() || BattleManager.isAborting() ||
        //        BattleManager.isBattleEnd()) {
        BattleManager.update();
        this.changeInputWindow();
        //}
    };

    //58
    Scene_Battle.prototype.changeInputWindow = function () {
        if (!this._partyCommandWindow.isClosed() ||
            this._actorCommandWindow.isClosing()) {
            return;
        } else if (this._actor !== BattleManager.actor()) {
            this._actor = BattleManager.actor();
            if (this._actor) {
                this._actorCommandWindow.openness = 0;
                this.startActorCommandSelection();
            } else {
                this.endCommandSelection();
            }
        } else if (!this._actor) {
            if (Input.isTriggered('cancel') || TouchInput.isCancelled()) {
                SoundManager.playCancel();
                this.startPartyCommandSelection();
            }
        }
    };

    //104
    Scene_Battle.prototype.updateWindowPositions = function () {
        var statusX = 0;
        if (!this._partyCommandWindow.isClosed() || !this._actorCommandWindow.isClosed()) {
            statusX = this._partyCommandWindow.width;
        } else {
            statusX = this._partyCommandWindow.width * MPPlugin.stWindowPos / 2;
        }
        if (this._statusWindow.x < statusX) {
            this._statusWindow.x += 16;
            if (this._statusWindow.x > statusX) {
                this._statusWindow.x = statusX;
            }
        }
        if (this._statusWindow.x > statusX) {
            this._statusWindow.x -= 16;
            if (this._statusWindow.x < statusX) {
                this._statusWindow.x = statusX;
            }
        }
    };

    //159
    Alias.ScBa_createStatusWindow = Scene_Battle.prototype.createStatusWindow;
    Scene_Battle.prototype.createStatusWindow = function () {
        Alias.ScBa_createStatusWindow.call(this);
        this._statusWindow.setHandler('ok', this.onStatusOk.bind(this));
    };

    //172
    Alias.ScBa_createActorCommandWindow = Scene_Battle.prototype.createActorCommandWindow;
    Scene_Battle.prototype.createActorCommandWindow = function () {
        Alias.ScBa_createActorCommandWindow.call(this);
        this._actorCommandWindow.setHandler('cancel', this.startPartyCommandSelection.bind(this));
        this._actorCommandWindow.setHandler('pageup', this.selectPreviousCommand.bind(this));
        this._actorCommandWindow.setHandler('pagedown', this.selectNextCommand.bind(this));
        this._statusWindow.setActorCmdWindow(this._actorCommandWindow);
    };

    //182
    Scene_Battle.prototype.createHelpWindow = function () {
        if (MPPlugin.helpWindowPos >= 0) {
            this._helpWindow = new Window_Help(MPPlugin.helpWindowRow);
            this._helpWindow.visible = false;
            if (MPPlugin.helpWindowPos === 1) {
                this._helpWindow.y = this._statusWindow.y - this._helpWindow.height;
            }
            this.addWindow(this._helpWindow);
        }
    };

    //188
    Scene_Battle.prototype.createSkillWindow = function () {
        var wy = this._statusWindow.y;
        var ww = Graphics.boxWidth - 144
        var wh = this._statusWindow.height;
        this._skillWindow = new Window_BattleSkill(0, wy, ww, wh);
        this._skillWindow.setHelpWindow(this._helpWindow);
        this._skillWindow.setHandler('ok', this.onSkillOk.bind(this));
        this._skillWindow.setHandler('cancel', this.onSkillCancel.bind(this));
        this.addWindow(this._skillWindow);

        this._skillStatusWindow = new Window_AtbSkillStatus(ww, wy, 144, wh);
        this.addWindow(this._skillStatusWindow);
        this._skillWindow.setStatusWindow(this._skillStatusWindow);
    };

    //198
    Scene_Battle.prototype.createItemWindow = function () {
        var wy = this._statusWindow.y;
        var wh = this._statusWindow.height;
        this._itemWindow = new Window_BattleItem(0, wy, Graphics.boxWidth, wh);
        this._itemWindow.setHelpWindow(this._helpWindow);
        this._itemWindow.setHandler('ok', this.onItemOk.bind(this));
        this._itemWindow.setHandler('cancel', this.onItemCancel.bind(this));
        this.addWindow(this._itemWindow);
    };

    //208
    Alias.ScBa_createActorWindow = Scene_Battle.prototype.createActorWindow;
    Scene_Battle.prototype.createActorWindow = function () {
        Alias.ScBa_createActorWindow.call(this);
        this._actorWindow.x = Graphics.boxWidth - this._actorWindow.width;
    };

    //236
    Alias.ScBa_refreshStatus = Scene_Battle.prototype.refreshStatus;
    Scene_Battle.prototype.refreshStatus = function () {
        Alias.ScBa_refreshStatus.call(this);
        this._actorCommandWindow.refresh();
        if (this._skillWindow.visible) {
            this._skillWindow.refresh();
        }
        if (this._itemWindow.visible) {
            this._itemWindow.refresh();
        }
        if (this._actorWindow.visible) {
            this._actorWindow.refresh();
        }
        if (this._enemyWindow.visible) {
            this._enemyWindow.refresh();
        }
    };

    //240
    Alias.ScBa_startPartyCommandSelection = Scene_Battle.prototype.startPartyCommandSelection;
    Scene_Battle.prototype.startPartyCommandSelection = function () {
        Alias.ScBa_startPartyCommandSelection.call(this);
        this._actor = null;
    };

    //248
    Scene_Battle.prototype.commandFight = function () {
        BattleManager.setEscaping(false);
        this._partyCommandWindow.close();
    };

    //252
    Scene_Battle.prototype.commandEscape = function () {
        BattleManager.setEscaping(true);
        this._partyCommandWindow.close();
    };

    //257
    Alias.ScBa_startActorCommandSelection = Scene_Battle.prototype.startActorCommandSelection;
    Scene_Battle.prototype.startActorCommandSelection = function () {
        SoundManager.playOk();
        Alias.ScBa_startActorCommandSelection.call(this);
        this._skillWindow.deactivate();
        this._skillWindow.hide();
        this._itemWindow.deactivate();
        this._itemWindow.hide();
        this._actorWindow.deactivate();
        this._actorWindow.hide();
        this._enemyWindow.deactivate();
        this._enemyWindow.hide();
    };

    //276
    Alias.ScBa_commandGuard = Scene_Battle.prototype.commandGuard;
    Scene_Battle.prototype.commandGuard = function () {
        BattleManager.inputtingAction().setGuard();
        BattleManager.actor().onMadeAction();
        Alias.ScBa_commandGuard.call(this);
    };

    Scene_Battle.prototype.onStatusOk = function () {
        BattleManager.changeActor(this._statusWindow.index(), 'undecided');
        this.changeInputWindow();
    };

    //297
    Alias.ScBa_selectActorSelection = Scene_Battle.prototype.selectActorSelection;
    Scene_Battle.prototype.selectActorSelection = function () {
        Alias.ScBa_selectActorSelection.call(this);
        this._actorWindow.selectForItem();
    };

    //303
    Alias.ScBa_onActorOk = Scene_Battle.prototype.onActorOk;
    Scene_Battle.prototype.onActorOk = function () {
        BattleManager.actor().onMadeAction();
        Alias.ScBa_onActorOk.call(this);
    };

    //326
    Alias.ScBa_selectEnemySelection = Scene_Battle.prototype.selectEnemySelection;
    Scene_Battle.prototype.selectEnemySelection = function () {
        Alias.ScBa_selectEnemySelection.call(this);
        this._enemyWindow.selectForItem();
    };

    //333
    Alias.ScBa_onEnemyOk = Scene_Battle.prototype.onEnemyOk;
    Scene_Battle.prototype.onEnemyOk = function () {
        BattleManager.actor().onMadeAction();
        Alias.ScBa_onEnemyOk.call(this);
    };

    //385
    Scene_Battle.prototype.onSelectAction = function () {
        var action = BattleManager.inputtingAction();
        //this._skillWindow.hide();
        //this._itemWindow.hide();
        if (action.isForOpponent()) {
            this.selectEnemySelection();
        } else {
            this.selectActorSelection();
        }
    };

    //398
    Alias.ScBa_endCommandSelection = Scene_Battle.prototype.endCommandSelection;
    Scene_Battle.prototype.endCommandSelection = function () {
        this._actor = null;
        Alias.ScBa_endCommandSelection.call(this);
        this._skillWindow.deactivate();
        this._skillWindow.hide();
        this._itemWindow.deactivate();
        this._itemWindow.hide();
        this._actorWindow.deactivate();
        this._actorWindow.hide();
        this._enemyWindow.deactivate();
        this._enemyWindow.hide();
    };

})();


code:
//=============================================================================
// MPP_ChoiceEX.js
//=============================================================================
// Copyright (c) 2015 - 2021 Mokusei Penguin
// Released under the MIT license
// http://opensource.org/licenses/mit-license.php
//=============================================================================

/*:
 * @target MV MZ
 * @plugindesc Extend the functionality of your choices.
 * @author Mokusei Penguin
 * @url
 *
 * @help [version 4.2.0]
 * This plugin is for RPG Maker MV and MZ.
 *
 * ▼ Plugin command
 *  - In MV, the variable N is referred to by writing v [N] in the item for
 *    inputting a numerical value.
 *  - In MZ, in the item to enter a numerical value, select the text and
 *    write v [N] to refer to the variable N.
 *  - It is basically preferable to execute the plugin command before
 *    [Show Choices].
 *  - If you want to use the plug-in command while the message window is
 *    displayed, execute it before [Display text].
 *
 *  〇 MV / MZ
 *
 *  〇 ChoicePos x y row  / choicePos
 *       x   : X coordinate of choice window
 *       y   : Y coordinate of choice window
 *       row : The number of lines in the choice window. Show all if not set
 *   - Specify the position (x, y) and the number of rows of the next choice
 *     to display.
 *
 *  〇 ChoiceVariableId varId  / choiceVariableId
 *       varId : Variable number
 *   - Set the default position of the next choice to display to the value of
 *     the variable.
 *   - In addition, put the current cursor position in a variable.
 *   - The cursor position is 0 to 5 for the first option from the top,
 *     10 to 15 for the next option, and +10 for each option.
 *
 *  〇 ChoiceRect x y width height  / choiceRect
 *       x      : X coordinate
 *       y      : Y coordinate
 *       width  : width
 *       height : height
 *   - Specify the coordinates and size of the next choice to display.
 *   - For items that have not been set or for which -1 is specified,
 *     normal values will be applied.
 *
 *  〇 ChoiceInMessage  / ChoiceInMessage
 *   - The next choice to display is displayed in the message window.
 *   - This function will not work unless it is used in combination with
 *     [Display Text].
 *   - Please execute before [Display text].
 *
 * ▼ More choices
 *  - If you place the event command [Display Choices] in succession,
 *    they will be combined into one choice.
 *  - If you don't want to put them together, you can separate them as usual by
 *    inserting annotations in between.
 *  - For the "default" process, the one set other than none is applied.
 *  - For the "Cancel" process, the ones other than prohibited are applied.
 *  - In both cases, the setting of the option that follows takes precedence.
 *  - For "Background" and "Window position", the settings of the options that
 *    follow are applied.
 *
 * ▼ Setting conditions for displaying items
 *  - If you enter
 *      if(condition)
 *    in the text of the choice and the condition becomes false,
 *    the item will not be displayed.
 *  - The operation when the "Default" item is not displayed can be set in the
 *    [Disabled Index] of the plug-in parameter.
 *  - If the "Cancel" item is not displayed, the same processing as prohibition
 *    is performed.
 *  - Within the condition, you can refer to the switch with "s" and
 *    the variable with "v".
 *     Example: When set to if(s[1])
 *                => Switch No. 1 is ON for display and OFF for non-display.
 *              When set to if(!s[2])
 *                => Switch 2 is displayed when it is OFF,
 *                   and is hidden when it is ON.
 *              When set to if(v[5]>0)
 *                => Display if variable 5 is greater than 0,
 *                   hide if variable 5 is less than 0.
 *
 *     Inequalities that can be used in variables
 *       === : equal
 *       !== : Not equal
 *       <   : Smaller
 *       <=  : Less than or equal to
 *       >   : Greater
 *       >=  : Greater than or equal to
 *
 * ▼ Setting conditions for displaying items semi-transparently
 *  - Enter
 *      en(condition)
 *    in the text of the choice, and if the condition is false,
 *    the item will be displayed semi-transparently.
 *  - Items that are semi-transparent cannot be selected.
 *  - The conditions are the same as "Setting the conditions for displaying
 *    items" above.
 *  - If the "Cancel" item is semi-transparent, you cannot cancel it.
 *
 * ▼ Display help message
 *  - You can put
 *      ChoiceHelp
 *    in the [Annotation] below each choice item to indicate the following text
 *    as a help message when you hover over it.
 *  - Help messages use the same functionality as View Text, so you can use
 *    control characters. (\! And \ ^ cannot be used)
 *
 * ================================
 * Mail : wood_penguin＠yahoo.co.jp (＠ is half-width)
 * Blog : http://woodpenguin.blog.fc2.com/
 * License : MIT license
 *
 *  @command choicePos
 *      @desc Specify the position and number of lines for the next choice to display.
 *      @arg x
 *          @desc
 *          @type number
 *              @min 0
 *              @max 999999
 *          @default 0
 *      @arg y
 *          @desc
 *          @type number
 *              @min 0
 *              @max 999999
 *          @default 0
 *      @arg row
 *          @desc 0 : Show all
 *          @type number
 *              @min 0
 *              @max 999
 *          @default 0
 *
 *
 *  @command choiceVariableId
 *      @desc Set the default position of the next choice to display to the value of the variable. In addition, put the current cursor position in a variable.
 *      @arg varId
 *          @desc
 *          @type variable
 *          @default 0
 *
 *  @command choiceRect
 *      @desc Specify the coordinates and size of the next choice to display.
 *      Normal values are applied to unset items.
 *      @arg x
 *          @desc
 *          @type number
 *              @min 0
 *              @max 999999
 *          @default
 *      @arg y
 *          @desc
 *          @type number
 *              @min 0
 *              @max 999999
 *          @default
 *      @arg width
 *          @desc
 *          @type number
 *              @min 1
 *              @max 999999
 *          @default
 *      @arg height
 *          @desc
 *          @type number
 *              @min 1
 *              @max 999999
 *          @default
 *
 *  @command choiceInMessage
 *      @desc The next choice to display is displayed in the message window.
 *      It will not work unless it is used in combination with [Display text].
 *
 *
 *  @param Max Page Row
 *      @desc Maximum number of lines displayed on one page
 *      @type number
 *          @min 1
 *          @max 999
 *      @default 6
 *
 *  @param Disabled Position
 *      @desc Cursor position when the default choice is not displayed
 *      @type select
 *          @option none
 *          @option top
 *      @default none
 *
 */

/*:ja
 * @target MV MZ
 * @plugindesc 選択肢の機能を拡張します。
 * @author 木星ペンギン
 * @url
 *
 * @help [version 4.2.0]
 * このプラグインはRPGツクールMVおよびMZ用です。
 *
 * ▼ プラグインコマンド
 *  - MVでは数値を入力する項目で v[N] と記述することで変数N番を参照します。
 *  - MZでは数値を入力する項目で、テキストを選択して v[N] と記述することで
 *    変数N番を参照します。
 *  - プラグインコマンドは基本的に[選択肢の表示]の前に実行するのが好ましいです。
 *  - メッセージウィンドウを表示したままプラグインコマンドを使いたい場合、
 *    [文章の表示]の前に実行してください。
 *
 *  〇 MV / MZ
 *
 *  〇 ChoicePos x y row  / 選択肢位置設定
 *       x   : 選択肢ウィンドウのX座標
 *       y   : 選択肢ウィンドウのY座標
 *       row : 選択肢ウィンドウの行数。未設定の場合はすべて表示
 *   - 次に表示する選択肢の位置(x,y)と行数(row)指定します。
 *
 *  〇 ChoiceVariableId varId  / カーソル位置設定
 *       varId : 変数番号
 *   - 次に表示する選択肢のデフォルト位置を変数の値にします。
 *   - さらに現在のカーソル位置を変数に入れます。
 *   - カーソル位置は最初の選択肢が上から0～5、次の選択肢は10～15と、
 *     選択肢毎に+10されます。
 *
 *  〇 ChoiceRect x y width height  / 選択肢サイズ設定
 *       x      : X座標
 *       y      : Y座標
 *       width  : 幅
 *       height : 高さ
 *   - 次に表示する選択肢の座標とサイズを指定します。
 *   - 未設定もしくは-1を指定した項目は、通常の値が適用されます。
 *
 *  〇 ChoiceInMessage  / メッセージ内表示
 *   - 次に表示する選択肢をメッセージウィンドウ内に表示させます。
 *   - この機能は[文章の表示]と併用しなければ機能しません。
 *   - [文章の表示]の前に実行してください。
 *
 * ▼ 選択肢を増やす
 *  - イベントコマンド『選択肢の表示』を続けて配置すると
 *    一つの選択肢にまとめられます。
 *  - まとめたくない場合は、間に注釈などを入れることで
 *    通常通り分けることができます。
 *  - 『デフォルト』の処理は、なし以外を設定したものが適用されます。
 *  - 『キャンセル』の処理は、禁止以外を設定したものが適用されます。
 *  - どちらも後にある選択肢の設定が優先されます。
 *  - 『背景』と『ウィンドウ位置』は後にある選択肢の設定が適用されます。
 *
 * ▼ 項目が表示される条件の設定
 *  - 選択肢の文章中に
 *      if(条件)
 *    と入れ、その条件が偽になると項目が表示されなくなります。
 *  - 『デフォルト』の項目が表示されない場合の動作は、
 *    プラグインパラメータの[Disabled Index]にて設定できます。
 *  - 『キャンセル』の項目が表示されない場合、禁止と同じ処理をします。
 *  - 条件内では s でスイッチ、v で変数を参照できます。
 *     例：if(s[1]) とした場合
 *          => スイッチ１番がONで表示、OFFで非表示。
 *        if(!s[2]) とした場合
 *          => スイッチ２番がOFFで表示、ONで非表示。
 *        if(v[5]>0) とした場合
 *          => 変数５番が0より大きければ表示、0以下で非表示。
 *
 *     変数で使える不等号
 *       === : 等しい
 *       !== : 等しくない
 *       <   : より小さい
 *       <=  : より小さいまたは等しい
 *       >   : より大きい
 *       >=  : より大きいまたは等しい
 *
 * ▼ 項目を半透明で表示する条件の設定
 *  - 選択肢の文章中に
 *      en(条件)
 *    と入れ、その条件が偽になると項目が半透明で表示されます。
 *  - 半透明となった項目は選択できなくなります。
 *  - 条件は上の『項目が表示される条件の設定』と同じです。
 *  - 『キャンセル』の項目が半透明の場合、キャンセルできなくなります。
 *
 * ▼ ヘルプメッセージの表示
 *  - 各選択肢項目の下に注釈で
 *      選択肢ヘルプ
 *    と入れると、続きの文章をヘルプメッセージとしてカーソルを合わせたときに
 *    標示させることができます。
 *  - ヘルプメッセージは[文章の表示]と同じ機能を使っているため、
 *    制御文字が使用できます。(\!と\^は使用できません)
 *
 * ================================
 * Mail : wood_penguin＠yahoo.co.jp (＠は半角)
 * Blog : http://woodpenguin.blog.fc2.com/
 * License : MIT license
 *
 *  @command choicePos
 *      @text 選択肢位置設定
 *      @desc 次に表示する選択肢の位置と行数を指定します。
 *      @arg x
 *          @desc
 *          @type number
 *              @min 0
 *              @max 999999
 *          @default 0
 *      @arg y
 *          @desc
 *          @type number
 *              @min 0
 *              @max 999999
 *          @default 0
 *       @arg row
 *          @text 行数
 *          @desc 0 : 全て表示
 *          @type number
 *              @min 0
 *              @max 999
 *          @default 0
 *
 *  @command choiceVariableId
 *      @text カーソル位置設定
 *      @desc 次に表示する選択肢のデフォルト位置を変数の値にします。
 *      さらに現在のカーソル位置を変数に入れます。
 *      @arg varId
 *          @text 変数
 *          @desc
 *          @type variable
 *          @default 0
 *
 *  @command choiceRect
 *      @text 選択肢サイズ設定
 *      @desc 次に表示する選択肢の座標とサイズを指定します。
 *      未設定の項目は通常の値が適用されます。
 *      @arg x
 *          @desc
 *          @type number
 *              @min 0
 *              @max 999999
 *          @default
 *      @arg y
 *          @desc
 *          @type number
 *              @min 0
 *              @max 999999
 *          @default
 *      @arg width
 *          @text 幅
 *          @desc
 *          @type number
 *              @min 1
 *              @max 999999
 *          @default
 *      @arg height
 *          @text 高さ
 *          @desc
 *          @type number
 *              @min 1
 *              @max 999999
 *          @default
 *
 *  @command choiceInMessage
 *      @text メッセージ内表示
 *      @desc 次に表示する選択肢をメッセージウィンドウ内に表示させます。
 *      [文章の表示]と併用しなければ機能しません。
 *
 *
 *  @param Max Page Row
 *      @text 最大表示行数
 *      @desc 1ページに表示される最大行数
 *      @type number
 *          @min 1
 *          @min 999
 *      @default 6
 *
 *  @param Disabled Position
 *      @text 無効時のカーソル位置
 *      @desc [デフォルト]となる選択肢が表示されない場合のカーソル位置
 *      @type select
 *          @option なし
 *          @value none
 *          @option 先頭
 *          @value top
 *      @default none
 *
 */

(() => {
    'use strict';

    const pluginName = 'MPP_ChoiceEX';

    // Plugin Parameters
    const parameters = PluginManager.parameters(pluginName);
    const param_MaxPageRow = Number(parameters['Max Page Row']);
    const param_DisabledPosition = parameters['Disabled Position'];

    // Dealing with other plugins
    const __base = (obj, prop) => {
        if (obj.hasOwnProperty(prop)) {
            return obj[prop];
        } else {
            const proto = Object.getPrototypeOf(obj);
            return function () { return proto[prop].apply(this, arguments); };
        }
    };

    //-------------------------------------------------------------------------
    // PluginManager

    PluginManager._commands = PluginManager._commands || {};

    if (!PluginManager.registerCommand) {
        PluginManager.registerCommand = function (pluginName, commandName, func) {
            const key = pluginName + ":" + commandName;
            this._commands[key] = func;
        };
    }

    if (!PluginManager.callCommand) {
        PluginManager.callCommand = function (self, pluginName, commandName, args) {
            const key = pluginName + ":" + commandName;
            const func = this._commands[key];
            if (typeof func === "function") {
                func.bind(self)(args);
            }
        };
    }

    PluginManager.registerCommand(pluginName, 'choicePos', args => {
        const x = PluginManager.mppValue(args.x);
        const y = PluginManager.mppValue(args.y);
        const row = PluginManager.mppValue(args.row) || 99;
        $gameMessage.setChoicePos(x, y, row);
    });

    PluginManager.registerCommand(pluginName, 'choiceVariableId', args => {
        const variableId = PluginManager.mppValue(args.varId);
        $gameMessage.setChoiceVariableId(variableId);
    });

    PluginManager.registerCommand(pluginName, 'choiceRect', args => {
        const x = args.x ? PluginManager.mppValue(args.x) : -1;
        const y = args.y ? PluginManager.mppValue(args.y) : -1;
        const width = args.width ? PluginManager.mppValue(args.width) : -1;
        const height = args.height ? PluginManager.mppValue(args.height) : -1;
        $gameMessage.setChoiceRect(x, y, width, height);
    });

    PluginManager.registerCommand(pluginName, 'choiceInMessage', args => {
        $gameMessage.requestChoiceInMessage();
    });

    PluginManager.mppValue = function (value) {
        const match = /^V\[(\d+)\]$/i.exec(value);
        return match ? $gameVariables.value(+match[1]) : +value;
    };

    //-------------------------------------------------------------------------
    // Game_Message

    Object.defineProperties(Game_Message.prototype, {
        choiceX: {
            get() { return this._choiceX; },
            configurable: true
        },
        choiceY: {
            get() { return this._choiceY; },
            configurable: true
        },
        choiceWidth: {
            get() { return this._choiceWidth; },
            configurable: true
        },
        choiceHeight: {
            get() { return this._choiceHeight; },
            configurable: true
        }
    });

    const _Game_Message_clear = Game_Message.prototype.clear;
    Game_Message.prototype.clear = function () {
        _Game_Message_clear.apply(this, arguments);
        this._choiceEnables = [];
        this._choiceResults = [];
        this._helpTexts = [];
        this._choiceX = -1;
        this._choiceY = -1;
        this._choiceWidth = -1;
        this._choiceHeight = -1;
        this._choiceMaxRow = param_MaxPageRow;
        this._choiceVariableId = 0;
        this._choiceInMessage = false;
    };

    Game_Message.prototype.choiceMaxRow = function () {
        return this._choiceMaxRow;
    };

    Game_Message.prototype.setTexts = function (texts) {
        this._texts = texts;
    };

    Game_Message.prototype.setChoiceEnables = function (enables) {
        this._choiceEnables = enables;
    };

    Game_Message.prototype.choiceEnables = function () {
        return this._choiceEnables;
    };

    Game_Message.prototype.setChoiceResults = function (results) {
        this._choiceResults = results;
    };

    Game_Message.prototype.choiceResults = function () {
        return this._choiceResults;
    };

    Game_Message.prototype.setChoiceHelpTexts = function (texts) {
        this._helpTexts = texts;
    };

    Game_Message.prototype.isHelp = function () {
        return !this._choiceInMessage && this._helpTexts.length > 0;
    };

    Game_Message.prototype.helpTexts = function () {
        return this._helpTexts;
    };

    Game_Message.prototype.setChoicePos = function (x, y, row) {
        this._choiceX = x;
        this._choiceY = y;
        this._choiceWidth = -1;
        this._choiceHeight = -1;
        this._choiceMaxRow = row;
    };

    Game_Message.prototype.setChoiceRect = function (x, y, width, height) {
        this._choiceX = x;
        this._choiceY = y;
        this._choiceWidth = width;
        this._choiceHeight = height;
    };

    Game_Message.prototype.setChoiceVariableId = function (id) {
        this._choiceVariableId = id;
    };

    Game_Message.prototype.lowerChoiceHeight = function (height) {
        this._choiceY += height;
        this._choiceHeight -= height;
    };

    Game_Message.prototype.requestChoiceInMessage = function () {
        this._choiceInMessage = true;
    };

    Game_Message.prototype.choiceVariableId = function () {
        return this._choiceVariableId;
    };

    Game_Message.prototype.isChoiceInMessage = function () {
        return this._choiceInMessage;
    };

    //-----------------------------------------------------------------------------
    // Game_Interpreter

    Game_Interpreter.prototype.setupChoices = function (params) {
        const data = {
            choices: [],
            enables: [],
            results: [],
            helpTexts: [],
            cancelType: -1,
            defaultType: -1,
            positionType: 0,
            background: 0
        };
        this.addChoices(params, this._index, data, 0);
        if (data.choices.length > 0) {
            const helpTexts = this.choiceHelpTexts(data);
            const cancelType = this.choiceCancelType(data);
            const defaultType = this.choiceDefaultType(data);
            $gameMessage.setChoices(data.choices, defaultType, cancelType);
            $gameMessage.setChoiceEnables(data.enables);
            $gameMessage.setChoiceResults(data.results);
            $gameMessage.setChoiceHelpTexts(helpTexts);
            $gameMessage.setChoiceBackground(data.background);
            $gameMessage.setChoicePositionType(data.positionType);
            $gameMessage.setChoiceCallback(n => {
                this._branch[this._indent] =
                    n < 0 ? data.cancelType : data.results[n];
            });
        } else {
            this._branch[this._indent] = -1;
        }
    };

    Game_Interpreter.prototype.addChoices = function (params, index, data, d) {
        const choices = params[0].clone();
        this.checkChoiceConditions(choices, data, d);
        const cancelType = params[1] < choices.length ? params[1] : -2;
        if (cancelType !== -1) data.cancelType = cancelType + d;
        const defaultType = params[2] || 0;
        if (defaultType >= 0) data.defaultType = defaultType + d;
        data.positionType = params.length > 3 ? params[3] : 2;
        data.background = params[4] || 0;
        index = this.setupHelpText(index, data, d);
        const command = this._list[index + 1];
        if (command && command.code === 102) {
            this.addChoices(command.parameters, index + 1, data, d + 10);
        }
    };

    Game_Interpreter.prototype.checkChoiceConditions = function (choices, data, d) {
        const regIf = /\s?if\((.+?)\)/;
        const regEn = /\s?en\((.+?)\)/;
        for (const [i, text] of choices.entries()) {
            if (this.meetsChoiceConditions(text, regIf)) {
                const realText = text.replace(regIf, '').replace(regEn, '');
                data.choices.push(realText);
                data.enables.push(this.meetsChoiceConditions(text, regEn));
                data.results.push(i + d);
            }
        };
    };

    Game_Interpreter.prototype.meetsChoiceConditions = function (text, reg) {
        const match = reg.exec(text);
        return !match || this.evalChoice(match[1]);
    };

    Game_Interpreter.prototype.evalChoice = function (condition) {
        try {
            const s = $gameSwitches._data;
            const realCondition = condition.replace(/V\[(\d+)\]/gi, (_, n) =>
                $gameVariables.value(+n)
            );
            return !!eval(realCondition);
        } catch (e) {
            console.log('条件エラー \n ' + condition);
            return true;
        }
    };

    Game_Interpreter.prototype.setupHelpText = function (index, data, d) {
        for (; ;) {
            index++;
            const command = this._list[index];
            if (!command) break;
            if (command.indent === this._indent) {
                if (command.code === 402) {
                    const type = command.parameters[0] + d;
                    const helpTexts = this.checkHelpTexts(index + 1);
                    if (helpTexts) data.helpTexts[type] = helpTexts;
                } else if (command.code === 404) {
                    break;
                }
            }
        }
        return index;
    };

    Game_Interpreter.prototype.checkHelpTexts = function (index) {
        const command = this._list[index];
        if (
            command.code === 108 &&
            ['ChoiceHelp', '選択肢ヘルプ'].includes(command.parameters[0])
        ) {
            return this.getHelpTexts(index);
        }
        return null;
    };

    Game_Interpreter.prototype.getHelpTexts = function (index) {
        const result = [];
        while (this._list[index + 1].code === 408) {
            index++;
            result.push(this._list[index].parameters[0]);
        }
        return result;
    };

    Game_Interpreter.prototype.choiceHelpTexts = function (data) {
        const helpTexts = data.helpTexts;
        return helpTexts.length > 0 ? data.results.map(i => helpTexts[i]) : [];
    };

    Game_Interpreter.prototype.choiceCancelType = function (data) {
        if (data.cancelType === -1) {
            return -1;
        } else if (data.cancelType.mod(10) === 8) {
            return -2;
        } else {
            return data.results.indexOf(data.cancelType);
        }
    };

    Game_Interpreter.prototype.choiceDefaultType = function (data) {
        const vId = $gameMessage.choiceVariableId();
        const index = vId > 0 ? $gameVariables.value(vId) : data.defaultType;
        const defaultType = data.results.indexOf(index);
        if (index >= 0 && defaultType < 0 && param_DisabledPosition === 'top') {
            return 0;
        }
        return defaultType;
    };

    // overwrite
    Game_Interpreter.prototype.command403 = function () {
        if (this._branch[this._indent] !== -2) {
            this.skipBranch();
        }
        return true;
    };

    Game_Interpreter.prototype.command404 = function () {
        if (this.nextEventCode() === 102) {
            this._branch[this._indent] -= 10;
            this._index++;
        }
        return true;
    };

    const _mzCommands = {
        ChoicePos: { name: 'choicePos', keys: ['x', 'y', 'row'] },
        ChoiceVariableId: { name: 'choiceVariableId', keys: ['varId'] },
        ChoiceRect: { name: 'choiceRect', keys: ['x', 'y', 'width', 'height'] },
        ChoiceInMessage: { name: 'choiceInMessage', keys: [] }
    };
    Object.assign(_mzCommands, {
        '選択肢位置設定': _mzCommands.ChoicePos,
        'カーソル位置設定': _mzCommands.ChoiceVariableId,
        '選択肢サイズ設定': _mzCommands.ChoiceRect,
        'メッセージ内表示': _mzCommands.ChoiceInMessage
    });

    const _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
    Game_Interpreter.prototype.pluginCommand = function (command, args) {
        _Game_Interpreter_pluginCommand.apply(this, arguments);
        const mzCommand = _mzCommands[command];
        if (mzCommand) {
            const args2 = Object.assign(...mzCommand.keys.map((k, i) => ({ [k]: args[i] })));
            PluginManager.callCommand(this, pluginName, mzCommand.name, args2);
        }
    };

    //-----------------------------------------------------------------------------
    // Window_ChoiceList

    const _Window_ChoiceList_select = __base(Window_ChoiceList.prototype, 'select');
    Window_ChoiceList.prototype.select = function (index) {
        const variableId = $gameMessage.choiceVariableId();
        if (index !== this.index() && variableId > 0) {
            const results = $gameMessage.choiceResults();
            $gameVariables.setValue(variableId, results[index]);
        }
        _Window_ChoiceList_select.apply(this, arguments);
    };

    const _Window_ChoiceList_updatePlacement = Window_ChoiceList.prototype.updatePlacement;
    Window_ChoiceList.prototype.updatePlacement = function () {
        _Window_ChoiceList_updatePlacement.apply(this, arguments);
        const {
            choiceX: x,
            choiceY: y,
            choiceWidth: width,
            choiceHeight: height
        } = $gameMessage;
        if (width >= 0) this.width = width.clamp(1, Graphics.boxWidth);
        if (height >= 0) this.height = height.clamp(1, Graphics.boxHeight);
        if (x >= 0) this.x = Math.min(x, Graphics.boxWidth - this.width);
        if (y >= 0) this.y = Math.min(y, Graphics.boxHeight - this.height);
        this._isWindow = !$gameMessage.isChoiceInMessage();
    };

    // overwrite
    Window_ChoiceList.prototype.numVisibleRows = function () {
        const choices = $gameMessage.choices();
        const maxLines = $gameMessage.choiceMaxRow();
        return Math.min(choices.length, maxLines);
    };

    // overwrite
    Window_ChoiceList.prototype.makeCommandList = function () {
        const enables = $gameMessage.choiceEnables();
        for (const [i, choice] of $gameMessage.choices().entries()) {
            this.addCommand(choice, 'choice', enables[i]);
        }
    };

    const _Window_ChoiceList_drawItem = Window_ChoiceList.prototype.drawItem;
    Window_ChoiceList.prototype.drawItem = function (index) {
        this.changePaintOpacity(this.isCommandEnabled(index));
        _Window_ChoiceList_drawItem.apply(this, arguments);
    };

    const _Window_ChoiceList_callOkHandler = Window_ChoiceList.prototype.callOkHandler;
    Window_ChoiceList.prototype.callOkHandler = function () {
        _Window_ChoiceList_callOkHandler.apply(this, arguments);
        this._messageWindow.forceClear();
        this._helpIndex = null;
    };

    const _Window_ChoiceList_callCancelHandler = Window_ChoiceList.prototype.callCancelHandler;
    Window_ChoiceList.prototype.callCancelHandler = function () {
        _Window_ChoiceList_callCancelHandler.apply(this, arguments);
        this._messageWindow.forceClear();
        this._helpIndex = null;
    };

    const _Window_ChoiceList_processCancel = __base(Window_ChoiceList.prototype, 'processCancel');
    Window_ChoiceList.prototype.processCancel = function () {
        const cancelType = $gameMessage.choiceCancelType();
        if (
            cancelType >= 0 &&
            this.isCancelEnabled() &&
            !this.isCommandEnabled(cancelType)
        ) {
            this.playBuzzerSound();
            return;
        }
        _Window_ChoiceList_processCancel.apply(this, arguments);
    };

    Window_ChoiceList.prototype.callUpdateHelp = function () {
        if (
            this.active &&
            this._messageWindow &&
            $gameMessage.isHelp() &&
            this._helpIndex !== this.index()
        ) {
            this._helpIndex = this.index();
            this.updateHelp();
        }
    };

    Window_ChoiceList.prototype.updateHelp = function () {
        this._messageWindow.forceClear();
        const texts = $gameMessage.helpTexts()[this.index()];
        $gameMessage.setTexts(texts ? [...texts] : ['']);
        this._messageWindow.startMessage();
    };

    //-----------------------------------------------------------------------------
    // Window_Message

    const _Window_Message_updatePlacement = Window_Message.prototype.updatePlacement;
    Window_Message.prototype.updatePlacement = function () {
        _Window_Message_updatePlacement.apply(this, arguments);
        this.clearInChoice();
    };

    Window_Message.prototype.clearInChoice = function () {
        if ($gameMessage.isChoiceInMessage()) {
            const x = this.x + this.choiceStartX();
            const y = this.y + 4;
            const height = this.height;
            $gameMessage.setChoiceRect(x, y, -1, height);
        }
    };

    Window_Message.prototype.choiceStartX = function () {
        if (Utils.RPGMAKER_NAME === 'MV') {
            return this.standardPadding() + this._textState.left;
        } else {
            return $gameSystem.windowPadding() + this._textState.startX;
        }
    };

    const _Window_Message_processNewLine = __base(Window_Message.prototype, 'processNewLine');
    Window_Message.prototype.processNewLine = function (textState) {
        if ($gameMessage.isChoiceInMessage()) {
            $gameMessage.lowerChoiceHeight(textState.height);
        }
        _Window_Message_processNewLine.apply(this, arguments);
    };

    const _Window_Message_updateInput = Window_Message.prototype.updateInput;
    Window_Message.prototype.updateInput = function () {
        if ($gameMessage.isHelp() && this._textState) return false;
        return _Window_Message_updateInput.apply(this, arguments);
    };

    const _Window_Message_onEndOfText = Window_Message.prototype.onEndOfText;
    Window_Message.prototype.onEndOfText = function () {
        const choiceWindow = this._choiceWindow || this._choiceListWindow;
        if (!choiceWindow.active && $gameMessage.isHelp()) {
            this.startInput();
        } else {
            _Window_Message_onEndOfText.apply(this, arguments);
        }
    };

    const _Window_Message_startInput = Window_Message.prototype.startInput;
    Window_Message.prototype.startInput = function () {
        const choiceWindow = this._choiceWindow || this._choiceListWindow;
        if (choiceWindow.active) return true;
        if (this.isLowerChoice()) {
            $gameMessage.lowerChoiceHeight(this._textState.height);
        }
        return _Window_Message_startInput.apply(this, arguments);
    };

    Window_Message.prototype.isLowerChoice = function () {
        const startX = Utils.RPGMAKER_NAME === 'MV' ? 'left' : 'startX';
        return (
            $gameMessage.isChoice() &&
            $gameMessage.isChoiceInMessage() &&
            this._textState.x !== this._textState[startX]
        );
    };

    Window_Message.prototype.forceClear = function () {
        this._textState = null;
        this.close();
        this._goldWindow.close();
    };

    const _Window_Message_newPage = Window_Message.prototype.newPage;
    Window_Message.prototype.newPage = function (textState) {
        _Window_Message_newPage.apply(this, arguments);
        this.clearInChoice();
    };

})();

repo_name: dazed/translations

license: unknown