Game_Systemに変数を代入できない

ppp
記事: 43
登録日時: 2022年9月28日(水) 21:50

Game_Systemに変数を代入できない

投稿記事by ppp » 2023年12月24日(日) 17:58

質問失礼します。アイテム調合プラグインを作っているのですが、Game_Systemに値を代入しても、thisがGame_System内で共有されず、$gameSystemからundefinedがconsole.logで返ってきてしまいます。どのようにすれば、正しく値を代入できるのでしょうか?
以下、中途半端で整形していないですがコードです

コード: 全て選択

/*:
 * @plugindesc アイテム調合プラグイン
 * @author free
 * @help MV アイテム調合プラグイン
 *
 * @param ItemCompound Compound Command
 * @desc アイテム調合成功のメッセージ
 * @type string
 * @default "の合成"
 *
 * @param ItemCompound Success Message
 * @desc アイテム調合成功のメッセージ
 * @type string
 * @default "アイテムの調合が成功しました。"
 *
 * @param ItemCompound Failure Message
 * @type string
 * @default "アイテムの調合が失敗しました。"
 *
 * @param ItemCompound Great Success Message
 * @type string
 * @default "アイテムの調合が大成功しました"
 */

(function () {
    "use strict";
    const pluginName = 'ItemCompound';

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

    const parameters = PluginManager.parameters(pluginName);
    ItemCompound.Parameters = {
       ItmCmpdCmd: parameters['ItemCompound Compound Command'],
       CpdSucsMsg: parameters['ItemCompound Success Message'],
       CpdFalrMsg: parameters['ItemCompound Failure Message'],
       CpdGrScMsg: parameters['ItemCompound Great Success Message']
    };

    ItemCompound.prototype.initialize = function() {
        this._compoundingItems = [];//調合中のアイテム {id:itemId, amount:amount}
        this.initializeRecipes();
    };

// メモ欄を取得しレシピを配列に保存
    ItemCompound.prototype.initializeRecipes = function () {
        const recipeRegex = /<recipe>\s*m:(\w+)\s*r:(\w+)\s*c:(\w+)\s*k:(\w+)\s*t:(\w+)\s*p:(\w+)\s*<\/recipe>/g;
        this._recipes = [[], [], []];
        const processElement = (element, type) => {
            if (element && element.meta) {
                const metaString = element.meta;
                var matches;
                while ((matches = recipeRegex.exec(metaString)) !== null) {
                    const recipes = {
                        m: matches[1],
                        r: matches[2],
                        c: matches[3],
                        k: matches[4],
                        t: matches[5],
                        p: matches[6]
                    };
                    this._recipes[type][element.id] = recipes;
                }
            }
        };

        $dataItems.forEach(element => processElement(element, 0));
        $dataWeapons.forEach(element => processElement(element, 1));
        $dataArmors.forEach(element => processElement(element, 2));
    };
//
   ItemCompound.prototype.hasRecipeItems = function(itemId, type) {
        if (!this._recipes[type][itemId]) return false;
        var recipes = this._recipes[type][itemId].map(item => {
            var itemIdMatch = item.match(/i(\d+)/);
            var itemAmtMatch = item.match(/a(\d+)/);
            return {i: itemIdMatch, a: itemAmtMatch};
        }, this);
        var i = 0;
        var materials = [];
        var amounts = [];
        return recipes.every(recipe => {
            materials.push(recipe.i.split(/,\s/));
            amounts.push(recipe.a.split(/,\s/));
            return amounts[i].a <= $gameParty.numItems(materials[i].i);
            i++;
        }, this);
    };

    ItemCompound.prototype.isEnoughRecipeCost = function(itemId) {
        return this._recipes[itemId].c <= $gameParty.gold();
    };

    //レシピから調合開始する
    ItemCompound.prototype.startCompoundItem = function(itemId) {
        if (this.hasRecipeItems(itemId)) {
            if (this.isEnoughRecipeCost(itemId)) {
                var usedItems = this._recipes[itemId].map(recipe => ({
                    m: recipe.m,
                    a: recipe.a
                }));

                usedItems.forEach(function(usedItem) {
                    $gameParty.loseItem($dataItems[usedItem.m], usedItem.a);
                }, this);

                $gameParty.gainGold(-this._recipes[itemId].c);
                var sameRecipes = this._recipes.filter(recipe => recipe.m === this._recipes[itemId].m);
                var totalProbability = sameRecipes.reduce((sum, recipe) => sum + recipe.p, 0);
                var cumulativeProbability = 0;
                var selectedRecipe = sameRecipes.find(recipe => {
                    cumulativeProbability += recipe.p / totalProbability;
                    return Math.random() <= cumulativeProbability;
                }, this);

                var resultItems = selectedRecipe.r.split(/,\s*/).map(recipe => {
                   var itemId = recipe.match(/r(\d+)/);
                   var itemAmt = recipe.match(/a(\d+)/);
                   return {i: itemId, a: itemAmt};
                }, this);

                this.compoundingItems.push({ id: selectedRecipe.i, a: selectedRecipe.a, t: selectedRecipe.t });

                resultItems.forEach(resultItem => {
                    this.compoundingItems.push({ id: resultItem.i, a: resultItem.a, t: resultItem.t });
                }, this);

            } else {
                this.notEnoughGold();
            }
        } else {
            this.notEnoughItems();
        }
    };

    ItemCompound.prototype.finishCompoundItem = function(item, compounder) {
        [$dataItems, $dataWeapons, $dataArmors].forEach((data, type) => {
            var processedData = processData(item, type === 0 ? 'item' : type === 1 ? 'weapon' : 'armor');
            this.compoundingItems.splice($dataItems[item.m].id, 0, ...processedData);
        }, this);
            this.compoundingItems.forEach(function(compoundingItem) {
                switch (compoundingItem.type) {
                case item:
                    $gameParty.gain($dataItems[compoundingItem.id], compoundingItem.a);
                    break;
                case weapon:
                    $gameParty.gain($dataWeapons[compoundingItem.id], compoundingItem.a);
                    break;
                case armors:
                    $gameParty.gain($dataArmors[compoundingItem.id], compoundingItem.a);
                    break;
                }
            }, this);
        };

//============================================================
var _Game_System_initialize = Game_System.prototype.initialize;
Game_System.prototype.initialize = function() {
    _Game_System_initialize.apply(this, arguments);
    this._itemCompound = new ItemCompound();
};

Game_System.prototype.recipes = function() {
    return this._itemCompound;
};

Game_System.prototype.canCompound = function(itemId) {
    return this.hasRecipeItems(itemId) && this.isEnoughRecipeCost(itemId);
};
//============================================================

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

   if(command === pluginName){
       switch(args[0]){
       case 'show':
      SceneManager.push(Scene_CompoundItem);
                break;
       }
   }
    };
   
//============================================================

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

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

    Scene_CompoundItem.prototype.initialize = function(){
        Scene_MenuBase.prototype.initialize.call(this);
    };
   
    Scene_CompoundItem.prototype.create = function(){
   Scene_MenuBase.prototype.create.call(this);

   this.createIndexWindow();
   this.createGoldWindow();
   this.createCommandWindow();

   this.activateIndexWindow();   
    };

    Scene_CompoundItem.prototype.createIndexWindow = function(){
   var wx = 0;
   var wy = 0;   
   var ww = Graphics.width / 2;
   var wh = Graphics.height;

   this._indexWindow = new Window_CompoundItemIndex(wx, wy, ww, wh);
   this._indexWindow.setHandler('ok', this.onIndexOk.bind(this));
   this._indexWindow.setHandler('cancel', this.onIndexCancel.bind(this));   
   
   this.addWindow(this._indexWindow);
    };

    Scene_CompoundItem.prototype.createGoldWindow = function(){
   this._goldWindow = new Window_Gold(0, 0);
   
   var wx = Graphics.width - this._goldWindow.width;
   this._goldWindow.move(wx, 0, this._goldWindow.width, this._goldWindow.height);

   this.addWindow(this._goldWindow);
    };
   
    Scene_CompoundItem.prototype.createCommandWindow = function(){
   this._commandWindow = new Window_CompoundItemCommand(0, 0);
   
   var wx = Graphics.width - this._commandWindow.width;
   var wy = Graphics.height - this._commandWindow.height;
   
   this._commandWindow.move(wx, wy, this._commandWindow.width, this._commandWindow.height);
   this._commandWindow.setHandler('compound', this.onCommandCompound.bind(this));
   this._commandWindow.setHandler('cancel', this.onCommandCancel.bind(this));

   this.hideCommandWindow();
   
   this.addWindow(this._commandWindow);   
    };
    Scene_CompoundItem.prototype.onIndexOk = function(){
   this.activateCommandWindow();
    };
   
    Scene_CompoundItem.prototype.onIndexCancel = function(){
   this.popScene();
    };
   
    Scene_CompoundItem.prototype.onCommandCompound = function(){
   this.hideCommandWindow();
   this.activateIndexWindow();
   this._goldWindow.refresh();
    };

    Scene_CompoundItem.prototype.onCommandCancel = function(){
   this.hideCommandWindow();
   this._indexWindow.activate();
   
    };

    Scene_CompoundItem.prototype.compound = function(){
   var actor = this._indexWindow.selectedItem();
    };
   
    Scene_CompoundItem.prototype.money = function(){
   return this._goldWindow.value();
    };

    Scene_CompoundItem.prototype.activateIndexWindow = function(){
   this._indexWindow.setMoney(this.money());
   this._indexWindow.activate();
   this._indexWindow.refresh();
    };

    Scene_CompoundItem.prototype.activateCommandWindow = function(){
   this._commandWindow.activate();
   this._commandWindow.select(0);
   this._commandWindow.show();
    };

    Scene_CompoundItem.prototype.hideCommandWindow = function(){
   this._commandWindow.deselect();
   this._commandWindow.deactivate();
   this._commandWindow.hide();
    };

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

    Window_CompoundItemIndex.prototype = Object.create(Window_Selectable.prototype);
    Window_CompoundItemIndex.prototype.constructor = Window_CompoundItemIndex;

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

   this.refresh();
   this.select(0);
   this.activate();
    };

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

    Window_CompoundItemIndex.prototype.maxItems = function(){
   return this._list ? this._list.length : 0;
    };

    Window_CompoundItemIndex.prototype.drawItem = function(index){
   var actor = this._list[index];
   var salary = actor.meta[tagName] + TextManager.currencyUnit;      
   var rect = this.itemRect(index);

   this.changePaintOpacity(this.isEnabled(actor));

   this.drawText(actor.name, rect.x, rect.y, 100);
   this.drawText(salary, rect.x + 130, rect.y, 100, 'right');
    };

    Window_CompoundItemIndex.prototype.selectedItem = function(){
   return this._list[this.index()];
    };
   
    Window_CompoundItemIndex.prototype.isCurrentItemEnabled = function(){
   return this.isEnabled(this.selectedItem());
    };

    Window_CompoundItemIndex.prototype.isEnabled = function(actor){
        return $gameSystem.hasRecipeItems();
    };

    Window_CompoundItemIndex.prototype.setMoney = function(money){
   this._money = money;
    };

    Window_CompoundItemIndex.prototype.refresh = function(){
   this.createContents();
   this.makeRecipeList();
   this.drawAllItems();

   if(this.lastIndex > this._list.length - 1){
       this.select(this._list.length - 1);
   }
    };

    Window_CompoundItemIndex.prototype.makeRecipeList = function(){

        this._list = [];
console.log($gameSystem.recipes()) ←ここでundefinedが返ってくる
        if (!!$gameSystem.recipes()) {
           
            $gameSystem.recipes().forEach(element => {
                this._list.push(element);
            }, this);
        }
    };

    function Window_CompoundItemCommand(){
   this.initialize.apply(this, arguments);
    }
   
    Window_CompoundItemCommand.prototype = Object.create(Window_Command.prototype);
    Window_CompoundItemCommand.prototype.constructor = Window_CompoundItemCommand;

    Window_CompoundItemCommand.prototype.initialize = function(x, y){
   Window_Command.prototype.initialize.call(this, x, y);
    };

    Window_CompoundItemCommand.prototype.makeCommandList = function(){
   this.addCommand('合成する', 'compound', true);
    };
})();

コード: 全て選択

console.log($gameSystem.recipes()) ←ここでundefinedが返ってくる

アバター
Plasma Dark
記事: 669
登録日時: 2020年2月08日(土) 02:29
連絡を取る:

Re: Game_Systemに変数を代入できない

投稿記事by Plasma Dark » 2023年12月24日(日) 18:40

動作確認の際、ニューゲームからゲームを開始しているでしょうか。
プラグイン導入前のセーブデータをロードした場合に、 Game_System のインスタンスである $gameSystem はセーブされた内容のものに置き換わってしまいますので、変数 _itemCompound はundefinedになります。
ppp
記事: 43
登録日時: 2022年9月28日(水) 21:50

Re: Game_Systemに変数を代入できない

投稿記事by ppp » 2023年12月24日(日) 18:59

素早い返答ありがとうございます!一旦ニューデータを作って試してみます!

“MV:質問” へ戻る