code:
const MOG_PHASE_NUMBER_NAME = 'Wave_Number';
const MOG_PHASE_NUMBER_X = -50;
const MOG_PHASE_NUMBER_Y = -18;

const MOG_WAVE_NUMBER_DURATION = 4;

//=============================================================================
// MOG_ConsecutiveBattles.js
//=============================================================================

/*:
 * @plugindesc (v1.0) Activates the system of consecutive battles.
 * @author Moghunter
 *
 * @param Show Wave Number
 * @desc Apresentar o número de Wave.
 * @default true
 *
 * @param X-Axis
 * @desc Definição X-axis.
 * @default 630
 *
 * @param Y-Axis
 * @desc Definição Y-axis.
 * @default 0
 *
 * @param Number X-Axis
 * @desc Definição X-axis do número.
 * @default 65
 *
 * @param Number Y-Axis
 * @desc Definição Y-axis do número.
 * @default 3
 *
 * @param Number FontSize
 * @desc Definição do tamanho da fonte.
 * @default 20
 *
 * @param Number Font Italic
 * @desc Ativar fonte em itálico.
 * @default false
 *
 * @param ---------------------
 *
 * @param Show Phase
 * @desc Apresentar a animação das fases.
 * @default true
 *
 * @param Phase Duration
 * @desc Definição da duração da animação.
 * @default 60
 *
 * @param Phase X-Axis
 * @desc Definição X-axis.
 * @default 220
 *
 * @param Phase Y-Axis
 * @desc Definição Y-axis.
 * @default 240
 *
 * @param Phase Number X-Axis
 * @desc Definição X-axis do número.
 * @default 10
 *
 * @param Phase Number Y-Axis
 * @desc Definição Y-axis do número.
 * @default 10
 *
 * @param Phase FontSize
 * @desc Definição do tamanho da fonte.
 * @default 28
 *
 * @param Phase Font Italic
 * @desc Ativar fonte em itálico.
 * @default true
 *
 * @help
 * =============================================================================
 * +++ MOG - Consecutive Battles (v1.0) +++
 * By Moghunter
 * https://atelierrgss.wordpress.com/
 * =============================================================================
 * Activates the system of consecutive battles.
 *
 * =============================================================================
 * PLUGIN COMMAND
 * =============================================================================
 * Use the command below to define consecutive battles,
 *
 * consecutive_battles : X,X,X,X,X,X......
 *
 * X - ID  da batalha
 *
 * =============================================================================
 * To display or hide the Wave number use the commands below.
 *
 * hide_wave_number
 *
 * show_wave_number
 *
 * =============================================================================
 * To show or hide the animation of the phases use the commands below.
 *
 * hide_phase_animation
 *
 * show_phase_animation
 *
 */

//=============================================================================
// ** PLUGIN PARAMETERS
//=============================================================================

  　var Imported = Imported || {};
　　Imported.MOG_ConsecutiveBattles = true;
　　var Moghunter = Moghunter || {};

  　Moghunter.parameters = PluginManager.parameters('MOG_ConsecutiveBattles');
    Moghunter.consBat_SpriteWave = String(Moghunter.parameters['Show Wave Number'] || 'true');
	Moghunter.consBat_SpriteWaveX = Number(Moghunter.parameters['X-Axis'] || 630);
	Moghunter.consBat_SpriteWaveY = Number(Moghunter.parameters['Y-Axis'] || 0);
	Moghunter.consBat_SpriteWaveNumberX = Number(Moghunter.parameters['Number X-Axis'] || 65);
	Moghunter.consBat_SpriteWaveNumberY = Number(Moghunter.parameters['Number Y-Axis'] || 3);
	Moghunter.consBat_SpriteWaveNumberFontSize = Number(Moghunter.parameters['Number FontSize'] || 20);
	Moghunter.consBat_SpriteWaveNumberFontItalic = String(Moghunter.parameters['Number Font Italic'] || 'false');

	Moghunter.consBat_SpriteTurn = String(Moghunter.parameters['Show Phase2 '] || 'true');
    Moghunter.consBat_SpriteTurnX = Number(Moghunter.parameters['Phase X-Axis'] || 220);
	Moghunter.consBat_SpriteTurnY = Number(Moghunter.parameters['Phase Y-Axis'] || 240);
	//Moghunter.consBat_SpriteTurnNumberX = Number(Moghunter.parameters['Phase Number X-Axis'] || 10);
	//Moghunter.consBat_SpriteTurnNumberY = Number(Moghunter.parameters['Phase Number Y-Axis'] || 10);
	Moghunter.consBat_SpriteTurnNumberX = MOG_PHASE_NUMBER_X;
	Moghunter.consBat_SpriteTurnNumberY = MOG_PHASE_NUMBER_Y;
    Moghunter.consBat_SpriteTurnNumberFontSize = Number(Moghunter.parameters['Phase FontSize'] || 34);
	Moghunter.consBat_SpriteTurnNumberFontItalic = String(Moghunter.parameters['Phase Font Italic'] || 'true');
	Moghunter.consBat_SpriteTurnDuration = Number(Moghunter.parameters['Phase Duration'] || 60);

//=============================================================================
// ** Game System
//=============================================================================

//==============================
// * initialize
//==============================
var _mog_consBat_gSys_initialize = Game_System.prototype.initialize;
Game_System.prototype.initialize = function() {
	_mog_consBat_gSys_initialize.call(this);
    this._consBat = {};
	this._consBat.enable = true;
	this._consBat.prepareSprite = false;
	this._consBat.index = 0;
	this._consBat.battles = [];
	this._consBat.rewards = [];
	this._consBatime = 0;
	this._consBaPhase = [false,false];
	this._consBaVisible = true;
	this._consBaTurnVisible = String(Moghunter.consBat_SpriteTurn) == "true" ? true : false;
	this._consBatWait = 0;
};

//==============================
// * clear ConsBat
//==============================
Game_System.prototype.clearConsBat = function() {
	this._consBat.enable = false;
	this._consBat.prepareSprite = false;
	this._consBat.index = 0;
	this._consBat.battles = [];
	this._consBat.rewards = [];
	this._consBatime = 0;
};

//=============================================================================
// ** Game_Interpreter
//=============================================================================

//==============================
// * PluginCommand
//==============================
var _mog_cosBat_pluginCommand = Game_Interpreter.prototype.pluginCommand
Game_Interpreter.prototype.pluginCommand = function(command, args) {
	_mog_cosBat_pluginCommand.call(this,command, args)
    this.setConsBattes(command, args);
	return true;
};

//==============================
// * set ConsBattes
//==============================
Game_Interpreter.prototype.setConsBattes = function(command, args) {
	if (command === "consecutive_battles")  {
		if (args[1]) {
			$gameSystem.clearConsBat();
			$gameSystem._consBat.enable = true;
			var battles = args[1].split(/,/)
			for (var i = 0; i < battles.length; i++) {
				var troopId = Number(battles[i]);
				if ($dataTroops[troopId]) {
					$gameSystem._consBat.battles.push(troopId);
				};
			};
			if ($gameSystem._consBat.battles.length === 0) {
				$gameSystem.clearConsBat();
			};
		};
	} else if (command === "hide_wave_number")  {
		     $gameSystem._consBaVisible = false;
	} else if (command === "show_wave_number")  {
		     $gameSystem._consBaVisible = true;
	} else if (command === "hide_phase_animation")  {
		     $gameSystem._consBaTurnVisible = false;
	} else if (command === "show_phase_animation")  {
		     $gameSystem._consBaTurnVisible = true;
    };
};

//=============================================================================
// ** Spriteset Battle
//=============================================================================

//==============================
// * create Enemies
//==============================
var _mog_consBat_sprtBat_createEnemies = Spriteset_Battle.prototype.createEnemies;
Spriteset_Battle.prototype.createEnemies = function() {
	_mog_consBat_sprtBat_createEnemies.call(this);
	this.createConBatField();
};

//==============================
// * create ConBat Field
//==============================
Spriteset_Battle.prototype.createConBatField = function() {
	this._conBatField = new Sprite();
	this._battleField.addChild(this._conBatField);
	if (this._enemySprites && this._enemySprites[0]) {
		this._conBatField.z = this._enemySprites[0].z ? this._enemySprites[0] : 0;
	} else {
		this._conBatField.z = 0
	};
};

//==============================
// * update
//==============================
var _mog_consBat_sprtBat_update = Spriteset_Battle.prototype.update;
Spriteset_Battle.prototype.update = function() {
    _mog_consBat_sprtBat_update.call(this);

	if ($gameSystem._consBatWait > 0) {$gameSystem._consBatWait--};
	if ($gameSystem._consBat.prepareSprite && $gameSystem._consBatWait === 0) {
	    this.prepareConBatSprites();
	};
};

//==============================
// * prepare ConBat Sprites
//==============================
Spriteset_Battle.prototype.prepareConBatSprites = function() {
   $gameSystem._consBat.prepareSprite = false;
   this.prepareComBatBefore();
   this.removeEnemiesConBat();
   this.createEnemies();
   this.prepareComBatAfter();
   BattleManager.startBattle();
   if ($gameSystem._consBat.index >= $gameSystem._consBat.battles.length) {
	   $gameSystem._consBat.enable = false;
   };
};

//==============================
// * prepare Com Bat Before
//==============================
Spriteset_Battle.prototype.prepareComBatBefore = function() {
   if (Imported.MOG_BattlerMotion) {
       this.removeBMotionShadow();
       this.createBMotionShadow();
   };
};

//==============================
// * prepare Com Bat After
//==============================
Spriteset_Battle.prototype.prepareComBatAfter = function() {
   if (Imported.MOG_HPGauge) {
       this.removeHPSprites();
       this.createHPSprites();
   };
   if (Imported.MOG_BattlerMotion) {
		for (var i = 0; i < this._enemySprites.length; i++) {
			var sprtEnemy = this._enemySprites[i];
			sprtEnemy.setIndexEm(i);
		};
		this.addBMotionShadow();
	};
	if (Imported.MOG_BattleCursor) {
	    $gameTemp._needRefreshBattleCursor = true;
	};
	if ($gameSystem._consBaTurnVisible) {
    	$gameSystem._consBaPhase = [true,true];
	};
	if ($gameTemp._battleEnd != null) {
		$gameTemp._battleEnd = false;
	};
	if (Imported.MOG_ATB) {
    	$gameSystem._atbEventPhase = [0,0,0,false,false];
    	$gameSystem._atbEventPhase[3] = BattleManager.updateEventMain();
	};
};

//==============================
// * remove Enemies ConBat
//==============================
Spriteset_Battle.prototype.removeEnemiesConBat = function() {
   for (var i = 0; i < this._enemySprites.length; i++) {
	    this._battleField.removeChild(this._enemySprites[i]);
		this._conBatField.removeChild(this._enemySprites[i]);
   };
};

//==============================
// * create Enemies ConBat
//==============================
Spriteset_Battle.prototype.createEnemiesConBat = function() {
    var enemies = $gameTroop.members();
    var sprites = [];
    for (var i = 0; i < enemies.length; i++) {
        sprites[i] = new Sprite_Enemy(enemies[i]);
    }
    sprites.sort(this.compareEnemySprite.bind(this));
    for (var j = 0; j < sprites.length; j++) {
        this._conBatField.addChild(sprites[j]);
    }
    this._enemySprites = sprites;
};

//=============================================================================
// ** Scene Base
//=============================================================================

//==============================
// ** create Hud Field
//==============================
Scene_Base.prototype.createHudField = function() {
	this._hudField = new Sprite();
	this._hudField.z = 10;
	this.addChild(this._hudField);
};

//==============================
// ** sort MZ
//==============================
Scene_Base.prototype.sortMz = function() {
   this._hudField.children.sort(function(a, b){return a.mz-b.mz});
};

//=============================================================================
// ** Scene Battle
//=============================================================================
var _mog_conBat_scBat_start = Scene_Battle.prototype.start;
Scene_Battle.prototype.start = function() {
	_mog_conBat_scBat_start.call(this);
	if ($gameSystem._consBaTurnVisible && $gameSystem._consBat.battles.length > 0
	&& ($gameVariables.value(VARIABLE_MOG_TURNS_SHOWED_1_ID) < $gameVariables.value(VARIABLE_MOG_TURNS_SHOWED_2_ID))
	) {
	    $gameSystem._consBaPhase = [true,true];
		$gameVariables.setValue(VARIABLE_MOG_TURNS_SHOWED_1_ID, $gameVariables.value(VARIABLE_MOG_TURNS_SHOWED_2_ID));
		//this._stateIconWindows = false;
		//this._statusWindow.refreshStateIconWindows();
	};
};
//==============================
// * create Spriteset
//==============================
var _mog_conBat_createSpriteset = Scene_Battle.prototype.createSpriteset;
Scene_Battle.prototype.createSpriteset = function() {
	_mog_conBat_createSpriteset.call(this);
	if (!this._hudField) {this.createHudField()};
};

//==============================
// * create Display Objects
//==============================
var _mog_consBat_sbat_createDisplayObjects = Scene_Battle.prototype.createDisplayObjects;
Scene_Battle.prototype.createDisplayObjects = function() {
	_mog_consBat_sbat_createDisplayObjects.call(this);
	var wsprite = String(Moghunter.consBat_SpriteWave) == "true" ? true : false;
    if(wsprite) {
	    this.createWaveNSprite();
		this.createTimeNSprite();
	    this.sortMz();
	};
};

//==============================
// * create Wave NSprite
//==============================
Scene_Battle.prototype.createWaveNSprite = function() {
    this._waveNCursor = new WaveNumber();
	this._waveNCursor.mz = 115;
	this._hudField.addChild(this._waveNCursor);

};

Scene_Battle.prototype.createTimeNSprite = function() {
    this._timeNCursor = new TimeNumber();
	this._timeNCursor.mz = 116;
	this._hudField.addChild(this._timeNCursor);

};

//==============================
// * need skip Battle Process CB
//==============================
Scene_Battle.prototype.needSkipBattleProcessCB = function() {
	if ($gameSystem._consBatime > 0) {return true};
	if ($gameSystem._consBaPhase[0]) {return true};
    return false;
};

//==============================
// * update Battle Process
//==============================
var _mog_consBat_sBat_updateBattleProcess = Scene_Battle.prototype.updateBattleProcess;
Scene_Battle.prototype.updateBattleProcess = function() {
	if (this.needSkipBattleProcessCB()) {
		$gameSystem._consBatime--;
		return;
	};
	_mog_consBat_sBat_updateBattleProcess.call(this);
};

//=============================================================================
// ** Battle Manager
//=============================================================================

//==============================
// * is Cons Battle
//==============================
BattleManager.isConsBattle = function() {
   if (!$gameSystem._consBat.enable) {return false};
   var troopID = $gameSystem._consBat.battles[$gameSystem._consBat.index]
   if (!$dataTroops[troopID]) {return false};
   return true;
};

//==============================
// * conBat
//==============================
BattleManager.prototype.conBat = function(switches) {
	if (!switches || switches.length === 0) {return}
	var swt = Math.randomInt(switches.length);
	var eswt = switches[swt]
    for (var i = 0; i < switches.length; i++) {
	     sch = Number(switches[i]);
		 if (sch === eswt) {
			 $gameSwitches.setValue(sch, true);
		 } else {
			 $gameSwitches.setValue(sch, false);
		 };
	};
};

//==============================
// * process Victory
//==============================
var _mog_conscBat_BatMngr_processVictory = BattleManager.processVictory;
BattleManager.processVictory = function() {
	if (this.isConsBattle()) {
	    this.prepareConBat();
		return;
	};
	this.getDataRewardsCB();
	_mog_conscBat_BatMngr_processVictory.call(this);
};

//==============================
// * prepare Con Bat
//==============================
BattleManager.prepareConBat = function() {
    this.getDataRewardsCB();
	this._phase = 'init';
	var troopID = $gameSystem._consBat.battles[$gameSystem._consBat.index]
    this._actorIndex = -1;
    this._actionForcedBattler = null;
    this._actionBattlers = [];
    this._subject = null;
    this._action = null;
    this._targets = [];
    $gameTroop.setup(troopID);
    $gameScreen.onBattleStart();
    this.makeEscapeRatio();
	$gameSystem._consBat.prepareSprite = true;
	$gameSystem._consBat.index++;
	$gameSystem._consBatime = 60;
	$gameSystem._consBatWait = 60;
	if ($gameTemp._battleEnd) {$gameTemp._battleEnd = false};
	if (Imported.MOG_BossHP) {$gameTemp._forceCreateBossHud = true};
	if (Imported.MOG_ATB) {
		$gameTemp._refreshATBGauge = true;
		BattleManager.selectionComAtbClear();
		BattleManager.prepareInitialATBValue();
		$gameSystem._atbEventPhase = [0,0,0,false,false];
	};
	SceneManager._scene._stateIconWindows = false;
};

//==============================
// * get Data Rewards CB
//==============================
BattleManager.getDataRewardsCB = function() {
	var index = $gameSystem._consBat.index
	$gameSystem._consBat.rewards[index] = {};
    $gameSystem._consBat.rewards[index].gold = $gameTroop.goldTotal();
    $gameSystem._consBat.rewards[index].exp = $gameTroop.expTotal();
    $gameSystem._consBat.rewards[index].items = $gameTroop.makeDropItems();
};

//==============================
// * make Rewards CB
//==============================
BattleManager.makeRewardsCB = function() {
    this._rewards = {};
	this._rewards.gold = 0;
	this._rewards.exp = 0;
	this._rewards.items = [];
	for (var i = 0; i < $gameSystem._consBat.rewards.length; i++) {
		var rwd = $gameSystem._consBat.rewards[i];
		this._rewards.gold += rwd.gold;
		this._rewards.exp += rwd.exp;
		for (var e = 0; e < rwd.items.length; e++) {
			 this._rewards.items.push(rwd.items[e]);
		};
	};
	$gameSystem._consBat.battles = [];
};

//==============================
// * make Rewards
//==============================
var _mog_cBat_BatMngr_makeRewards = BattleManager.makeRewards;
BattleManager.makeRewards = function() {
	if ($gameSystem._consBat.rewards.length > 0) {
		this.makeRewardsCB();
		return;
	};
	if ($gameTemp._battleEnd != null) {
		$gameTemp._battleEnd = true;
	};
	_mog_cBat_BatMngr_makeRewards.call(this);
};

//==============================
// * end Battle
//==============================
var _mog_cBat_BatMngr_endBattle = BattleManager.endBattle;
BattleManager.endBattle = function(result) {
	$gameSystem.clearConsBat();
	_mog_cBat_BatMngr_endBattle.call(this,result);
};

//==============================
// * display Start Messages
//==============================
var _mog_cBat_BatMngr_displayStartMessages = BattleManager.displayStartMessages;
BattleManager.displayStartMessages = function() {
	if ($gameSystem._consBat.index > 0) {return};
	_mog_cBat_BatMngr_displayStartMessages.call(this);
};

//=============================================================================
// * WaveNumber
//=============================================================================
function WaveNumber() {
    this.initialize.apply(this, arguments);
};

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

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

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

//==============================
// * Initialize
//==============================
WaveNumber.prototype.initialize = function() {
    Sprite.prototype.initialize.call(this);
	this.setup();
	this.createSprites();
};

TimeNumber.prototype.initialize = function() {
    Sprite.prototype.initialize.call(this);
	this.setup();
	this.createSprites();
};

//==============================
// * Setup
//==============================
WaveNumber.prototype.setup = function() {
	this._waveIndex = this.data().index;
	this._mwaveIndex = this.data().battles.length;
	this._showTurn = $gameSystem._consBaTurnVisible;
	this.opacity = 0;
};

TimeNumber.prototype.setup = function() {
	this._minuteValue = $gameParty.getTimeMinutesNumber();
	this._secondValue = '' + $gameParty.getTimeSecondsNumber();
	this._secondValue = this._secondValue.padStart(2, "0");
	this._showTimer = $gameParty._showTopRightTimeNumberFlag;
	this.opacity = 0;
};

//==============================
// * create Sprites
//==============================
WaveNumber.prototype.createSprites = function() {
	let showTopRightWave = $gameParty._showTopRightWaveNumberFlag;
	if(showTopRightWave) {
		this.createLayout();
		this.createNumber();
	}
	if(this._showTurn) {
		this.createTurnLayout();
		this.createTurnNumber();
	};
};

TimeNumber.prototype.createSprites = function() {
	if($gameParty._showTopRightTimeNumberFlag) {
		this.createLayout();
		this.createNumber();
	}
};

//==============================
// * create Layout
//==============================
WaveNumber.prototype.createLayout = function() {
	this._layout = new Sprite(ImageManager.loadSystem("Wave_A"));
	this._layout.x = REM_WAVE_LAYOUT_X;
	this._layout.y = REM_WAVE_LAYOUT_Y;
	this.addChild(this._layout);
};

TimeNumber.prototype.createLayout = function() {
	this._layout = new Sprite(ImageManager.loadSystem("Time_A"));
	if($gameParty._showTopRightWaveNumberFlag && $gameSystem._consBaTurnVisible && $gameSystem._consBat.battles.length > 0) {
		this._layout.x = REM_TIMER_LAYOUT_X;
		this._layout.y = REM_TIMER_LAYOUT_Y;
	}
	else {
		this._layout.x = REM_TIMER_LAYOUT_X;
		this._layout.y = REM_WAVE_LAYOUT_Y;
	}
	this.addChild(this._layout);
};

//==============================
// * Data
//==============================
WaveNumber.prototype.data = function() {
	 return $gameSystem._consBat;
};

//==============================
// * create Number
//==============================
WaveNumber.prototype.createNumber = function() {
     this._number = new Sprite(new Bitmap(160,48));

	this._number.bitmap.fontSize = REM_WAVE_FONT_SIZE;
	this._number.bitmap.fontItalic = String(Moghunter.consBat_SpriteWaveNumberFontItalic) === "true" ? true : false;
	this._number.x = this._layout.x + REM_WAVE_NUMBER_X;
	this._number.y = this._layout.y + REM_WAVE_NUMBER_Y;

	 this.addChild(this._number)
	 this.refreshWaveNumber();
};

TimeNumber.prototype.createNumber = function() {
     this._number = new Sprite(new Bitmap(160,48));

	this._number.bitmap.fontSize = REM_TIMER_FONT_SIZE;
	this._number.bitmap.fontItalic = String(Moghunter.consBat_SpriteWaveNumberFontItalic) === "true" ? true : false;
	this._number.x = this._layout.x + REM_TIMER_NUMBER_X;
	this._number.y = this._layout.y + REM_TIMER_NUMBER_Y;

	 this.addChild(this._number)
	 this.refreshTimeNumber();
};

//==============================
// * Refresh Wave Number
//==============================
WaveNumber.prototype.refreshWaveNumber = function() {
	let showTopRightWave = $gameParty._showTopRightWaveNumberFlag;
	 this._waveIndex = this.data().index;
	 this._mwaveIndex = this.data().battles.length;
	 if (this._mwaveIndex === 0) {return};
	 if(showTopRightWave)
		this._number.bitmap.clear();
	 var wave =  this._waveIndex + 1;
	 var mwave = this._mwaveIndex + 1;
	 var text = String(wave + " / " + mwave);
	 if(Prison.isEndlessBattle()) text = String(wave);
	 if(showTopRightWave)
		this._number.bitmap.drawText(text,0,0,this._number.width - 5,this._number.height - 5,"center");
	 $gameVariables.setValue(VARIABLE_MOG_TURNS_SHOWED_2_ID, wave);
};

TimeNumber.prototype.refreshTimeNumber = function() {
	let showTopRightTimer = $gameParty._showTopRightTimeNumberFlag;
	if(this._minuteValue === 0 && this._secondValue == '00') {return};
	if(!showTopRightTimer) {
		this.removeChild(this._layout);
		if(this._number) {
			this._number.bitmap.clear();
			this.removeChild(this._number);
		}
		this._minuteValue = 0;
		this._secondValue = '00';
		return;
	}

	if(showTopRightTimer && this._number)
		this._number.bitmap.clear();
	this._minuteValue = $gameParty.getTimeMinutesNumber();
	this._secondValue = '' + $gameParty.getTimeSecondsNumber();
	this._secondValue = this._secondValue.padStart(2, "0");
	let text = String(this._minuteValue + " : " + this._secondValue);
	if(showTopRightTimer)
		this._number.bitmap.drawText(text,0,0,this._number.width - 5,this._number.height - 5,"center");
};

//==============================
// * need Refresh Wave Number
//==============================
WaveNumber.prototype.needRefreshWaveNumber = function() {
    if (this._waveIndex != this.data().index) {return true};
	if (this._mwaveIndex != this.data().battles.length) {return true};
    return false;
};

TimeNumber.prototype.needRefreshTimeNumber = function() {
    if (this._minuteValue != $gameParty.getTimeMinutesNumber()) {return true};
	if (this._secondValue != $gameParty.getTimeSecondsNumber()) {return true};
    return false;
};

//==============================
// * create Turn Layout
//==============================
WaveNumber.prototype.createTurnLayout = function() {
    this._layoutTurn = new Sprite(ImageManager.loadSystem("Wave_B"));
	this._layoutTurn.x = Moghunter.consBat_SpriteTurnX;
	this._layoutTurn.y = Moghunter.consBat_SpriteTurnY;
	this._layoutTurn.org = [-1,-1];
	this._layoutTurn.visible = false;
	this._layoutTurn.anchor.x = 0.5;
	this._layoutTurn.anchor.y = 0.5;
	this._layoutTurnPhase = [0,60];
	this.addChild(this._layoutTurn);
};

//==============================
// * create Turn Number
//==============================
WaveNumber.prototype.createTurnNumber = function() {
	/*
   this._numberTurn = new Sprite(new Bitmap(300,48));
   this._numberTurn.bitmap.fontSize = Moghunter.consBat_SpriteTurnNumberFontSize;
   this._numberTurn.bitmap.fontItalic = String(Moghunter.consBat_SpriteTurnNumberFontItalic) === "true" ? true : false;
   this._numberTurn.x = Moghunter.consBat_SpriteTurnNumberX;
   this._numberTurn.y = Moghunter.consBat_SpriteTurnNumberY;
   this._numberTurn.org = [this._numberTurn.x,this._numberTurn.y];
   this._numberTurn.org = [this._numberTurn.x,this._numberTurn.y];
   this._numberTurn.anchor.x = 0.5;
   this._numberTurn.anchor.y = 0.5;
   */
   this._numberTurn = new Sprite_RemNumber(MOG_PHASE_NUMBER_NAME);
	this._numberTurn.x = MOG_PHASE_NUMBER_X;
	this._numberTurn.y = MOG_PHASE_NUMBER_Y;
	this._numberTurn.org = [this._numberTurn.x,this._numberTurn.y];
	this._numberTurn.setNumber(this._waveIndex + 1);
   this.addChild(this._numberTurn);
   this.refreshNumberTurn();
};

//==============================
// * refresh Number Turn
//==============================
WaveNumber.prototype.refreshNumberTurn = function() {
	/*
 	 this._numberTurn.bitmap.clear();
	 var waveWord = String(Moghunter.consBat_SpriteWaveWord)
	 var wave =  this._waveIndex + 1;
	 var mwave = this._mwaveIndex + 1;
	 var text = String(wave)
	 //var text = String(wave + "/" + mwave)
	 this._numberTurn.bitmap.drawText(text,0,0,this._numberTurn.width - 5,this._numberTurn.height - 5,"center");
	 */
	 this.removeChild(this._numberTurn);
	   this._numberTurn = new Sprite_RemNumber(MOG_PHASE_NUMBER_NAME);
	this._numberTurn.x = MOG_PHASE_NUMBER_X;
	this._numberTurn.y = MOG_PHASE_NUMBER_Y;
	this._numberTurn.org = [this._numberTurn.x,this._numberTurn.y];
	this._numberTurn.setNumber(this._waveIndex + 1);
   this.addChild(this._numberTurn);
};

//==============================
// * need Fade
//==============================
WaveNumber.prototype.needFade = function() {
	//if ($gameMessage.isBusy()) {return true};
	if (this._mwaveIndex === 0) {return true};
	if (!$gameSystem._consBaVisible) {return true};
	return false;
};

TimeNumber.prototype.needFade = function() {
	//if ($gameMessage.isBusy()) {return true};
	if(this._minuteValue === 0 && this._secondValue == '00') {return};
	return false;
};

//==============================
// * Update Visible
//==============================
WaveNumber.prototype.updateVisible = function() {
	if (this.needFade()) {
	    this.opacity -= 10;
	} else {
    	this.opacity += 10;
	};
};

TimeNumber.prototype.updateVisible = function() {
	if (this.needFade()) {
	    this.opacity -= 10;
	} else {
    	this.opacity += 10;
	};
};

//==============================
// * get Data
//==============================
WaveNumber.prototype.getData = function() {
	this._layoutTurn.org[0] = this._layoutTurn.x + (this._layoutTurn.width / 2) ;
	this._layoutTurn.org[1] = this._layoutTurn.y + (this._layoutTurn.height / 2);
};

//==============================
// * needRefreshTurnNumber
//==============================
WaveNumber.prototype.needRefreshTurnNumber = function() {
	if (!$gameSystem._consBaPhase[0]) {return false};
	if (!$gameSystem._consBaPhase[1]) {return false};
	return true;
};

//==============================
// * refresh Turn Number
//==============================
WaveNumber.prototype.refreshTurnNumber = function() {
	$gameSystem._consBaPhase[1] = false;
	this.opacity = 255
 	this._layoutTurn.x = this._layoutTurn.org[0] - 60;
	this._layoutTurn.y = this._layoutTurn.org[1];
	this._layoutTurn.opacity = 0;
	this._layoutTurn.visible = true;
	this._layoutTurnPhase = [0,60];
	this.refreshNumberTurn();
};

//==============================
// * update Slide
//==============================
WaveNumber.prototype.updateSlide = function() {
	if (this._layoutTurnPhase[0] === 0) {
		if (this._layoutTurn.x < this._layoutTurn.org[0]) {
			this._layoutTurn.x += 1
			this._layoutTurn.opacity += 5;
			if (this._layoutTurn.x >= this._layoutTurn.org[0]) {
				this._layoutTurn.x = this._layoutTurn.org[0];
				this._layoutTurn.opacity = 255;
				//this._layoutTurnPhase = [1,Moghunter.consBat_SpriteTurnDuration];
				this._layoutTurnPhase = [1,MOG_WAVE_NUMBER_DURATION];
				$gameSwitches.setValue(SWITCH_HIDE_STATE_ICONS_ID, false);
			};
		};
	} else if (this._layoutTurnPhase[0] === 1) {
		this._layoutTurnPhase[1]--;
		if (this._layoutTurnPhase[1] <= 0) {
			this._layoutTurnPhase[0] = 2
		};
	} else if (this._layoutTurnPhase[0] === 2) {
			this._layoutTurn.x += 1;
			this._layoutTurn.opacity -= 5;
			if (this._layoutTurn.opacity <= 0) {
				this._layoutTurnPhase[0] = 3;
				this._layoutTurn.visible = false;
				$gameSystem._consBaPhase[0] = false;
				$gameSwitches.setValue(SWITCH_HIDE_STATE_ICONS_ID, false);
			};
	};
	$gameVariables.setValue(VARIABLE_MOG_TURNS_SHOWED_1_ID, $gameVariables.value(VARIABLE_MOG_TURNS_SHOWED_2_ID));
};

//==============================
// * update Turn Sprites
//==============================
WaveNumber.prototype.updateTurnSprites = function() {
	if (this._layoutTurn.org[0] === -1) {
	    if (this._layoutTurn.bitmap.isReady()) {
			this.getData();
		};
	    return;
	};
	if (this.opacity === 0) {return};
	if (this.needRefreshTurnNumber()) {this.refreshTurnNumber()};
    this.updateSlide();
	this._numberTurn.x = this._layoutTurn.x + this._numberTurn.org[0];
	this._numberTurn.y = this._layoutTurn.y + this._numberTurn.org[1];
	this._numberTurn.opacity = this._layoutTurn.opacity;
	this._numberTurn.visible = this._layoutTurn.visible;
};

//==============================
// * Update
//==============================
WaveNumber.prototype.update = function() {
    Sprite.prototype.update.call(this);
	this.updateVisible();
	if (this.needRefreshWaveNumber()) {this.refreshWaveNumber()};
	if (this._layoutTurn) {this.updateTurnSprites()};
};

TimeNumber.prototype.update = function() {
    Sprite.prototype.update.call(this);
	this.updateVisible();
	if (this.needRefreshTimeNumber()) {this.refreshTimeNumber()};
};


code:
//=============================================================================
// MOG_MenuCursor.js
//=============================================================================
/*:
 * @plugindesc (v1.6) Adiciona um cursor animado no menu.
 * @author Moghunter
 *
 * @param Slide Animation
 * @desc Ativar animação de movimento lateral.
 * @default true
 *
 * @param Cursor X-axis
 * @desc Definição da posição X-axis para ajustes.
 * @default 0
 *
 * @param Cursor Y-axis
 * @desc Definição da posição Y-axis para ajustes.
 * @default 0
 *
 * @param Frames Animation
 * @desc Ativar animação por frames de imagem.
 * @default false
 *
 * @param Max Frames
 * @desc Quantidade de frames de animação.
 * @default 4
 *
 * @param Animation Speed
 * @desc Definição da velocidade da animação.
 * @default 7
 *
 * @help
 * =============================================================================
 * +++ MOG - Menu Cursor (v1.6) +++
 * By Moghunter
 * https://atelierrgss.wordpress.com/
 * =============================================================================
 * Adiciona um cursor animado no menu.
 * Será necessário o arquivo Menu_Cursor.png gravado na pasta. (img/system/)
 *
 * =============================================================================
 * HISTÓTICO
 * =============================================================================
 * (v1.6) - Melhoria na codificação.
 * (v1.5) - Correção de não ativar o cursor animado.
 * (v1.4) - Correção da velocidade do cursor na cena de titulo.
 * (v1.3) - Correção de na atualização na posição do Index quando os comandos
 *          ultrapassam o tamanho da janela.
 *        - Melhoria na compatibilidade de plugins.
 * (v1.2) - Melhoria no sistema de rolamento do mouse.
 * (v1.1) - Correção do glitch de não ocultar o cursor durante o fade da cena.
 *        - Melhoria da animação inicial do cursor.
 *
 */

//=============================================================================
// ** PLUGIN PARAMETERS
//=============================================================================
　　var Imported = Imported || {};
　　Imported.MOG_MenuCursor = true;
　　var Moghunter = Moghunter || {};

  　Moghunter.parameters = PluginManager.parameters('MOG_MenuCursor');
    Moghunter.mcursor_float = String(Moghunter.parameters['Slide Animation'] || true);
	Moghunter.mcursor_x = Number(Moghunter.parameters['Cursor X-axis'] || 0);
	Moghunter.mcursor_y = Number(Moghunter.parameters['Cursor Y-axis'] || 0);
	Moghunter.mcursor_animated = String(Moghunter.parameters['Frames Animation'] || "false");
	Moghunter.mcursor_maxframes = Number(Moghunter.parameters['Max Frames'] || 4);
	Moghunter.mcursor_animationSpeed = Number(Moghunter.parameters['Animation Speed'] || 7);

//=============================================================================
// ** Game_Temp
//=============================================================================

//==============================
// * Initialize
//==============================
var _alias_mog_mcursor_temp_initialize = Game_Temp.prototype.initialize;
Game_Temp.prototype.initialize = function() {
	_alias_mog_mcursor_temp_initialize.call(this);
	this._mcursorData = [false,0,0,0];
};

//=============================================================================
// ** Scene_Base
//=============================================================================

//==============================
// * Initialize
//==============================
var _mog_mcursor_scnBase_initialize = Scene_Base.prototype.initialize;
Scene_Base.prototype.initialize = function() {
	_mog_mcursor_scnBase_initialize.call(this);
	if ($gameTemp) {$gameTemp._mcursorData = [false,0,0,0]};
	this._sprite_mcursor = null;
};

//==============================
// * Update
//==============================
var _mog_mcursor_scnBase_update = Scene_Base.prototype.update;
Scene_Base.prototype.update = function() {
    _mog_mcursor_scnBase_update.call(this);
	if (!this._sprite_mcursor && $gameTemp && $gameTemp._mcursorData[0]){this.create_menucursor()};
	if (this._sprite_mcursor) {this.update_mcursor();};
};

//==============================
// * Create Menu Cursor
//==============================
Scene_Base.prototype.create_menucursor = function() {
	this.removeChild(this._sprite_mcursor);
    this._sprite_mcursor = new Sprite(ImageManager.loadSystem("Menu_Cursor"));
	this._sprite_mcursor.opacity = 0;
	this._sprite_mcursor.anchor.x = 0.5;
	this._sprite_mcursor.anchor.y = 0.5;
	this._mcursor_data = [-1,-1,0,0,0,false,false,0,0,0,5,0,0];
	if (String(Moghunter.mcursor_float) === "true") {this._mcursor_data[5] = true};
	if (String(Moghunter.mcursor_animated) === "true"){this._mcursor_data[6] = true};
    this._mcursor_data[11] = Math.min(Math.max(Moghunter.mcursor_animationSpeed,1),999);
	this.addChild(this._sprite_mcursor);
};

//==============================
// * Update Menu Cursor
//==============================
Scene_Base.prototype.update_mcursor = function() {
	if (this.isBusy()) {this._sprite_mcursor.opacity -= 25;return};
    if (this._mcursor_data[0] == -1) {this.set_mcursor_initial();return}
	if ($gameTemp._mcursorData[1] > 0) {$gameTemp._mcursorData[1] -= 1,this._sprite_mcursor.opacity +=15;}
	else {this._sprite_mcursor.opacity = 0};
	if (this._mcursor_data[5]) {this.update_mcursor_float()};
	if (this._mcursor_data[6]) {this.update_mcursor_frames()};
	var nx = $gameTemp._mcursorData[2] + this._mcursor_data[0] + this._mcursor_data[2];
    this._sprite_mcursor.x = this.cursorMoveToSVD(this._sprite_mcursor.x,nx,5);
	this._sprite_mcursor.y = this.cursorMoveToSVD(this._sprite_mcursor.y,$gameTemp._mcursorData[3] + this._mcursor_data[1],5);
};

//==============================
// * Set Mcursor Initial
//==============================
Scene_Base.prototype.set_mcursor_initial = function() {
    if (!this._sprite_mcursor.bitmap.isReady()) {return};
    this._mcursor_data[0] = Moghunter.mcursor_x;
	this._mcursor_data[1] = (this._sprite_mcursor.bitmap.height / 2) + Moghunter.mcursor_y;
	if (this._mcursor_data[6] ) {
	    this._mcursor_data[7] = Math.floor(this._sprite_mcursor.bitmap.width / Moghunter.mcursor_maxframes)
		this._mcursor_data[8] = this._sprite_mcursor.bitmap.height;
	};
};

//==============================
// * Udate Mcursor Frames
//==============================
Scene_Base.prototype.update_mcursor_frames = function() {
	this._mcursor_data[10] += 1
	if (this._mcursor_data[10] < this._mcursor_data[11]) {return};
	this._mcursor_data[10] = 0
	this._sprite_mcursor.setFrame(this._mcursor_data[7] * this._mcursor_data[9],0, this._mcursor_data[7],this._mcursor_data[8]);
	this._mcursor_data[9] += 1;
	if (this._mcursor_data[9] >= Moghunter.mcursor_maxframes) {this._mcursor_data[9] = 0};
};

//==============================
// * Update Mcursor Float
//==============================
Scene_Base.prototype.update_mcursor_float = function() {
	 this._mcursor_data[4] += 1;
	 if (this._mcursor_data[4] < 2) {return;};
     this._mcursor_data[4] = 0;
	 this._mcursor_data[3] += 1;
	 if (this._mcursor_data[3] < 15) {this._mcursor_data[2] += 1}
	 else if (this._mcursor_data[3] < 30) {this._mcursor_data[2] -= 1}
	 else {this._mcursor_data[2] = 0 ;this._mcursor_data[3] = 0};
};

//==============================
// * cursor Move toSVD
//==============================
Scene_Base.prototype.cursorMoveToSVD = function(value,real_value,speed) {
	if (value == real_value) {return value};
	var dnspeed = 255 + (Math.abs(value - real_value) / 255);
	if (value > real_value) {value -= dnspeed;
	    if (value < real_value) {value = real_value};}
    else if (value < real_value) {value  += dnspeed;
    	if (value  > real_value) {value  = real_value};
    };
	return Math.floor(value);
};

//=============================================================================
// ** Window Selectable
//=============================================================================

//==============================
// * Initialize
//==============================
var _mog_mcursor_wselect_initialize = Window_Selectable.prototype.initialize;
Window_Selectable.prototype.initialize = function(x, y, width, height) {
    _mog_mcursor_wselect_initialize.call(this,x, y, width, height);
	this._refCursorIndex = false;
};

//==============================
// * Update Arrows
//==============================
var _mog_mcursor_wSelect_updateArrows = Window_Selectable.prototype.updateArrows
Window_Selectable.prototype.updateArrows = function() {
    _mog_mcursor_wSelect_updateArrows.call(this);
	if (this.need_set_mcursor_data()) {this.set_mcursor_data();};
};

//==============================
// * Need Set MCursor Data
//==============================x
Window_Selectable.prototype.need_set_mcursor_data = function() {
	if (!this.active) {return false};
	if (!this.visible) {return false};
	if (this.index() < 0) {return false};
	if (this._opening) {return false};
	if (this._closing) {return false};
	if (this.openness <= 0) {return false};
	if (this.x <= -this.width || this.x >= Graphics.boxWidth) {return false};
	if (this.y <= -this.height || this.y >= Graphics.boxHeight) {return false};
	if (SceneManager.isSceneChanging()) {return false};
	return true;
};

//==============================
// * Set Mcursor Data
//==============================
Window_Selectable.prototype.set_mcursor_data = function() {
	if (!this._refCursorIndex) {this._refCursorIndex = true;this.select(this.index())};
	var rect = this.itemRect(this.index());
	if(rect.x < 0 || rect.y < 0 || rect.x > (this.width - 48) || rect.y > (this.height - 48)) {return};
	$gameTemp._mcursorData[0] = true;
	$gameTemp._mcursorData[1] = 1;
	$gameTemp._mcursorData[2] = this.x + rect.x;
	$gameTemp._mcursorData[3] = this.y + rect.y + (rect.height / 2);
	this.updateScrollRoll();
};

//==============================
// * update SCroll Roll
//==============================
Window_Selectable.prototype.updateScrollRoll = function() {
    if (this.isOpenAndActive() && this.maxItems() > 0) {
		var srow = this.maxTopRow() === 0 ? 1 : this.maxCols();
        var threshold = 20;
		var idx = this._index;
        if (TouchInput.wheelY >= threshold) {
            this._index += srow;
			if (this._index > (this.maxItems() - 1)) {this._index = this.maxItems() - 1};
			this.select(this._index);
			if (idx != this._index) {SoundManager.playCursor()};
        };
        if (TouchInput.wheelY <= -threshold) {
            this._index -= srow;
			if (this._index < 0) {this._index = 0};
			this.select(this._index);
			if (idx != this._index) {SoundManager.playCursor()};
        };
    };
};

repo_name: voidljb/karryn

license: unknown


code:
//===========================================================================
// MOG_Scrollbar.js
// Translate to Japanese : fungamemake.com
//===========================================================================

/*:
 * @plugindesc (v2.2) Adiciona uma barra de rolamento nas janelas.
 * @author Moghunter
 *
 * @param Always Visible
 * @desc Deixar o medidor sempre visível.
 * @default true
 *
 * @param X-Axis
 * @desc Definição da posição X-Axis da barra.
 * @default 0
 *
 * @param Y-Axis
 * @desc Definição da posição Y-Axis da barra.
 * @default 0
 *
 * @param Button X-Axis
 * @desc Definição da posição X-Axis do botão.
 * @default 1
 *
 * @param Button Y-Axis
 * @desc Definição da posição Y-Axis da botão.
 * @default 1
 *
 * @help
 * ===========================================================================
 * +++ MOG - Scroll Bar (v2.2) +++
 * By Moghunter
 * https://atelierrgss.wordpress.com/
 * ===========================================================================
 * Adiciona uma barra de rolamento nas janelas.
 *
 * ===========================================================================
 * UTILIZAÇÃO
 * ===========================================================================
 * Serão necessários as imagens. (/img/system/)
 *
 * ScrollBarA.png
 * ScrollBarB.png
 *
 * ===========================================================================
 * HISTÓRICO
 * ===========================================================================
 * (v2.2) - Correção de não atualizar o rolamento ao diminuir o tamanho.
 *        - Correção do modo "Always Visible".
 *        - Correção do plugin parameter da posição Y do layout.
 * (v2.1) - Correção do plugin parameter da posição Y do botão.
 * (v2.0) - Plugin reescrito por completo.
 *        - Barra baseadas em imagens.
 *        - Movimento suave.
 * (v1.4) - Correção o erro de não criar o Scroll bar quando a janela é atualizada.
 * (v1.3) - Correção do glitch na janela de escolhas.
 * (v1.2) - Melhoria na codificação.
 * (v1.1) - Correção da posição da barra em janelas de multiplas colunas.
 *
 */

/*:ja
 * @plugindesc (v2.2) ウィンドウにスクロールバーを追加します。
 * @author Moghunter
 *
 * @param Always Visible
 * @text メーターの表示
 * @type boolean
 * @on 表示
 * @off 非表示
 * @default true
 *
 * @param X-Axis
 * @text バーのX軸位置
 * @desc 正:右 / 負:左
 * @default 0
 *
 * @param Y-Axis
 * @text バーのY軸位置
 * @desc 正:下 / 負:上
 * @default 0
 *
 * @param Button X-Axis
 * @text ボタンのX軸位置
 * @desc 正:右 / 負:左
 * @default 1
 *
 * @param Button Y-Axis
 * @text ボタンのY軸位置
 * @desc 正:下 / 負:上
 * @default 1
 *
 * @help
 * 翻訳:ムノクラ
 * https://fungamemake.com/
 * https://twitter.com/munokura/
 *
 * ===========================================================================
 * +++ MOG - Scroll Bar (v2.2) +++
 * By Moghunter
 * https://atelierrgss.wordpress.com/
 * ===========================================================================
 * ウィンドウにスクロールバーを追加します。
 *
 * ===========================================================================
 * 必要ファイル
 * ===========================================================================
 * 下記の画像ファイルが必要になります。 (/img/system/)
 *
 * ScrollBarA.png
 * ScrollBarB.png
 *
 * ===========================================================================
 * 変更履歴
 * ===========================================================================
 * (v2.2) - サイズを小さくしてベアリングを更新しない問題を修正
 *          - "Always Visible"モードの修正
 *          - レイアウトY位置プラグインパラメータ修正
 * (v2.1) - ボタン位置Yプラグインパラメータの修正
 * (v2.0) - プラグインが完全に書き直されました
 *          - 画像に基づくバー
 *          - 滑らかな動き
 * (v1.4) - ウィンドウが更新された時、スクロールバーが作成されないエラーを修正
 * (v1.3) - 選択ウィンドウのグリッチ修正
 * (v1.2) - コーディングの改善
 * (v1.1) - 複数列のウィンドウにおけるバーの位置の修正
 *
 */

//===========================================================================
// ** PLUGIN PARAMETERS
//===========================================================================
    var Imported = Imported || {};
    Imported.MOG_Scrollbar = true;
    var Moghunter = Moghunter || {};

    Moghunter.parameters = PluginManager.parameters('MOG_Scrollbar');
	Moghunter.scrollBarAlwaysVisible = String(Moghunter.parameters['Always Visible'] || 'true');
    Moghunter.scrollBarX = Number(Moghunter.parameters['X-Axis'] || 0);
    Moghunter.scrollBarY = Number(Moghunter.parameters['Y-Axis'] || 0);
    Moghunter.scrollBar_ButtonX = Number(Moghunter.parameters['Button X-Axis'] || 1);
    Moghunter.scrollBar_ButtonY = Number(Moghunter.parameters['Button Y-Axis'] || 0);

//===========================================================================
// ** Window Selectable
//===========================================================================

//==============================
// * Initialize
//==============================
var _mog_scrollbar_winSel_initialize = Window_Selectable.prototype.initialize;
Window_Selectable.prototype.initialize = function(x, y, width, height) {
	_mog_scrollbar_winSel_initialize.call(this,x, y, width, height);
	this.createScrollBar();
};

//==============================
// * create Scroll Bar
//==============================
Window_Selectable.prototype.createScrollBar = function() {
	this._refScroll = true;
	this._scrollBar = new SpriteScrollBar(this);
	var id = this.scrollBarSetChild();
	this.addChildAt(this._scrollBar,id);
};

//==============================
// * scrollBarSetChild
//==============================
Window_Selectable.prototype.scrollBarSetChild = function() {
	var id = 3;
	if (id > this.children.length) {id = this.children.length};
	return id;
};

//==============================
// * set Cursor Rect
//==============================
var _mog_scroll_setCursorRect = Window_Selectable.prototype.setCursorRect;
Window_Selectable.prototype.setCursorRect = function(x, y, width, height) {
	_mog_scroll_setCursorRect.call(this,x, y, width, height);
    this._refScroll = true;
};

//==============================
// * select
//==============================
var _mog_scrollbar_wsel_select = Window_Selectable.prototype.select;
Window_Selectable.prototype.select = function(index) {
	_mog_scrollbar_wsel_select .call(this,index);
    if (this._scrollBar) {this._scrollBar.update()};
};

//===========================================================================
// ** Sprite Scroll Bar
//===========================================================================
function SpriteScrollBar() {
    this.initialize.apply(this, arguments);
};

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

//==============================
// * Initialize
//==============================
SpriteScrollBar.prototype.initialize = function(win) {
    Sprite.prototype.initialize.call(this);
	this._window = win;
	this.visible = false;
    this._avisble = String(Moghunter.scrollBarAlwaysVisible) === 'true' ? true : false;
	this.loadBitmaps();
	this.createSprites();
};

//==============================
// * Load Bitmaps
//==============================
SpriteScrollBar.prototype.loadBitmaps = function() {
   this._img1 = ImageManager.loadSystem("ScrollBarA");
   this._img2 = ImageManager.loadSystem("ScrollBarB");
};

//==============================
// * rc
//==============================
SpriteScrollBar.prototype.rc = function() {
   return this._window._cursorRect
};

//==============================
// * create Sprites
//==============================
SpriteScrollBar.prototype.createSprites = function() {
    this.createBack();
	this.createButton();
};

//==============================
// * create Back
//==============================
SpriteScrollBar.prototype.createButton = function() {
    this._button = [];
	this._button._ny = 0;
	this._button._maxItens = -1;
	this._button._maxTopRow = -1;
	for (var i = 0; i < 3; i++) {
		 this._button[i] = new Sprite(this._img2);
		 this._button[i].visible = false;
		 this.addChild(this._button[i]);
	};
};

//==============================
// * refresh button
//==============================
SpriteScrollBar.prototype.refreshButton = function() {
	var w = this._img2.width / 2;
	var h = this._img2.height;
    for (var i = 0; i < this._button.length; i++) {
		 var p = [0,-999];
		 var bx = Moghunter.scrollBar_ButtonX;
		 var by = this.buttonPos();
		 this._button[i].setFrame(0,0,w,h);
		 this._button[i].visible = true;
		 if (i === 0) {p = [bx,by - this._img2.height]};
		 if (i === 1) {p = [bx,by];this._button[i].setFrame(w,0,w,h)};
		 if (i === 2) {p = [bx,by + this.buttonSize() + this._img2.height]};
		 this._button[i].x = p[0];
	     if (this._button._maxItens != this._window.maxItems()) {
			 this._button[i].y = p[1]

		};
	};
	this.setScaleButton();
	this._button._maxItens = this._window.maxItems();
};

//==============================
// * update Button
//==============================
SpriteScrollBar.prototype.updateButton = function() {
    for (var i = 0; i < this._button.length; i++) {
		 var by = this.buttonPos();
		 if (i === 0) {ny = by - this._img2.height};
		 if (i === 1) {ny = by};
		 if (i === 2) {ny = by + this.buttonSize() + this._img2.height};
	     this._button[i].y = this.moveto(this._button[i].y,ny);
	};
};

//==============================
// * button Size
//==============================
SpriteScrollBar.prototype.buttonSize = function() {
	var size = (this.heightF() - (this.padding() * this._window.maxTopRow()));
	return Math.min(Math.max(size,this.padding()),this.heightF());
};

//==============================
// * moveto
//==============================
SpriteScrollBar.prototype.moveto = function(value,real_value) {
	if (value == real_value) {return value};
	var dnspeed = 3 + (Math.abs(value - real_value) / 10);
	if (value > real_value) {value -= dnspeed;
	    if (value < real_value) {value = real_value};}
    else if (value < real_value) {value  += dnspeed;
    	if (value  > real_value) {value  = real_value};
    };
	return Math.floor(value);
};

//==============================
// * scroll Bar Y
//==============================
SpriteScrollBar.prototype.scrollBarY = function() {
	return Moghunter.scrollBar_ButtonY;
};

//==============================
// * button Pos
//==============================
SpriteScrollBar.prototype.buttonPos = function() {
	var space_max = this.heightF() - this.buttonSize();
 	var space = space_max / this._window.maxTopRow();
	var s = Math.min(Math.max(space,0.001),space_max);
	var y = this.scrollBarY() + (s * Math.floor(this._window.topIndex() / this._window.maxCols()));
	return Math.min(Math.max(y,0),space_max);
};

//==============================
// * set Scale Button
//==============================
SpriteScrollBar.prototype.setScaleButton = function() {
    this._button[1].scale.y = this.buttonSize() / this._img2.height;
	this._button[2].scale.y = -1.00;
};

//==============================
// * create Back
//==============================
SpriteScrollBar.prototype.createBack = function() {
    this._back = [];
	for (var i = 0; i < 3; i++) {
		 this._back[i] = new Sprite(this._img1);
		 this._back[i].visible = false;
		 this.addChild(this._back[i]);
	};
};

//==============================
// * refresh Back
//==============================
SpriteScrollBar.prototype.refreshBack = function() {
	var w = this._img1.width / 2;
	var h = this._img1.height;
    for (var i = 0; i < this._back.length; i++) {
		 var p = [0,0];
		 this._back[i].setFrame(0,0,w,h);
		 if (i === 0) {p = [0,-this._img1.height]};
		 if (i === 1) {p = [0,0];this._back[i].setFrame(w,0,w,h)};
		 if (i === 2) {p = [0,this.heightF() + this._img1.height]};
		 this._back[i].x = p[0];
		 this._back[i].y = p[1];
		 this._back[i].visible = true;
	};
	this.setScaleBack();
};

//==============================
// * Set Scale Back
//==============================
SpriteScrollBar.prototype.setScaleBack = function() {
    this._back[1].scale.y = this.heightF() / this._img1.height;
	this._back[2].scale.y = -1.00;
};

//==============================
// * Padding
//==============================
SpriteScrollBar.prototype.padding = function() {
   return this._window.standardPadding()
};

//==============================
// * Pos X
//==============================
SpriteScrollBar.prototype.posX = function() {
	return this._window.width - this.padding() + Moghunter.scrollBarX;
};

//==============================
// * Pos Y
//==============================
SpriteScrollBar.prototype.posY = function() {
	return this.padding() + Moghunter.scrollBarY;
};

//==============================
// * Height F
//==============================
SpriteScrollBar.prototype.heightF = function() {
    return this._window.height - (this.padding() * 2);
};

//==============================
// * refresh Sprites
//==============================
SpriteScrollBar.prototype.refreshSprites = function() {
    this._window._refScroll = false;
	this._button._maxTopRow = this._window.maxTopRow();
	this.refreshBack();
	this.refreshButton();
};

//==============================
// * needRefresh
//==============================
SpriteScrollBar.prototype.needRefresh = function() {
	if (this._window._refScroll) {return true};
	if (this._button._maxTopRow != this._window.maxTopRow()) {return true};
    return false;
};

//==============================
// * update Position
//==============================
SpriteScrollBar.prototype.updatePosition = function() {
     if (this.needRefresh()) {this.refreshSprites()};
	 this.updateButton();
	 this.visible = this.isVisible();
	 this.x = this.posX();
  	 this.y = this.posY();
     this.opacity = this._window.contentsOpacity;
	 if (!this.visible) {this._button._maxItens = -2};
};

//==============================
// * Is Visible
//==============================
//REM
SpriteScrollBar.prototype.isVisible = function() {
	if (this._window._opening) {return false};
	if (this._window._closing) {return false};
	if (this._window.openness <= 0) {return false};
	if (!this._window.visible) {return false};
	if (this._window.maxTopRow() === 0) {return false};
	if (!this._avisble && !this._window.active) {return false};
	if(this._window._logMainSprite && this._window._logMainSprite.visible) return false;
	return true;
};
this._logMainSprite
//==============================
// * Update
//==============================
SpriteScrollBar.prototype.update = function() {
    Sprite.prototype.update.call(this);
	if (!this._img1) {return};
    if (!this._img1.isReady()) {return};
	if (!this.rc()) {this.visible = false;return};
	this.updatePosition();
};


code:
const TITLE_CURSOR_AXIS_X = 8;　//CursorからCommandまでの移動
const TITLE_CURSOR_AXIS_Y = 10;

const TITLE_CURSOR_START_X = 850; //Cursorはどこから出てくるか
const TITLE_CURSOR_START_Y = 400;

const TITLE_COMMAND_0_X = 900; //New Game
const TITLE_COMMAND_0_Y = 385;
const TITLE_COMMAND_1_X = 900; //Continue
const TITLE_COMMAND_1_Y = 445;
const TITLE_COMMAND_2_X = 900; //Settings
const TITLE_COMMAND_2_Y = 505;
const TITLE_COMMAND_3_X = 900; //Patreon / Ci-en
const TITLE_COMMAND_3_Y = 565;
const TITLE_COMMAND_4_X = 900; //Discord
const TITLE_COMMAND_4_Y = 625;
const TITLE_COMMAND_5_X = 900; //Exit Game
const TITLE_COMMAND_5_Y = 685;

//=============================================================================
// MOG_TitlePictureCom.js
//=============================================================================

/*:
 * @plugindesc (v1.4) Adiciona comandos em imagens no lugar da janela.
 * @author Moghunter
 *
 * @param Title Sprite
 * @desc Ativar o nome do título em sprite.
 * É necessário ter o arquivo Title.png na pasta img/titles2/
 * @default true
 *
 * @param Title Sprite X-Axis
 * @desc Definição X-axis do texto do título.
 * @default 0
 *
 * @param Title Sprite Y-Axis
 * @desc Definição Y-axis do texto do título.
 * @default 0
 *
 * @param Cursor Visible
 * @desc Ativar cursor.
 * @default true
 *
 * @param Cursor Wave Animation
 * @desc Ativar animação de deslize.
 * @default true
 *
 * @param Cursor X-Axis
 * @desc Definição X-axis do cursor.
 * @default 8
 *
 * @param Cursor Y-Axis
 * @desc Definição Y-axis do cursor.
 * @default -10
 *
 * @param Command Pos 1
 * @desc Definição da posição do comando 1.
 * E.g -     32,32
 * @default 650,460
 *
 * @param Command Pos 2
 * @desc Definição da posição do comando 2.
 * E.g -     32,32
 * @default 660,490
 *
 * @param Command Pos 3
 * @desc Definição da posição do comando 3.
 * E.g -     32,32
 * @default 665,520
 *
 * @param Command Pos 4
 * @desc Definição da posição do comando 4.
 * E.g -     32,32
 * @default 670,550
 *
 * @param Command Pos 5
 * @desc Definição da posição do comando 5.
 * E.g -     32,32
 * @default 345,498
 *
 * @param Command Pos 6
 * @desc Definição da posição do comando 6.
 * E.g -     32,32
 * @default 345,530
 *
 * @param Command Pos 7
 * @desc Definição da posição do comando 7.
 * E.g -     32,32
 * @default 0,192
 *
 * @param Command Pos 8
 * @desc Definição da posição do comando 8.
 * E.g -     32,32
 * @default 0,224
 *
 * @param Command Pos 9
 * @desc Definição da posição do comando 9.
 * E.g -     32,32
 * @default 0,256
 *
 * @param Command Pos 10
 * @desc Definição da posição do comando 10.
 * E.g -     32,32
 * @default 0,288
 *
 * @help
 * =============================================================================
 * +++ MOG - Title Picture Commands (v1.4) +++
 * By Moghunter
 * https://atelierrgss.wordpress.com/
 * =============================================================================
 * Adiciona comandos em imagens no lugar da janela.
 * É necessário ter os arquivos:
 *
 * Command_0.png, Command_1.png, Command_2.png , Command_3.png ...
 *
 * Grave as imagens na pasta:
 *
 * img/titles2/
 * =============================================================================
 * Será necessário também uma imagem representando o cursor.
 *
 * Cursor.png
 *
 * =============================================================================
 * ** Histórico **
 * =============================================================================
 * v1.4 - Melhoria na codificação.
 * v1.3 - Adição do Cursor.
 * v1.2 - Possibilidade de definir a posição de multiplos comandos.
 *      - Correção do lag ao trocar de comandos.
 * v1.1 - Corrigido o glich de poder clicar no comando durante o fade.
 *
 */

//=============================================================================
// ** PLUGIN PARAMETERS
//=============================================================================
　　var Imported = Imported || {};
　　Imported.MOG_Picture_Command = true;
　　var Moghunter = Moghunter || {};

  　Moghunter.parameters = PluginManager.parameters('MOG_TitlePictureCom');
	Moghunter.title_sprite = (Moghunter.parameters['Title Sprite'] || false);
	Moghunter.title_x = Number(Moghunter.parameters['Title Sprite X-Axis'] || 0);
	Moghunter.title_y = Number(Moghunter.parameters['Title Sprite Y-Axis'] || 0);
	Moghunter.title_cursorVisible = String(Moghunter.parameters['Cursor Visible'] || "true");
	Moghunter.title_cursorSlide = String(Moghunter.parameters['Cursor Wave Animation'] || "true");
	Moghunter.title_cursorX = Number(Moghunter.parameters['Cursor X-Axis'] || 8);
	Moghunter.title_cursorY = Number(Moghunter.parameters['Cursor Y-Axis'] || -10);
	Moghunter.title_com_pos = [];
	for (let i = 0; i < 10; i++) {
		Moghunter.title_com_pos[i] = (Moghunter.parameters['Command Pos ' + String(i + 1)] || null);
		if(i === 0) Moghunter.title_com_pos[i] = '' + TITLE_COMMAND_0_X + ',' + TITLE_COMMAND_0_Y;
		else if(i === 1) Moghunter.title_com_pos[i] = '' + TITLE_COMMAND_1_X + ',' + TITLE_COMMAND_1_Y;
		else if(i === 2) Moghunter.title_com_pos[i] = '' + TITLE_COMMAND_2_X + ',' + TITLE_COMMAND_2_Y;
		else if(i === 3) Moghunter.title_com_pos[i] = '' + TITLE_COMMAND_3_X + ',' + TITLE_COMMAND_3_Y;
		else if(i === 4) Moghunter.title_com_pos[i] = '' + TITLE_COMMAND_4_X + ',' + TITLE_COMMAND_4_Y;
		else if(i === 5) Moghunter.title_com_pos[i] = '' + TITLE_COMMAND_5_X + ',' + TITLE_COMMAND_5_Y;
	};

//=============================================================================
// ** Window_TitleCommand
//=============================================================================

//==============================
// * updatePlacement
//==============================
var _alias_mog_title_picture_commands_updatePlacement = Scene_Title.prototype.updatePlacement;
Window_TitleCommand.prototype.updatePlacement = function() {
   this.x = -Graphics.boxWidth;
   this.y = -Graphics.boxheight;
   this.visible = false;
};

//=============================================================================
// ** Scene Title
//=============================================================================

//==============================
// * Create
//==============================
var _alias_mog_title_picture_commands_create = Scene_Title.prototype.create;
Scene_Title.prototype.create = function() {
    _alias_mog_title_picture_commands_create.call(this);
    this.create_picture_commands();
	if (String(Moghunter.title_cursorVisible) === "true") {this.createCursorCommand()};
	this._comSave = this._commandWindow.isContinueEnabled();
};

//==============================
// * set tcp
//==============================
Scene_Title.prototype.set_tcp = function(value) {
	if (!value) {return null};
	var s = value.split(',');
	if (!s[0] || !s[1]) {return null};
	return  [Number(s[0]),Number(s[1])];
};

//==============================
// * Update
//==============================
var _alias_mog_title_picture_commands_update = Scene_Title.prototype.update;
Scene_Title.prototype.update = function() {
    _alias_mog_title_picture_commands_update.call(this);
	this.update_picture_commands();
};

//==============================
// * Create Cursor Command
//==============================
Scene_Title.prototype.createCursorCommand = function() {
	this._cursorSlide = [0,0,0,false];
	if (String(Moghunter.title_cursorSlide) === "true") {this._cursorSlide[3] = true};
    this._cursor = new Sprite(ImageManager.loadTitle2("Cursor"));
	this._cursor.anchor.x = 0.5;
	this._cursor.anchor.y = 0.5;
	this._cursor.opacity = 0;
	this._cursor.x = TITLE_CURSOR_START_X;
	this._cursor.y = TITLE_CURSOR_START_Y;
	this.addChild(this._cursor);
};

//==============================
// * Com Sprite
//==============================
Scene_Title.prototype.comSprite = function() {
    return this._com_sprites[this._commandWindow._index];
};

//==============================
// * update Cursor
//==============================
Scene_Title.prototype.updateCursor = function() {
	 if (this._cursorSlide[3]) {this.updateCursorSlide()};
   	 this._cursor.opacity += 10;
 	 //var nx = this.comSprite().x - (this._cursor.width / 2) + Moghunter.title_cursorX + this._cursorSlide[0];
	 //var ny = this.comSprite().y + (this._cursor.height / 2) + Moghunter.title_cursorY;
	 var nx = this.comSprite().x - (this._cursor.width / 2) + TITLE_CURSOR_AXIS_X + this._cursorSlide[0];
	 var ny = this.comSprite().y + (this._cursor.height / 2) + TITLE_CURSOR_AXIS_Y;
     this._cursor.x = this.cursorMoveto(this._cursor.x, nx, 20);
	 this._cursor.y = this.cursorMoveto(this._cursor.y, ny, 20);
};

//==============================
// * update Cursor Slide
//==============================
Scene_Title.prototype.updateCursorSlide = function() {
     this._cursorSlide[1] ++
	 if (this._cursorSlide[1] < 3) {return};
	 this._cursorSlide[1] = 0
	 this._cursorSlide[2] ++
	 if (this._cursorSlide[2] < 15) {
		 this._cursorSlide[0] ++;
	 } else if (this._cursorSlide[2] < 30) {
		 this._cursorSlide[0] --;
	 } else {
		 this._cursorSlide[0] = 0;
		 this._cursorSlide[2] = 0;
	 };
};

//==============================
// * Sprite Move To
//==============================
Scene_Title.prototype.cursorMoveto = function(value,real_value,speed) {
	if (value == real_value) {return value};
	var dnspeed = 5 + (Math.abs(value - real_value) / speed);
	if (value > real_value) {value -= dnspeed;
	    if (value < real_value) {value = real_value};}
    else if (value < real_value) {value  += dnspeed;
    	if (value  > real_value) {value  = real_value};
    };
	return Math.floor(value);
};

//==============================
// * Create Picture Commands
//==============================
Scene_Title.prototype.create_picture_commands = function() {
	this._com_position = [];
	for (var i = 0; i < 10; i++) {
	    this._com_position[i] = this.set_tcp(Moghunter.title_com_pos[i]);
    };
	var _com_index_old = -2;
	this._csel = false;
	this._com_pictures = [];
	this._com_sprites = [];
	this._com_pictures_data = [];
	for (i = 0; i < this._commandWindow._list.length; i++){
		if(false && STEAM_MODE) {
			let j = i;
			if(i >= 3) {
				j++;
				if(j > 5) j = 5;
			}

			let imageName = "Command_" + j;
			this._com_pictures.push(ImageManager.loadTitle2(imageName));
			this._com_sprites.push(new Sprite(this._com_pictures[i]));
			this.addChild(this._com_sprites[i]);
		}
		else {
			let imageName = "Command_" + i;
			if(i === 3) {
				if(STEAM_MODE) imageName += '_Steam';
				else if(TextManager.isJapanese) imageName += '_JP';
			}
			this._com_pictures.push(ImageManager.loadTitle2(imageName));
			this._com_sprites.push(new Sprite(this._com_pictures[i]));
			this.addChild(this._com_sprites[i]);
		}
	};
};

//==============================
// * Refresh Picture Command
//==============================
Scene_Title.prototype.refresh_picture_command = function() {
	this._com_index_old = this._commandWindow._index;
	for (i = 0; i < this._com_sprites.length; i++){
		if (this._commandWindow._index != i) {
        var ch = this._com_pictures[i].height / 2;
		}
		else {
		var ch = 0;
      	}
		this.cpsx = [this._com_position[i][0],this._com_position[i][1]];
		if (this._commandWindow._list[i].symbol === 'continue' && !this._comSave) {this._com_sprites[i].opacity = 160};
		this._com_sprites[i].setFrame(0, ch, this._com_pictures[i].width, this._com_pictures[i].height / 2);
		this._com_sprites[i].x = this.cpsx[0];
		this._com_sprites[i].y = this.cpsx[1];
		this._com_pictures_data[i] = [this._com_sprites[i].x,this._com_pictures[i].width ,this._com_sprites[i].y,this._com_pictures[i].height / 2 ];
	};
};

//==============================
// * Update Picture Commands
//==============================
Scene_Title.prototype.update_picture_commands = function() {
	if (this._com_index_old != this._commandWindow._index) { this.refresh_picture_command()};
	if (TouchInput.isTriggered()) {
		for (i = 0; i < this._com_sprites.length; i++){
			if (this.on_picture_com(i) && !this._csel ) {
				this._commandWindow._index = i;	 this._commandWindow.processOk();
	            if (this._commandWindow.isCommandEnabled(i)) {this._csel = true};
		   };
		};
	};
	if (this._cursor) {this.updateCursor()};
};

//==============================
// * On Picture Com
//==============================
Scene_Title.prototype.on_picture_com = function(index) {
	 if (TouchInput.x < this._com_pictures_data[index][0]) { return false};
	 if (TouchInput.x > this._com_pictures_data[index][0] + this._com_pictures_data[index][1]) { return false};
	 if (TouchInput.y < this._com_pictures_data[index][2]) { return false};
	 if (TouchInput.y > this._com_pictures_data[index][2] + this._com_pictures_data[index][3]) { return false};
	 return true;
};

//==============================
// * Create Foreground
//==============================
var _mog_titlecom_createForeground = Scene_Title.prototype.createForeground;
Scene_Title.prototype.createForeground = function() {
	_mog_titlecom_createForeground.call(this);
	if (String(Moghunter.title_sprite) === "true") {this.createTitleSprite();}
};

//==============================
// * Create Title Sprite
//==============================
Scene_Title.prototype.createTitleSprite = function() {
	if (this._gameTitleSprite) {this.removeChild(this._gameTitleSprite)};
	let titleName = 'Title_EN';

	if(STEAM_MODE) {
		titleName = 'Title_Steam_EN';
		if(TextManager.isJapanese) titleName = 'Title_Steam_JP';
	}
	else {
		titleName = 'Title_EN';
		if(TextManager.isJapanese) titleName = 'Title_JP';
	}

    this._gameTitleSprite = new Sprite(ImageManager.loadTitle2(titleName));
    this.addChild(this._gameTitleSprite);
	this._gameTitleSprite.x = Moghunter.title_x;
	this._gameTitleSprite.y = Moghunter.title_y;
};


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

/*:
 * @plugindesc 【ver.3.10】選択肢の機能拡張
 * @author 木星ペンギン
 *
 * @help ※[]内は未設定でも動作します。
 * プラグインコマンド:
 *   ChoicePos x y[ row]    # 選択肢の位置(x,y)と行数(row)指定
 *   ChoiceVariableId n     # 選択肢のデフォルト位置を変数n番にする
 *   ChoiceRect x y width height
 *                          # 選択肢の座標とサイズを指定
 *   ChoiceUnderMessage     # 選択肢をメッセージの下に表示
 *
 * ※ プラグインコマンドにて指定する値には変数が使用できます。
 *    v[n] と記述することでn番の変数の値を参照します。
 *
 * 注釈:
 *   選択肢ヘルプ             # 各項目の下に設定することでヘルプを表示させる
 *
 * 選択肢テキスト:
 *   if(条件)                # 条件が偽になると項目が表示されなくなる
 *   en(条件)                # 条件が偽になると項目が選択不可
 *
 * ================================================================
 * ▼ 使い方
 * --------------------------------
 *  〇 選択肢を増やす
 *   イベントコマンド『選択肢の表示』を続けて配置すると
 *   一つの選択肢にまとめられます。
 *   まとめたくない場合は、間に注釈などを入れることで
 *   通常通り分けることができます。
 *
 *   『デフォルト』の処理は、なし以外を設定したものが適用されます。
 *   『デフォルト』の処理が複数ある場合、
 *   後に設定された選択肢のものが適用されます。
 *
 *   『キャンセル』の処理は、禁止以外を設定したものが適用されます。
 *   『キャンセル』の処理が複数ある場合、
 *   後に設定された選択肢のものが適用されます。
 *
 *  『背景』と『ウィンドウ位置』は後の選択肢のものが適用されます。
 *
 *
 * ================================================================
 * ▼ プラグインコマンド 詳細
 * --------------------------------
 *  〇 ChoicePos x y[ row]
 *      x   : 選択肢ウィンドウのX座標
 *      y   : 選択肢ウィンドウのY座標
 *      row : 選択肢ウィンドウの行数。未設定の場合はすべて表示
 *
 *   次に表示する選択肢の位置(x,y)と行数(row)指定します。
 *
 * --------------------------------
 *  〇 ChoiceVariableId n
 *      n : 変数番号
 *
 *   次に表示する選択肢のデフォルト位置を変数の値にします。
 *   さらに現在のカーソル位置を変数に入れます。
 *
 *   カーソル位置は最初の選択肢が上から0～5、次の選択肢は10～15と、
 *   選択肢毎に+10されます。
 *
 *   変数に入った値の項目が表示されない場合、なしと同じ処理をします。
 *
 * --------------------------------
 *  〇 ChoiceRect x y width height
 *      x      : X座標
 *      y      : Y座標
 *      width  : 幅
 *      height : 高さ
 *
 *   次に表示する選択肢の座標とサイズを指定します。
 *
 *   各項目、未設定もしくは-1を指定した場合、通常の値が適用されます。
 *
 * --------------------------------
 *  〇 ChoiceUnderMessage
 *
 *   次に表示する選択肢をメッセージウィンドウ内に表示させます。
 *
 *   この機能は[文章の表示]と併用しなければ機能しません。
 *   [文章の表示]の前に実行してください。
 *
 *   選択肢ウィンドウの[背景]は設定したものが適用されます。
 *
 *
 * ================================================================
 * ▼ 選択肢テキスト 詳細
 * --------------------------------
 *  〇 項目が表示される条件の設定
 *   選択肢の文章中に
 *     if(条件)
 *   と入れ、その条件が偽になると項目が表示されなくなります。
 *
 *   『デフォルト』の項目が表示されない場合の動作は、
 *   プラグインパラメータの[Disabled Index]にて設定できます。
 *
 *   『キャンセル』の項目が表示されない場合、禁止と同じ処理をします。
 *
 *   条件内では s でスイッチ、v で変数を参照できます。
 *
 *     例：if(s[1]) とした場合
 *          => スイッチ１番がONで表示、OFFで非表示。
 *        if(!s[2]) とした場合
 *          => スイッチ２番がOFFで表示、ONで非表示。
 *        if(v[5]>0) とした場合
 *          => 変数５番が0より大きければ表示、0以下で非表示。
 *
 *     変数で使える不等号
 *       === : 等しい
 *       !== : 等しくない
 *       <   : より小さい
 *       <=  : より小さいまたは等しい
 *       >   : より大きい
 *       >=  : より大きいまたは等しい
 *
 *     条件式はeval関数で処理されているため、他演算子も使用できます。
 *
 * --------------------------------
 *  〇 項目を半透明で表示する条件の設定
 *   選択肢の文章中に
 *     en(条件)
 *   と入れ、その条件が偽になると項目が半透明で表示されます。
 *   半透明となった項目は選択できなくなります。
 *
 *   条件は上の『項目が表示される条件の設定』と同じです。
 *
 *   『キャンセル』の項目が半透明の場合、ブザーが鳴ります。
 *
 *
 * ================================================================
 * ▼ プラグインパラメータ 詳細
 * --------------------------------
 *  〇 Disabled Index
 *
 *   [デフォルト]となる項目がif(条件)により非表示となった場合、
 *   デフォルト位置をどこにするかを設定します。
 *
 *     none : [なし]と同じ
 *     top  : 先頭の項目
 *
 * --------------------------------
 *  〇 Plugin Commands / Event Comment
 *
 *   プラグインコマンドや注釈で使用するコマンドは、
 *   プラグインパラメータから変更できます。
 *
 *   コマンドを短くしたり日本語にしたりなどして、
 *   自分が使いやすいようにしてください。
 *
 *   プラグインコマンドのみ、変更後もデフォルトのコマンドでも動作します。
 *
 *
 * ================================================================
 * ▼ その他
 * --------------------------------
 *  〇 プラグインコマンドの実行タイミング
 *   プラグインコマンドを使用する場合、[選択肢の表示]の前に実行するのが
 *   好ましいです。
 *   ただし、メッセージウィンドウを表示したまま選択肢の処理を実行したい場合、
 *   [文章の表示]より前にプラグインコマンドを実行してください。
 *
 * --------------------------------
 *  〇 ヘルプメッセージの表示
 *   各選択肢項目の下に注釈で以下の文字列を入れると、
 *   続きの文章をヘルプメッセージとしてカーソルを合わせたときに
 *   標示させることができます。
 *
 *     選択肢ヘルプ
 *
 *   ※注意点
 *    ヘルプメッセージは[文章の表示]と同じ機能を使っているため、
 *    制御文字が使用できます。
 *    ただし、\!と\^は使用できません。
 *
 * ================================
 * 制作 : 木星ペンギン
 * URL : http://woodpenguin.blog.fc2.com/
 *
 * @param maxPageRow
 * @type number
 * @desc 1ページに表示される行数
 * @default 6
 *
 * @param Disabled Index
 * @type select
 * @option none
 * @option top
 * @desc [デフォルト]となる選択肢が表示されない場合のデフォルト位置
 * @default none
 *
 *
 * @param === Command ===
 *
 * @param Plugin Commands
 * @type struct<Plugin>
 * @desc プラグインコマンド名
 * @default {"ChoicePos":"ChoicePos","ChoiceVariableId":"ChoiceVariableId","ChoiceRect":"ChoiceRect","ChoiceUnderMessage":"ChoiceUnderMessage"}
 * @parent === Command ===
 *
 * @param Event Comment
 * @type struct<EventComment>
 * @desc イベントの注釈で使うコマンド名
 * @default {"ChoiceHelp":"選択肢ヘルプ"}
 * @parent === Command ===
 *
 */

/*~struct~Plugin:
 * @param ChoicePos
 * @desc 選択肢の位置(x,y)と行数(row)指定
 * @default ChoicePos
 *
 * @param ChoiceVariableId
 * @desc 選択肢のデフォルト位置を変数n番にする
 * @default ChoiceVariableId
 *
 * @param ChoiceRect
 * @desc 選択肢の座標とサイズ(x,y,width,height)指定
 * @default ChoiceRect
 *
 * @param ChoiceUnderMessage
 * @desc 選択肢をメッセージの下に表示
 * @default ChoiceUnderMessage
 *
 */

/*~struct~EventComment:
 * @param ChoiceHelp
 * @desc 各項目の下に設定することでヘルプを表示させる
 * @default 選択肢ヘルプ
 */

(function() {

const MPPlugin = {};

{

    let parameters = PluginManager.parameters('MPP_ChoiceEX');

    MPPlugin.maxPageRow = Number(parameters['maxPageRow']);
    MPPlugin.DisabledIndex = parameters['Disabled Index'];

    MPPlugin.PluginCommands = JSON.parse(parameters['Plugin Commands']);
    MPPlugin.EventComment = JSON.parse(parameters['Event Comment']);

}

const Alias = {};

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

//15
Alias.GaMe_clear = Game_Message.prototype.clear;
Game_Message.prototype.clear = function() {
    Alias.GaMe_clear.apply(this, arguments);
    this._choiceEnables = [];
    this._choiceResults = [];
    this._helpTexts = [];
    this._choiceX = -1;
    this._choiceY = -1;
    this._choiceWidth = -1;
    this._choiceHeight = -1;
    this._choiceMaxRow = MPPlugin.maxPageRow;
    this._choiceVariableId = 0;
    this.choiceUnderMes = false;
};

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.setChoiceHelpTexts = function(texts) {
    this._helpTexts = texts;
};

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

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.shiftLine = function(height) {
    this._choiceY += height;
    this._choiceHeight -= height;
};

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

//336
Game_Interpreter.prototype.setupChoices = function(params) {
    var data = {
        choices: [],
        enables: [],
        results: [],
        helpTexts: [],
        cancelType: -1,
        defaultType: -1,
        positionType: 0,
        background: 0
    };
    data = this.addChoices(params, this._index, data, 0);
    if (data.choices.length > 0) {
        var helpTexts = [];
        if (data.helpTexts.length > 0) {
            helpTexts = data.results.map( i => data.helpTexts[i] );
        }
        var cancelType = -1;
        if (data.cancelType.mod(10) === 8 || data.results.contains(data.cancelType)) {
            data.results.push(data.cancelType);
            cancelType = data.choices.length;
        }
        var index = data.defaultType;
        if ($gameMessage._choiceVariableId > 0) {
            index = $gameVariables.value($gameMessage._choiceVariableId);
        }
        var defaultType = data.results.indexOf(index);
        if (index >= 0 && defaultType < 0 && MPPlugin.DisabledIndex === "top")  {
            defaultType = 0;
        }
        $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] = data.results[n] );
    } else {
        this._branch[this._indent] = -1;
    }
};

Game_Interpreter.prototype.addChoices = function(params, i, data, d) {
    var regIf = /\s*if\((.+?)\)/;
    var regEn = /\s*en\((.+?)\)/;
    for (var n = 0; n < params[0].length; n++) {
        var str = params[0][n];
        if (regIf.test(str)) {
            str = str.replace(regIf, '');
            if (RegExp.$1 && !this.evalChoice(RegExp.$1)) continue;
        }
        var enable = true;
        if (regEn.test(str)) {
            str = str.replace(regEn, '');
            enable = this.evalChoice(RegExp.$1);
        }
        data.choices.push(str);
        data.enables.push(enable);
        data.results.push(n + d);
    }
    var cancelType = params[1];
    if (cancelType !== -1) {
        data.cancelType = cancelType + d;
    }
    var defaultType = params.length > 2 ? params[2] : 0;
    if (defaultType >= 0) {
        data.defaultType = defaultType + d;
    }
    data.positionType = params.length > 3 ? params[3] : 2;
    data.background = params.length > 4 ? params[4] : 0;
    var command;
    for (;;) {
        i++;
        command = this._list[i];
        if (!command) break;
        if (command.indent === this._indent) {
            if (command.code === 402) {
                this.getHelpText(command.parameters[0] + d, i + 1, data);
            } else if (command.code === 404) {
                break;
            }
        }
    }
    command = this._list[i + 1];
    if (command && command.code === 102) {
        this.addChoices(command.parameters, i + 1, data, d + 10);
    }
    return data;
};

//REM
Game_Interpreter.prototype.getHelpText = function(c, i, data) {
    //var command = MPPlugin.EventComment.ChoiceHelp || '選択肢ヘルプ';
	let command = 'description';
    if (this._list[i].code === 108 && this._list[i].parameters[0] === command) {
        var texts = [];
        while (this._list[i + 1].code === 408) {
            i++;
            texts.push(this._list[i].parameters[0]);
        }
        data.helpTexts[c] = texts;
    }
};

Game_Interpreter.prototype.evalChoice = function(formula) {
    try {
        var s = $gameSwitches._data;
        var formula2 = formula.replace(/v\[(\d+)\]/g,
            (match, p1) => $gameVariables.value(parseInt(p1)) );
        return !!eval(formula2);
    } catch (e) {
        alert("条件エラー \n\n " + formula);
        return true;
    }
};

//362
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;
};

//1739
Alias.GaIn_pluginCommand = Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function(command, args) {
    Alias.GaIn_pluginCommand.apply(this, arguments);
    var args2 = this.mppPluginCommandArgs(args);
    switch (command) {
        case MPPlugin.PluginCommands.ChoicePos:
        case 'ChoicePos':
            var x = args2[0];
            var y = args2[1];
            var row = args2[2] || 99;
            $gameMessage.setChoicePos(x, y, row);
            break;
        case MPPlugin.PluginCommands.ChoiceVariableId:
        case 'ChoiceVariableId':
            $gameMessage.setChoiceVariableId(args2[0]);
            break;
        case MPPlugin.PluginCommands.ChoiceRect:
        case 'ChoiceRect':
            var x = (args2[0] === undefined ? -1 : args2[0]);
            var y = (args2[1] === undefined ? -1 : args2[1]);
            var width = (args2[2] === undefined ? -1 : args2[2]);
            var height = (args2[3] === undefined ? -1 : args2[3]);
            $gameMessage.setChoiceRect(x, y, width, height);
            break;
        case MPPlugin.PluginCommands.ChoiceUnderMessage:
        case 'ChoiceUnderMessage':
            $gameMessage.choiceUnderMes = true;
            break;
    }
    return true;
};

Game_Interpreter.prototype.mppPluginCommandArgs = function(args) {
    var v = $gameVariables._data;
    return args.map(function(arg) {
        try {
            return eval(arg) || 0;
        } catch (e) {
            return arg;
        }
    });
};

//-----------------------------------------------------------------------------
// Window

Window.prototype.isClearWindowRect = function() {
    return true;
};

//-----------------------------------------------------------------------------
// WindowLayer

//7100
Alias.WiLa__canvasClearWindowRect = WindowLayer.prototype._canvasClearWindowRect;
WindowLayer.prototype._canvasClearWindowRect = function(renderSession, window) {
    if (window.isClearWindowRect())
        Alias.WiLa__canvasClearWindowRect.apply(this, arguments);
};

//7162
Alias.WiLa__maskWindow = WindowLayer.prototype._maskWindow;
WindowLayer.prototype._maskWindow = function(window, shift) {
    Alias.WiLa__maskWindow.apply(this, arguments);
    if (!window.isClearWindowRect()) {
        var rect = this._windowRect;
        rect.x = 0;
        rect.y = 0;
        rect.width = 0;
        rect.height = 0;
    }
};

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

Window_ChoiceList.prototype.isClearWindowRect = function() {
    return !this._underMessage;
};

if (Window_ChoiceList.prototype.hasOwnProperty('close')) {
    Alias.WiChLi_close = Window_ChoiceList.prototype.close
}
Window_ChoiceList.prototype.close = function() {
    if ($gameMessage.isHelp()) this._messageWindow.onShowFast();
    var _super = Alias.WiChLi_close || Window_Command.prototype.close;
    _super.apply(this, arguments);
};

if (Window_ChoiceList.prototype.hasOwnProperty('select')) {
    Alias.WiChli_select = Window_ChoiceList.prototype.select;
}
Window_ChoiceList.prototype.select = function(index) {
    var variableId = $gameMessage._choiceVariableId;
    if (index !== this.index() && variableId > 0) {
        var results = $gameMessage._choiceResults;
        $gameVariables.setValue(variableId, results[index]);
    }
    var _super = Alias.WiChli_select = Window_Command.prototype.select
    _super.apply(this, arguments);
};

//34
Alias.WiChLi_updatePlacement = Window_ChoiceList.prototype.updatePlacement;
Window_ChoiceList.prototype.updatePlacement = function() {
    Alias.WiChLi_updatePlacement.apply(this, arguments);
    if ($gameMessage._choiceWidth >= 0) {
        this.width = Math.min($gameMessage._choiceWidth, Graphics.boxWidth);
    }
    if ($gameMessage._choiceHeight >= 0) {
        this.height = Math.min($gameMessage._choiceHeight, Graphics.boxHeight);
    }
    if ($gameMessage._choiceX >= 0) {
        this.x = Math.min($gameMessage._choiceX, Graphics.boxWidth - this.width);
    }
    if ($gameMessage._choiceY >= 0) {
        this.y = Math.min($gameMessage._choiceY, Graphics.boxHeight - this.height);
    }
    this._underMessage = $gameMessage.choiceUnderMes;
};

//67
Window_ChoiceList.prototype.numVisibleRows = function() {
    return Math.min($gameMessage.choices().length, $gameMessage._choiceMaxRow);
};

//103
Window_ChoiceList.prototype.makeCommandList = function() {
    var choices = $gameMessage.choices();
    var enables = $gameMessage._choiceEnables;
    for (var i = 0; i < choices.length; i++) {
        this.addCommand(choices[i], 'choice', enables[i]);
    }
};

//110
Alias.WiChLi_drawItem = Window_ChoiceList.prototype.drawItem;
Window_ChoiceList.prototype.drawItem = function(index) {
    this.changePaintOpacity(this.isCommandEnabled(index));
    Alias.WiChLi_drawItem.apply(this, arguments);
};

//123
Alias.WiChLi_callOkHandler = Window_ChoiceList.prototype.callOkHandler;
Window_ChoiceList.prototype.callOkHandler = function() {
    Alias.WiChLi_callOkHandler.apply(this, arguments);
    this._messageWindow.forceClear();
};

//129
Alias.WiChLi_callCancelHandler = Window_ChoiceList.prototype.callCancelHandler;
Window_ChoiceList.prototype.callCancelHandler = function() {
    Alias.WiChLi_callCancelHandler.apply(this, arguments);
    this._messageWindow.forceClear();
};

if (Window_ChoiceList.prototype.hasOwnProperty('processCancel')) {
    Alias.WiChLi_processCancel = Window_ChoiceList.prototype.processCancel
}
Window_ChoiceList.prototype.processCancel = function() {
    var type = $gameMessage.choiceCancelType();
    var results = $gameMessage._choiceResults;
    var index = results.indexOf(results[type]);
    if (this.isCancelEnabled() && index !== type && !this.isCommandEnabled(index)) {
        this.playBuzzerSound();
    } else {
        var _super = Alias.WiChLi_processCancel || Window_Command.prototype.processCancel;
        _super.apply(this, arguments);
    }
};

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

Window_ChoiceList.prototype.updateHelp = function() {
    this._messageWindow.forceClear();
    var texts = $gameMessage._helpTexts[this.index()];
    $gameMessage._texts = texts ? texts.clone() : [''];
    this._messageWindow.startMessage();
};

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

//109
Alias.WiMe_updatePlacement = Window_Message.prototype.updatePlacement;
Window_Message.prototype.updatePlacement = function() {
    Alias.WiMe_updatePlacement.apply(this, arguments);
    this.clearUnderChoice();
};

Window_Message.prototype.clearUnderChoice = function() {
    if ($gameMessage.choiceUnderMes) {
        var x = this.x + this.standardPadding();
        x += this._textState.left || 0;
        var y = this.y + 4;
        var height = this.windowHeight();
        $gameMessage.setChoiceRect(x, y, -1, height);
    }
};

if (Window_Message.prototype.hasOwnProperty('processNewLine')) {
    Alias.WiMe_processNewLine = Window_Message.prototype.processNewLine;
}
Window_Message.prototype.processNewLine = function(textState) {
    if ($gameMessage.choiceUnderMes) $gameMessage.shiftLine(textState.height);
    var _super = Alias.WiMe_processNewLine || Window_Base.prototype.processNewLine;
    _super.apply(this, arguments);
};

//149
Alias.WiMe_updateInput = Window_Message.prototype.updateInput;
Window_Message.prototype.updateInput = function() {
    if ($gameMessage.isHelp() && this._textState) return false;
    return Alias.WiMe_updateInput.apply(this, arguments);
};

//196
Alias.WiMe_onEndOfText = Window_Message.prototype.onEndOfText;
Window_Message.prototype.onEndOfText = function() {
    if ($gameMessage.isHelp() && !this._choiceWindow.active) {
        this.startInput();
    } else {
        Alias.WiMe_onEndOfText.apply(this, arguments);
    }
};

//207
Alias.WiMe_startInput = Window_Message.prototype.startInput;
Window_Message.prototype.startInput = function() {
    if (this._choiceWindow.active) return true;
    if ($gameMessage.isChoice() && $gameMessage.choiceUnderMes)
        $gameMessage.shiftLine(this._textState.height);
    return Alias.WiMe_startInput.apply(this, arguments);
};

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

Window_Message.prototype.onShowFast = function() {
    this._showFast = true;
};

//243
Alias.WiMe_newPage = Window_Message.prototype.newPage;
Window_Message.prototype.newPage = function(textState) {
    Alias.WiMe_newPage.apply(this, arguments);
    this.clearUnderChoice();
};

})();