GRB NewGamePlus MultiItem

Матеріал з РПГ.укр
Перейти до: навігація, пошук

GRB_NewGamePlus_MultiItem — варіант плагіна GRB_NewGamePlus для RPG Maker MV та RPG Maker MZ від команди Гарбата. Він дозволяє додавати на титульний екран довільну кількість команд «Нова гра+» після основного сюжету гри. Кожна така команда дозволяє почати гру як звичайно, але з іншої локації.

Завантажити плагін можна тут: GRB_NewGamePlus_MultiItem.js.

Ліцензія[ ]

Плагін розповсюджується згідно з ліцензією Creative Commons Zero, тобто автори відмовляються від авторських прав (настільки, наскільки це взагалі можливо зробити згідно з законодавством).

Код[ ]

Показати код плагіну

//==============================================================================
// GRB_NewGamePlus_MultiItem.js
//==============================================================================

/*:
 * @target MV MZ
 * @plugindesc Adds new menu items accessible after completing the game
 * @author Garbata Team
 * @url https://rpgukr.one/GRB_NewGamePlus_MultiItem
 *
 * @command newgame+ ID on
 * @text NewGame+ ID ON (show one)
 * @desc Enables the "New Game+" menu item
 
 * @arg menuItemId
 * @text Menu item ID
 * @desc ID of menu item to enable (chosen in plugin settings).
 *
 * @command newgame+ ID off
 * @text NewGame+ ID OFF (hide one)
 * @desc Disables the "New Game+" menu item
 *
 * @arg menuItemId
 * @text Menu item ID
 * @desc ID of menu item to disable (chosen in plugin settings).
 *
 * @command newgame+ on
 * @text NewGame+ ON (show all)
 * @desc Enables all the "New Game+" menu items
 *
 * @command newgame+ off
 * @text NewGame+ OFF (hide all)
 * @desc Disables all the "New Game+" menu items
 *
 * @command newgame on
 * @text NewGame ON (re-show default)
 * @desc Re-enables the standard "New Game" menu item
 *
 * @command newgame off
 * @text NewGame OFF (hide default)
 * @desc Disables the standard "New Game" menu item
 *
 * @param menuItems
 * @text New Game+ menu items
 * @type struct<NewGamePlusItem>[]
 * @desc “New Game+” menu items that can be enabled or disabled during the gameplay.
 *
 * @help
 * This plugin is ALTERNATIVE version of GRB_NewGamePlus plugin that allows
 * creating several menu items. It should be used INSTEAD of GRB_NewGamePlus,
 * they shouldn't both be installed at the same time.
 *
 * ----------------------------------------------------------------------------
 *
 * New Game+ is a special kind of new game that starts after the player has
 * completed the game one time.
 *
 * This plugin allows to add *several* such menu items, and each can be turned
 * on or off separately. This plugin also allows to turn on and off the default
 * New Game menu item.
 *
 * All New Game+ the main menu that is invisible by default, but becomes
 * visible later. The text of this menu item is set by the "Menu item text"
 * parameter.
 *
 * These menu items start the game like usual, but from a different place.
 * This place is specified by "Start map ID", "Start tile X" and "Start tile Y"
 * parameters. They can be obtained as follows:
 *
 * - Open the map which you want to use for the start position.
 * - Switch to the Event mode by pressing F6.
 * - Left-click on the place where you want to start the game in the New Game+
 * mode.
 * - Now, look at the lowest part of the window screen. There is a status bar
 * separated into several labels, like this:
 *  |               |  002:Рыбацкая деревня (40x40)   | 100% | 18,12 |       |
 * - The first (leftmost) label is always empty.
 * - Start map ID is the second number in the second label (before :), use it
 * in the plugin settings
 * - The third item is zoom, it can be ignored
 * - The forth item contans X and Y coordinates, separated by comma.
 * Use the first number as Start Map X, and the second number as Start Map Y.
 *
 * To enable or disable the "New Game+" menu item, use the "Plugin Command"
 * event command. In MV, use the following commands:
 * newgame+ ID on
 * newgame+ ID off
 * Replace ID with the ID set in menu item settings.
 *
 * For example, if ID is “newgameplus”, the MV plugin commands will be
 * as follows:
 * newgame+ newgameplus on
 * newgame+ newgameplus off
 *
 * If you omit the ID, you will enable or disable ALL the New Game+ items:
 * newgame+ on
 * newgame+ off
 *
 * To enable or disable the standard “New Game” menu item, use “newgame on” or
 * “newgame off” event command.
 *
 * In RPG Maker MZ, select the event command from the list.
 *
 * This is version 1.0 of the plugin, published at 2025-03-23.
 *
 * Thanks to Tarwix <https://tarwix.itch.io/> for the help with a config bug.
 *
 * This plugin is placed into public domain according to the CC0 public domain
 * dedication. See https://creativecommons.org/publicdomain/zero/1.0/ for more
 * information.
 */
/*~struct~NewGamePlusItem:
 * @param id
 * @text ID
 * @desc Code that will be used in "newgame+ ID on” and "newgame+ ID off” commands. Should not contain spaces.
 * @type text
 * @default newgameplus
 *
 * @param menuItemText
 * @text Menu item text
 * @desc Label of the new menu item in the title screen
 * @type text
 * @default New Game+
 *
 * @param mapId
 * @text Start map ID
 * @desc From which map will New Game+ start
 * @type number
 * @min 1
 * @max 999
 *
 * @param x
 * @text Start tile X
 * @desc Number of tiles from leftmost tile column to the tile
 * where the New Game+ starts.
 * @type number
 * @min 0
 * @max 255
 *
 * @param y
 * @text Start tile Y
 * @desc Number of tiles from topmost tile row to the tile
 * where the New Game+ starts.
 * @type number
 * @min 0
 * @max 255
 */
/*:uk
 * @target MV MZ
 * @plugindesc Додає нові пункти меню, доступні пісня перемоги
 * @author Команда Гарбата
 * @url https://рпг.укр/GRB_NewGamePlus_MultiItem
 *
 * @command newgame+ ID on
 * @text НоваГра+ ID Увімкнена (один пункт)
 * @desc Показує один пункт меню «Нова гра+»
 
 * @arg menuItemId
 * @text ID пункта меню
 * @desc ID пункта меню, який буде увімкнено (вказується в налаштуваннях пунта меню).
 *
 * @command newgame+ ID off
 * @text НоваГра+ ID ВИМкнена (один пункт)
 * @desc Приховує один пункт меню «Нова гра+»
 *
 * @arg menuItemId
 * @text ID пункта меню
 * @desc ID пункта меню, який буде сховано (вказується в налаштуваннях пунта меню).
 *
 * @command newgame+ on
 * @text НоваГра+ УВімкнені (показати всі)
 * @desc Показує всі пункти меню «Нова гра+»
 *
 * @command newgame+ off
 * @text НоваГра+ ВИМкнена (приховати всі)
 * @desc Приховує всі пункти меню «Нова гра+»
 *
 * @command newgame on
 * @text НоваГра УВімкнена (показати стандартну)
 * @desc Повторно вмикає стандартний пункт меню «Нова гра»
 *
 * @command newgame off
 * @text НоваГра ВИМкнена (сховати стандартну)
 * @desc Вимикає стандартний пункт меню «Нова гра»
 *
 * @param menuItems
 * @text Пункти меню «Нова гра+»
 * @type struct<NewGamePlusItem>[]
 * @desc Пункти меню «Нова гра+», які можна показати та приховати під час гри.
 *
 * @help
 * Це плагін — це АЛЬТЕРНАТИВНА версія плагіну GRB_NewGamePlus, яка дозволяє
 * додавати декілька пунктів меню. Це ЗАМІНА для GRB_NewGamePlus, їх не треба
 * встановлювати одночасно.
 *
 * ----------------------------------------------------------------------------
 *
 * Нова гра+ — це особливий початок гри, який стає доступним після перемоги
 * в основній грі.
 *
 * Цей плагін дозволяє додати *декілька* таких пунктів меню, і кожен можна буде
 * показати або приховати окремо. Цей плагін також дозволяє приховати та
 * показати стандартний пункт «Нова гра».
 *
 * Усі пукнти меню Нова гра+ на початку гри приховані, і стають доступними
 * пізніше. Текст цих пунктів меню задається в параметрах «Текст пункту меню».
 *
 * Ці пункти меню починають гру так, як і звичайний, але в іншому місці. Це
 * місце вказується параметрами «№ початкової карти», «X початкової клітини»
 * та «Y початкової клітини». Їх можна довідатися таким чином:
 *
 * - Відкрийте карту, на якій ви хочете починати Нову гру+.
 * - Перемикніться на режим Подій клавішею F6.
 * - Натисніть лівою кнопкою миші по місцю, де ви хочете починати Нову гру+.
 * - Після цього подивіться на нижню частину екрана. Там є рядок стану,
 * розділений на декілька пунктів, приблизно таким чином:
 *  |               |  002:Рибальське село (40x40)   | 100% | 18,12 |       |
 * - Перший (найлівіший) пункт завжди пустий.
 * - В другому пункті можна побачити номер початкової карти (перед :), вкажіть
 * його в налаштуваннях плагіну
 * - Третій пункт — масштаб, пропустіть його
 * - В четвертому пункті вказано координати X та Y, розділені комою.
 * Вкажіть перше число як X початкової клітини, а друге — як Y початкової
 * клітини.
 *
 * Щоб увімкнути або вимкнути пункт меню «Нова гра+», використовуйте команду
 * подій «Команда плагіну». В MV використовуйте такі команди:
 * нова_гра+ ID увімкнена
 * нова_гра+ ID вимкнена
 * Замініть ID на ID, вказаний в налаштуваннях пункта меню.
 *
 * Наприклад, якщо ID — «newgameplus», команда плагіна для MV виглядатиме так:
 * нова_гра+ newgameplus увімкнена
 * нова_гра+ newgameplus вимкнена
 *
 * Якщо не вказувати ID, можна показати або приховати ВСІ пункти «Нова гра+»:
 * нова_гра+ увімкнена
 * нова_гра+ вимкнена
 *
 * Щоб показати або приховати стандартний пункт меню «Нова гра», використовуйте
 * команди «нова_гра увімкнена» та «нова_гра вимкнена».
 *
 * У RPG Maker MZ команди вибираються зі списку.
 *
 * Це версія плагіну 1.0, опублікована 2025-03-23.
 *
 * Дякую Tarwix <https://tarwix.itch.io/> за допомогу з помилкою з читанням
 * конфігурації.
 *
 * Цей плагін передано до суспільного надбання згідно з CC0. Детальніше див.
 * на сторінці https://creativecommons.org/publicdomain/zero/1.0/deed.uk
 */
/*~struct~NewGamePlusItem:uk
 * @param id
 * @text ID
 * @desc Код, який буде використовуватися в командах «НоваГра+ ID УВімкнено» та «НоваГра+ ID ВИМкенено». Без пробілів
 * @type text
 * @default newgameplus
 *
 * @param menuItemText
 * @text Текст пункту меню
 * @desc Текст нового пункту меню на титульному екрані
 * @type text
 * @default Нова гра+
 *
 * @param mapId
 * @text № початкової карти
 * @desc З якої карти починатиметься Нова гра+
 * @type number
 * @min 1
 * @max 999
 *
 * @param x
 * @text X початкової клітини
 * @desc Кількість клітин від найлівішого стовпчика клітин
 * до клітини, де починатиметься Нова гра+.
 * @type number
 * @min 0
 * @max 255
 *
 * @param y
 * @text Y початкової клітини
 * @desc Кількість клітин від верхнього рядка клітин
 * до клітини, де починатиметься Нова гра+.
 * @type number
 * @min 0
 * @max 255
 */
/*:be
 * @target MV MZ
 * @plugindesc Дадае новыя пункты меню, даступныя пасля перамогі
 * @author Каманда Гарбата
 * @url https://рпг.укр/GRB_NewGamePlus_MultiItem
 *
 * @command newgame+ ID on
 * @text Новая_гульня+ ID уключаная (адзін пункт)
 * @desc Паказвае адзін пункт меню «Новая гульня+»
 
 * @arg menuItemId
 * @text ID пункта меню
 * @desc ID пункта меню, які будзе ўключаны (задаецца ў налаштаваннях пункта меню).
 *
 * @command newgame+ ID off
 * @text Новая_гульня+ выключаная (адзін пункт)
 * @desc Прыхоўвае адзін пункт меню «Новая гульня+»
 *
 * @arg menuItemId
 * @text ID пункта меню
 * @desc ID пункта меню, які будзе схаваны (задаецца ў налаштаваннях пункта меню).
 *
 * @command newgame+ on
 * @text Новая_гульня+ уключаная (паказаць усе)
 * @desc Паказвае ўсе пункты меню «Новая гульня+»
 *
 * @command newgame+ off
 * @text Новая_гульня+ выключаная (схаваць усе)
 * @desc Прыхоўвае ўсе пункты меню «Новая гульня+»
 *
 * @command newgame on
 * @text Новая_гульня уключаная (паказаць стандартную)
 * @desc Паўторна ўключае стандартны пункт меню «Новая гульня»
 *
 * @command newgame off
 * @text Новая_гульня выключаная (схаваць стандартную)
 * @desc Прыхоўвае стандартны пункт меню «Новая гульня»
 *
 * @param menuItems
 * @text Пункты меню «Новая гульня+»
 * @type struct<NewGamePlusItem>[]
 * @desc Пункты меню «Нова гра+», якія можна паказаць ці схаваць падчас гульні
 *
 * @help
 * Гэты плагін — гэта АЛЬТЭРНАТЫЎНАЯ версія плагіна GRB_NewGamePlus, якая
 * дазваляе дадаваць некалькі пунктаў меню. Гэта ЗАМЕНА для GRB_NewGamePlus,
 * іх не трэба ўсталёўваць адначасова.
 *
 * ----------------------------------------------------------------------------
 *
 * Новая гульня+ — гэта асаблівы пачатак гульня, які робіцца даступным пасля
 * перамогі ў асноўнай гульні.
 *
 * Гэты плагін дазваляе дадаць *некалькі* такіх пунктаў меню, і кожны можна 
 * будзе паказаць або прыхаваць асобна. Гэтып лагін таксама дазваляе схаваць
 * ці зноў паказаць стандартны пункт меню «Новая гульня».
 *
 * Усе пункты меню «Новая гульня+» на пачатку гульні прыхаваныя, і стаюць
 * даступнымі пазней. Тэкст гэтых пунктаў задаецца ў параметрах «Тэкст пунктаў
 * меню».
 *
 * Гэтыя пункты меню пачынаюць гульню гэтак жа, як і звычайны пункт «Новая
 * гульня», але ў іншым месцы. Гэта месца задаецца параметрамі «№ пачатковай
 * карты», «X пачатковай клеткі» і «Y пачатковай клеткі». Іх можна даведацца
 * такім чынам:
 *
 * - Адкрыйце карту, на якой вы хочаце пачынаць Новую гульню+.
 * - Пераключыцеся на Рэжым падзей клавішай F6.
 * - Пстрыкніце левай кнопкай мышы па месцы, дзе вы хочаце пачынаць Новую
 * гульню+.
 * - Пасля гэтага паглядзіце на ніжнюю частку экрана. Там ёсць радок стану,
 * падзелены на некалькі пунктаў, прыблізна такім чынам:
 *  |               |  002:Рыбацкая вёска (40x40)   | 100% | 18,12 |       |
 * - Першы (найлявейшы) пункт заўсёды пусты
 * - У другім пункце можна ўбачыць нумар пачатковай карты (перад :), увядзіце
 * яго ў наладках плагіна
 * - Трэці пункт — масштаб, прапусціце яго
 * - У чацвёртым пункце паказваюцца каардынаты X і Y, раздзеленыя коскай.
 * Увядзіце першы лік як X пачатковай клеткі, а другі лік — як Y пачатковай
 * клеткі.
 *
 * Каб уключыць ці выключыць пункт меню «Новая гульня+», выкарыстоўвайце
 * каманду падзей «Каманда плагіна». У MV выкарыстоўвайце такія каманды:
 * новая_гульня+ ID укл
 * новая_гульня+ ID выкл
 * Замяніце ID на ID, указаны у наладах плагіна.
 *
 * Напрыклад, калі ID — «newgameplus», каманда плагіна для MV будзе выгдядаць
 * так:
 * новая_гульня+ newgameplus укл
 * новая_гульня+ newgameplus выкл
 *
 * Калі не ўказваць ID, можна паказаць або прыхаваць УСЕ пункты «Новая
 * гульня+»:
 * новая_гульня+ укл
 * новая_гульня+ выкл
 *
 * Каб паказаць або прыхаваць стандартны пункт меню «Новая гульня»
 * выкарыстоўвуйце каманды «новая_гульня укл» і «новая_гульня выкл».
 *
 * У RPG Maker MZ каманды выбіраюцца са спісу.
 *
 * Гэта версія плагіна 1.0, апублікаваная 2025-03-23.
 *
 * Дзякуй Tarwix <https://tarwix.itch.io/> за дапамогу з памылкай з чытаннем
 * канфігурацыі.
 *
 * Гэты плагін перададзены ў грамадскі набытак згодна з CC0. Падрабязней гл.
 * на старонцы https://creativecommons.org/publicdomain/zero/1.0/deed.be
 */
/*~struct~NewGamePlusItem:be
 * @param id
 * @text ID
 * @desc Код, які будзе выкарыстоўвацца ў камандах «Новая_гульня+ ID УКЛ» і «Новая_гульня+ ID ВЫКЛ». Без прабелаў
 * @type text
 * @default newgameplus
 *
 * @param menuItemText
 * @text Тэкст пункта меню
 * @desc Тэкст новага пункта меню на тытульным экране
 * @type text
 * @default Новая гульня+
 *
 * @param mapId
 * @text № пачатковай карты
 * @desc З якой карты пачынаецца Новая гульня+
 * @type number
 * @min 1
 * @max 999
 *
 * @param x
 * @text X пачатковай клеткі
 * @desc Колькасць клетак ад найлявейшага слупочка клетак
 * да клеткі, дзе будзе пачынацца Новая гульня+.
 * @type number
 * @min 0
 * @max 255
 *
 * @param y
 * @text Y пачатковай клеткі
 * @desc Колькасць клетак ад верхняга радка клетак
 * да клеткі, дзе будзе пачынацца Новая гульня+.
 * @type number
 * @min 0
 * @max 255
 */
/*:ru
 * @target MV MZ
 * @plugindesc Добавляет новые пункты меню, доступные после победы
 * @author Команда Гарбата
 * @url https://rpgukr.one/GRB_NewGamePlus_MultiItem
 *
 * @command newgame+ ID on
 * @text Новая_игра+ ID включена (один пункт)
 * @desc Показывает один пункт меню «Новая игра+»
 
 * @arg menuItemId
 * @text ID пункта меню
 * @desc ID пункта меню, который будет включён (задаётся в настройках пункта меню)
 *
 * @command newgame+ ID off
 * @text Новая_игра+ ID отключена (один пункт)
 * @desc Скрывает один пункт меню «Новая игра+»
 *
 * @arg menuItemId
 * @text ID пункта меню
 * @desc ID пункта меню, который будет скрыт (задаётся в настройках пункта меню)
 *
 * @command newgame+ on
 * @text Новая_игра+ включена (показать все)
 * @desc Показывает все пункты меню «Новая игра+»
 *
 * @command newgame+ off
 * @text Новая_игра+ отключена (скрыть все)
 * @desc Скрывает все пункты меню «Новая игра+»
 *
 * @command newgame on
 * @text Новая_игра включена (показаць стандартную)
 * @desc Повторно включает стандартный пункт меню «Новая игра»
 *
 * @command newgame off
 * @text Новая_игра отключена (скрыть стандартную)
 * @desc Скрывает стандартный пункт меню «Новая игра»
 *
 * @param menuItems
 * @text Пункты меню «Новая игра+»
 * @type struct<NewGamePlusItem>[]
 * @desc Пункты меню «Новая игра+», которые можно показать или скрыть во время игры
 *
 * @help
 * Этот плагин — это АЛЬТЕРНАТИВНАЯ версия плагина GRB_NewGamePlus, которая
 * позволяет добавлять несколько пунктов меню. Это ЗАМЕНА для GRB_NewGamePlus,
 * их не следует устанавливать одновременно.
 *
 * ----------------------------------------------------------------------------
 *
 * Новая игра+ — это особое начало игры, которое делается доступным после
 * победы в основной игре.
 *
 * Данный плагин позволяет добавить *несколько* таких пунктов меню, и каждый
 * можно будет показать или скрыть отдельно. Данный плагин также позволяет
 * скрывать или вновь показывать стандартный пункт меню «Новая игра».
 *
 * Все пунткы меню «Новая игра+» в начале игры скрыты, и становятся доступны
 * позже. Текст этих пунктов меню задаётся в параметрах «Текст пунктов меню».
 *
 * Эти пункты меню начинают игру так же, как и обычный пункт «Новая игра», но
 * с другого места. Это место задаётся параметрами «№ начальной карты»,
 * «X начальной клетки» и «Y начальной клетки». Их можно узнать таким образом:
 *
 * - Откройте карту, на которой вы хотите начать Новую игру+.
 * - Переключитесь на Режим событий клавишей F6.
 * - Щёлкните левой кнопкой мыши по месту, где вы хотите начинать Новую игру+.
 * - После этого посмотрите на нижнюю часть экрана. Там есть строка состояния,
 * разделённая не несколько пунктов, примерно таким образом:
 *  |               |  002:Рыбацкая деревня (40x40)   | 100% | 18,12 |       |
 * - Первый (самый левый) пункт всегда пустой
 * - На втором пункте можно увидеть номер начальной карты (перед :), введите
 * его в настройках плагина.
 * - Третий пункт — масштаб, пропустите его
 * - В четвёртом пункте показываются координаты X и Y, разделённые запятой.
 * Введите первое число как X начальной клетки, а второе — как Y начальной
 * клетки.
 *
 * Чтобы включить или выключить пункт меню «Новая игра+», используйте команду
 * событий «Команда плагина». В MV используйте такие команды:
 * новая_игра+ включена
 * новая_игра+ отключена
 * Замените ID на ID, указанный в настройках плагина.
 *
 * Например, если ID — «newgameplus», команда плагина для MV будет выглядеть
 * так:
 * новая_игра+ newgameplus включена
 * новая_игра+ newgameplus отключена
 *
 * Если не указывать ID, можно показать или скрыть ВСЕ пункты «Новая
 * игра+»:
 * новая_игра+ включена
 * новая_игра+ отключена
 *
 * Чтобыпоказать или скрыть стандартный пункт меню «Новая игра» используйте
 * команды «новая_игра включена» и «новая_игра отключена».
 *
 * В RPG Maker MZ выберите команду плагина из списка.
 *
 * Это версия плагина 1.0, опубликованная 2025-03-23.
 *
 * Спасибо Tarwix <https://tarwix.itch.io/> за помощь с ошибкой при чтении
 * конфигурации.
 *
 * Этот плагин передан в общественное достояние согласно CC0. Подробнее см. на
 * странице https://creativecommons.org/publicdomain/zero/1.0/deed.ru
 */
/*~struct~NewGamePlusItem:ru
 * @param id
 * @text ID
 * @desc Код для команд «Новая_игра+ ID включена» і «Новая_игра+ ID отключена». Без пробелов
 * @type text
 * @default newgameplus
 *
 * @param menuItemText
 * @text Текст пункта меню
 * @desc Текст нового пункта меню на титульном экране
 * @type text
 * @default Новая игра+
 *
 * @param mapId
 * @text № начальной карты
 * @desc С какой карты начинается Новая игра+
 * @type number
 * @min 1
 * @max 999
 *
 * @param x
 * @text X начальной клетки
 * @desc Количество клеток от самого левого столбца клеток
 * до клетки, где будет начинаться Новая игра+.
 * @type number
 * @min 0
 * @max 255
 *
 * @param y
 * @text Y начальной клетки
 * @desc Количество клеток от самого верхнего ряда клеток
 * до клетки, где будет начинаться Новая игра+.
 * @type number
 * @min 0
 * @max 255
 */

(function () {

/**
 * Parsed setting for a single menu item.
 * @typedef  {Object} NewGamePlusMenuItem
 * @property {string} id - ID used for plugin commands to enable or disable the menu item
 * @property {string} menuItemText - Text of the label
 * @property {number} mapId - ID of the map on which the player starts game if choses this menu item
 * @property {number} x - X coordinate of the point of which the player starts game after choosing the menu item
 * @property {number} y - Y coordinate of the point of which the player starts game after choosing the menu item
 * @property {number} index - The index of the map description. Used for better error reporting
 */
 
var pluginName = 'GRB_NewGamePlus_MultiItem';
var parameters = PluginManager.parameters(pluginName);

/** @var {NewGamePlusMenuItem[]> Array of parsed menu item configurations */
var itemsArray = prepareNewGamePlusDataArray(parameters.menuItems)

/** @var {Object.<string, NewGamePlusMenuItem> Map of parsed menu item configurations */
var itemsConfig = prepareNewGamePlusDataMap(itemsArray);

/** @var {string} Text that is prefixed to IDs to generate symbols for command window */
var symbolPrefix = 'newGamePlus_';

/**
 * Converts JSON string as returned by plugin manager into parsed object
 *
 * @param {string} jsonItem - Object serialized to JSON
 * @param {number} index - Zero-based index of the object in the original array. Used for better error reporting.
 * @returns {NewGamePlusMenuItem}
 */
function parseJsonMenuItem(jsonItem, index) {
  var item = JSON.parse(jsonItem);
  var id = item.id.trim()
  var x = parseInt(item.x)
  var y = parseInt(item.y)
  var mapId = parseInt(item.mapId)
  if (id === '') {
    throw new Error('Incorrect New Game+ menu item without ID encountered (in item #' + (index+1) + ')')
  }
  if (isNaN(x) || x < 0) {
    throw new Error('Incorrect X value for New Game+ menu item encountered: ' + item.x + ' (in item #' + (index+1) + ')')
  }
  if (isNaN(y) || y < 0) {
    throw new Error('Incorrect Y value for New Game+ menu item encountered: ' + item.y + ' (in item #' + (index+1) + ')')
  }
  if (isNaN(mapId) || mapId < 0) {
    throw new Error('Incorrect Map ID value for New Game+ menu item encountered: ' + item.y + ' (in item #' + (index+1) + ')')
  }
  
  return {id: id, mapId: mapId, x: x, y: y, index: index, menuItemText: item.menuItemText};
}

/**
 * Parses JSON array of menu items, as returned by Plugin Manager, and returns an array
 *
 * @param {string} JSON-encoded array of JSON-encoded objects representing menu items
 * @returns {NewGamePlusMenuItem[]}
 */
function prepareNewGamePlusDataArray(jsonMenuItems) {
  var jsonArray = JSON.parse(jsonMenuItems);
  return jsonArray.map(parseJsonMenuItem)
}

/**
 * Parses JSON array of menu items, as returned by Plugin Manager
 *
 * @param {NewGamePlusMenuItem[]} Array of parsed items
 * @returns {Object.<string, NewGamePlusMenuItem>}
 */
function prepareNewGamePlusDataMap(parsedItemsArray) {
  var itemsMap = {};
  parsedItemsArray.forEach(function (item, index) {
    if (itemsMap[item.id] !== undefined) {
      throw new Error('Two New Game+ menu items with same ID "' + item.id + '" found (#' + (item.index+1) + ' and #' + (itemsMap[item.id].index + 1) + ')');
    }
    itemsMap[item.id] = item
  })
  return itemsMap
}

/**
 * Returns normalized currently active New Game+ item IDs.
 * @returns {string[]}
 */
ConfigManager.correctActiveNewGamePlusMenuItemIds = function () {
  return this.normalizeNewGamePlusMenuItemIds(this.activeNewGamePlusMenuItemIds);
};

/**
 * Returns the New Game+ menu item IDs that are currently enabled.
 * This function reorders them according to the settings and removes
 * deleted ones.
 * @param {string[]} Item IDs to normalize
 * @return {string[]}
 */
ConfigManager.normalizeNewGamePlusMenuItemIds = function (ids) {
  if (!ids) {
    return []
  }
  
  var correctItemIds = [];
  itemsArray.forEach(function (item) {
    if (ids.indexOf(item.id) > -1) {
      correctItemIds.push(item.id);
    }
  })
  return correctItemIds;
};


/**
 * Checks whether the whether the default New Game menu items should be
 * hidden.
 *
 * NOTE! In MZ, this function will be called with this=null
 */
Window_TitleCommand.prototype.defaultNewGameDisabled = function () {
  if (!ConfigManager.defaultNewGameDisabled) {
    return false;
  }
  if (ConfigManager.correctActiveNewGamePlusMenuItemIds().length === 0) {
    // If all New Game+ items are disabled and New Game is disabled,
    // then still show New Game to make sure the player is not locked out
    // of the game at all
    return false;
  }
  return true;
}

var Window_TitleCommand_addCommand = Window_Command.prototype.addCommand;
/**
 * Add a new command to the title command window. This is the default MV/MZ
 * function, aliased to insert "New Game+" after a predefined command
 * (by default after "New Game", but this can be overriden by aliasing
 * symbolBeforeNewGamePlus).
 *
 * @param {string} name Text of the menu item, as shown to the playes
 * @param {string} symbol Internal code of the menu item
 * @param {boolean} enabled Specified whether the menu item is displayed as
 * enabled (by default, all menu items are enabled)
 * @param {any} ext Additional data associated with the menu command
 * @return {any} By default returns undefined, but can be aliased
 */
Window_TitleCommand.prototype.addCommand = function(name, symbol, enabled, ext) {
  var result
  var removeCurrentItem = false
  if (this.symbolToRemoveForDisabledNewGame() === symbol) {
    this.removedStandardNewGame = this.defaultNewGameDisabled()
    removeCurrentItem = this.removedStandardNewGame
  }
  if (!removeCurrentItem) {
    result = Window_TitleCommand_addCommand.call(
      this, name, symbol, enabled, ext
    );
  }
  if (symbol === this.symbolBeforeNewGamePlus()) {
    this.addNewGamePlusCommands();
  }
  return result;
};

/**
 * Returns the symbol of the menu item after which 'New Game+' will be inserted.
 *
 * @return {string} Name of the symbol
 */
Window_TitleCommand.prototype.symbolBeforeNewGamePlus = function () {
  return 'newGame';
};

/**
 * Returns the symbol that will be removed if New Game is disabled.
 *
 * @return {string} Name of the symbol
 */
Window_TitleCommand.prototype.symbolToRemoveForDisabledNewGame = function () {
  return 'newGame';
};


/**
 * Adds a 'New Game+' menu item, if needed.
 */
Window_TitleCommand.prototype.addNewGamePlusCommands = function() {
  this.addedNewGamePlusIds = ConfigManager.correctActiveNewGamePlusMenuItemIds();
  var window = this
  this.addedNewGamePlusIds.forEach(function (id) {
    window.addCommand(itemsConfig[id].menuItemText || 'New Game+', symbolPrefix + id);
  });
};

/**
 * Checks if the window corresponds to the current configuration.
 * @return {boolean} True if the window needs to be recteated
 */
Window_TitleCommand.prototype.needsRecreatingForNewGamePlus = function () {
  if (Boolean(this.removedStandardNewGame) !== Boolean(this.defaultNewGameDisabled())) {
    return true
  }
  
  var existingList = this.addedNewGamePlusIds;
  var newList = ConfigManager.activeNewGamePlusMenuItemIds;
  if (existingList.length != newList.length) {
    return true;
  }
  var removed = existingList.filter(function (id) {
  newList.indexOf(id) === -1
  })
  if (removed.length > 0) {
    return true
  }
  var added = newList.filter(function (id) {
  existingList.indexOf(id) === -1
  })
  if (added.length > 0) {
    return true
  }
  
  return false
}

var Scene_Title_createCommandWindow = Scene_Title.prototype.createCommandWindow;
/**
 * Creates a command window, adds menu item handlers. This is the default MV/MZ
 * function, aliased to add 'New Game+' handler.
 */
Scene_Title.prototype.createCommandWindow = function() {
  Scene_Title_createCommandWindow.call(this);
  this.addNewGamePlusHandler();
};

var Scene_Title_commandWindowRect = Scene_Title.prototype.commandWindowRect;
/**
 * MZ-only. Calculates the sizes of the command window. Aliased to create bigger
 * windows if "New Game+" command is visible.
 * @return {Rectangle}
 */
Scene_Title.prototype.commandWindowRect = function() {
  var rect = Scene_Title_commandWindowRect.call(this); 
  
  let offsetChanges = ConfigManager.correctActiveNewGamePlusMenuItemIds().length
  if (Window_TitleCommand.prototype.defaultNewGameDisabled.call(this)) {
    --offsetChanges;
  }
  if (offsetChanges !== 0) {
    return this.modifyCommandWindowSizeForNewGamePlus(rect, offsetChanges);
  }

  return rect;
}

/**
 * MZ-only. Returns changed dimensions of the command window if "New Game+"
 * commands are visible, or if New Game command is hidden.
 * @param {Rectangle} rect - Original rectangle
 * @param {number} numberOfItemsDifference - How many items are added (or removed)
 * @return {Rectangle} - Changed rectangle
 */
Scene_Title.prototype.modifyCommandWindowSizeForNewGamePlus = function (rect, numberOfItemsDifference) {
  var referenceCount = 3
  var changedCount = referenceCount + numberOfItemsDifference
  var referenceItemHeight = this.calcWindowHeight(referenceCount, true);
  var changedItemHeight = this.calcWindowHeight(changedCount, true);
  var heightDifference = changedItemHeight - referenceItemHeight;

  return new Rectangle(
    rect.x,
    rect.y - heightDifference / 2,
    rect.width,
    rect.height + heightDifference
  );
}

/**
 * Adds a handler for the "New Game+" menu item.
 */
Scene_Title.prototype.addNewGamePlusHandler = function() {
  var scene = this
  itemsArray.forEach(function (item) {
    scene._commandWindow.setHandler(symbolPrefix + item.id, scene.commandNewGamePlus.bind(scene, item));
  })  
};

/**
 * The handler function that is executed when "New Game+" menu item is selected.
 * @param {NewGamePlusMenuItem} menuItem Menu item that has been chosen
 */
Scene_Title.prototype.commandNewGamePlus = function(menuItem) {
    DataManager.setupNewGamePlus(menuItem);
    this._commandWindow.close();
    this.fadeOutAll();
    SceneManager.goto(Scene_Map);
};

var Scene_Title_update = Scene_Title.prototype.update;
/**
 * Updates the title scene. This function is called every frame (1/60th part
 * of the second). Aliased to re-create the command window if the "New Game+
 * enabled?" configuration changed since the scene was created.
 */
Scene_Title.prototype.update = function() {
  if (this._commandWindow && this._commandWindow.needsRecreatingForNewGamePlus()) {
    this.recteateCommandWindowForNewGamePlus();
  }
  Scene_Title_update.call(this);
}

/**
 * Recreates the command window to take new configuration into account.
 */
Scene_Title.prototype.recteateCommandWindowForNewGamePlus = function() {
  this._commandWindow.destroy();
  delete this._commandWindow;
  this.createCommandWindow();
}

/**
 * Sets up the "New Game+" type of game. It is basically same as the new game,
 * but the game starts in a different location.
 * @param {NewGamePlusMenuItem} menuItem Menu item that has been chosen
 */
DataManager.setupNewGamePlus = function(menuItem) {
  this.setupNewGame();
  $gamePlayer.reserveTransfer(
    parseInt(menuItem.mapId),
    parseInt(menuItem.x),
    parseInt(menuItem.y)
  );
};

/**
 * @var {boolean} defaultNewGameDisabled Default value (for MV) of the configuration
 * setting whether the standard New Game is hidden. Unlike the other configuration settings,
 * it is not visible in the Config Scene, but it's stored here for simplicity.
 */
ConfigManager.defaultNewGameDisabled = false;

/**
 * @var {string[]} activeNewGamePlusMenuItemIds Default value of IDs of the
 * currently enabled New Game+ menu items. Unlike the other other configuration settings,
 * it is not visible in the Config Scene, but it's stored here for simplicity.
 */
ConfigManager.activeNewGamePlusMenuItemIds = [];


var ConfigManager_makeData = ConfigManager.makeData;
/**
 * Prepare config data for saving. Aliased to save newGamePlusEnabled.
 * @return {object} JSON-stringifiable array
 */
ConfigManager.makeData = function() {
  var config = ConfigManager_makeData.call(this);
  return this.addNewGamePlusConfigurationToData(config);
};

/**
 * Adds a "New Game+ enabled?" configuration setting to the data that will
 * be saved.
 * @param {object} JSON-parseable object that will be modified
 * @return {object} The same object
 */
ConfigManager.addNewGamePlusConfigurationToData = function(config) {
  if (this.defaultNewGameDisabled) {
    config.defaultNewGameDisabled = this.defaultNewGameDisabled;
  }
  if (this.activeNewGamePlusMenuItemIds.length > 0) {
    config.activeNewGamePlusMenuItemIds = this.activeNewGamePlusMenuItemIds;
  }
  return config;
};

var ConfigManager_applyData = ConfigManager.applyData;
/**
 * Read the configuration from the parsed JSON. Aliased to read the "New Game+
 * enabled?" configuration.
 * @param {Object} config - Configuration map
 */
ConfigManager.applyData = function(config) {
  ConfigManager_applyData.apply(this, arguments);
  
  //The last parameter is the default value in MZ
  this.defaultNewGameDisabled = this.readFlag(config, 'defaultNewGameDisabled', false);
  this.readActiveNewGamePlusMenuItemIds(config)
};

/**
 * Reads the activeNewGamePlusMenuItemIds array from configuration object.
 * @param {Object} config - Configuration map
 */
ConfigManager.readActiveNewGamePlusMenuItemIds = function (config) {
  if (Object.prototype.toString.call(config.activeNewGamePlusMenuItemIds) !== '[object Array]') {
    this.activeNewGamePlusMenuItemIds = []
    return
  }
  
  this.activeNewGamePlusMenuItemIds = config.activeNewGamePlusMenuItemIds.filter((id) => {
    return itemsConfig[id]
  })
}

var Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
/**
 * Parse MV-style plugin command. Aliased to enable "newgame+ ID enable",
 * "newgame+ ID disable", "newgame enable", "newgame disable" event commands.
 *
 * @param {string} command The first word of the plugin command (separated by
 * spaces)
 * @param {string[]} args The rest of the words of the event command
 */
Game_Interpreter.prototype.pluginCommand = function (command, args) {
  if (!this.newGamePlusPluginCommandHandling(command, args)) {
    return Game_Interpreter_pluginCommand.call(this, command, args);
  }
}

/**
 * Parse MV-style plugin New Game+ commands.
 *
 * @param {string} command The first word of the plugin command (separated by
 * spaces)
 * @param {string[]} args The rest of the words of the event command
 * @returns {boolean} Returns true if the command was parsed as New Game+ command,
 * false if it needs to be passed to other plugins
 */
Game_Interpreter.prototype.newGamePlusPluginCommandHandling = function (command, args) {
  var commandMatches = command.match(/(new_?game|нова_?гра|новая_?игра|новая_?гульня)(?<plus>\+?)/i)
  if (!commandMatches) {
    return false
  }
  
  var isNewGamePlusCommand = commandMatches.groups.plus === '+';
  if (!isNewGamePlusCommand) {
    // Enable or disable the standard New Game item
    if (args.length !== 1) {
      return false;
    }
    
    if (this.newGamePlusPluginIsOn(args[0]) && ConfigManager.defaultNewGameDisabled) {
      ConfigManager.defaultNewGameDisabled = false;
      ConfigManager.save();
      return true;
    }
    
    if (this.newGamePlusPluginIsOff(args[0]) && !ConfigManager.defaultNewGameDisabled) {
      ConfigManager.defaultNewGameDisabled = true;
      ConfigManager.save();
      return true;
    }
    
    return false;
  }
  
  if (args.length === 1) {
    // Enable or disable all the New Game+ items
    if (this.newGamePlusPluginIsOn(args[0])) {
      ConfigManager.activeNewGamePlusMenuItemIds = Object.keys(itemsConfig);
      ConfigManager.save();
      return true;
    }
    
    if (this.newGamePlusPluginIsOff(args[0])) {
      ConfigManager.activeNewGamePlusMenuItemIds = [];
      ConfigManager.save();
      return true;
    }
  }
  
  if (args.length === 2) {
    var id = args[0];
    if (!itemsConfig[id]) {
      return false;
    }
    
    if (this.newGamePlusPluginIsOn(args[1])) {
      var ids = ConfigManager.activeNewGamePlusMenuItemIds;
      ids.push(id);
      ConfigManager.activeNewGamePlusMenuItemIds = ConfigManager.normalizeNewGamePlusMenuItemIds(ids);
      ConfigManager.save();
      return true;
    }
    
    if (this.newGamePlusPluginIsOff(args[1])) {
      var index = ConfigManager.activeNewGamePlusMenuItemIds.indexOf(id);
      if (index === -1) {
        return true;
      }
      ConfigManager.activeNewGamePlusMenuItemIds.splice(index, 1);
      ConfigManager.save();
      return true;
    }
  }
  
  return false;
}

/**
 * Checks if text says a variation of “on”, in the supported languages.
 * @param {string} arg - The text to be checked
 * @retruns {boolean} - True if the text says “on” or a variation of it
 */
Game_Interpreter.prototype.newGamePlusPluginIsOn = function (arg) {
  return Boolean(arg.match(/on|enabled?|ув|увімкнути|ввімкнути|вв|увімкнено|увімкнена|увімкнені|ввімкнено|ввімкнена|ввімкнені|вкл|включить|включена|включены|укл|уключыць|уключаная?|уключаныя?/i));
}

/**
 * Checks if text says a variation of “off”, in the supported languages.
 * @param {string} arg - The text to be checked
 * @retruns {boolean} - True if the text says “off” or a variation of it
 */
Game_Interpreter.prototype.newGamePlusPluginIsOff = function (arg) {
  return Boolean(arg.match(/off|disabled?|вим|вимкнути|вимкнено|вимкнуто|вимкнено|вимкнена|вимкнені|вимкнута|вимкнуті|выкл|выключить|выключена|выключены|выключыць|выключаная?|выключаныя?|откл|отключена|адкл|адключаная|адключаныя?/i));
}

if (Utils.RPGMAKER_NAME == 'MZ') {
  PluginManager.registerCommand(pluginName, "newgame+ ID on", function (args) {
    var ids = ConfigManager.activeNewGamePlusMenuItemIds;
    ids.push(args.menuItemId);
    ConfigManager.activeNewGamePlusMenuItemIds = ConfigManager.normalizeNewGamePlusMenuItemIds(ids);
    ConfigManager.save();
  });

  PluginManager.registerCommand(pluginName, "newgame+ ID off", function (args) {
      var index = ConfigManager.activeNewGamePlusMenuItemIds.indexOf(args.menuItemId);
      if (index === -1) {
        return;
      }
      ConfigManager.activeNewGamePlusMenuItemIds.splice(index, 1);
      ConfigManager.save();
  });

  PluginManager.registerCommand(pluginName, "newgame+ on", function (args) {
      ConfigManager.activeNewGamePlusMenuItemIds = Object.keys(itemsConfig);
      ConfigManager.save();
      return true;
  });

  PluginManager.registerCommand(pluginName, "newgame+ off", function (args) {
      ConfigManager.activeNewGamePlusMenuItemIds = [];
      ConfigManager.save();
      return true;
  });

  PluginManager.registerCommand(pluginName, "newgame on", function (args) {
      ConfigManager.defaultNewGameDisabled = false;
      ConfigManager.save();
  });

  PluginManager.registerCommand(pluginName, "newgame off", function (args) {
      ConfigManager.defaultNewGameDisabled = true;
      ConfigManager.save();
  });
}

})();

Посилання[ ]

Є пропозиції щодо покращення цієї сторінки. Якщо ви хочете цим зайнятися, зверніть увагу на коментарі <!-- ... --> в коді сторінки.