ChapelR / custom-macros-for-sugarcube-2

A collection of systems and macros for Twine.
https://macros.twinelab.net/
The Unlicense
170 stars 43 forks source link

Example Code for Automatically updating inventories Not working? #63

Closed kiltedken closed 4 months ago

kiltedken commented 1 year ago

Hi,

Thanks for all your amazing work!

I'm not new to programming, but very new to Twine, Tweego, js, etc., so sorry for the lengthy issue post, I'm not sure what I should include or not. If there's anything missing, please let me know.

I'm trying to get the Automatic updating of inventories to work and ran into an error message. I'm using the example code from: https://twinelab.net/custom-macros-for-sugarcube-2/#/simple-inventory?id=event-inventory-update

First Issue

I had to change the examples code a bit, this caused errors:

Items you're carrying:
@@.auto-update;<<linkedinventory '$player' '$room' 'Drop'>>@@

What's laying around in this room:
@@.auto-update;<<linkedinventory '$room' '$player' 'Take'>>@@

The errors were

Items you're carrying:
Error: <<linkedinventory>>: variable name "Drop" is missing its sigil ($ or _)

What's laying around in this room:
Error: <<linkedinventory>>: variable name "Take" is missing its sigil ($ or _)

I moved the 'Take' and 'Drop' and this stopped those errors:

Items you're carrying:
@@.auto-update;<<linkedinventory 'Drop' '$player' '$room'>>@@

What's laying around in this room:
@@.auto-update;<<linkedinventory 'Take' '$room' '$player'>>@@

Hopefully that change didn't cause the next issue.

The Issue I can't figure out

The error that comes up in a pop up is:

An error has occurred. You may be able to continue, but some parts may not work properly.

Error: inv is undefined.
Stack Trace:
... [there's some personal information in the stack trace, if you need it I can send it in email or redact it some]
...

The way it pops up, is when you first click a Drop, or a Take, it just works fine. The item automatically updates and moves from one inventory to the other and is updated on the page. Looks great!

But, the next click of a Drop or a Take causes the error above to pop up. All subsequent Drop or a Takes also get the error.

If you click the error's OK button, I find the inventories are not updated, but the variables are (debugging shows them). If you leave the page with the GO Here, and then Go Back, the inventory is updated as it should be, and once again the first click just works, but subsequent clicks get the error message.

Thanks again!

-Ken

Code and Stuff

I'm running tweego like this:

tweego -o inventory-issue.html inventory-issue.twee simple-inventory.min.js inventory-update.js -t --watch

Watch mode started.  Press CTRL+C to stop.

Recursively watched paths: 3
  inventory-issue.twee
  simple-inventory.min.js
  inventory-update.js

BUILDING: inventory-issue.html

inventory-issue.twee:

:: StoryTitle
Simple Inventory Issue

:: StoryData
{
    "ifid": "574FCB3B-5362-4D89-9507-77A0DB5CCE5B",
    "format": "SugarCube",
    "format-version": "2.36.1",
    "options": [
        "debug"
    ],
    "start": "Start",
    "zoom": 1
}

:: Start
<<newinventory '$player' 'pants' 'wallet'>>
<<newinventory '$room' 'dustbunny'>>

[[GO There|There]]

:: There
Items you're carrying:
@@.auto-update;<<linkedinventory 'Drop' '$player' '$room'>>@@

What's laying around in this room:
@@.auto-update;<<linkedinventory 'Take' '$room' '$player'>>@@

[[GO Here|Here]]

:: Here

Nothing to see Here
[[Go Back|There]]

inventory-update.js

$(document).on(':inventory-update', function (ev) {
    if (ev.context !== 'transfer') {
        // this event should only occur on transfer events
        return;
    }
    // only the receiving inventory needs updated, but we'll update both for the sake of simplicity
    $('.auto-update').each( function (i, el) {
        // find the inventories marked for auto-updating
        // get the macro's wrapper:
        var $macro = $(el).find('.macro-linkedinventory');
        // get the inventories:
        var inv = State.getVar($macro.attr('data-self'));
        var rec = false;
        if ($macro.attr('data-rec')) {
            rec = State.getVar($macro.attr('data-rec'));
        }
        // reconstruct the list via the `inventory#linkedList()` method
        var $list = inv.linkedList(rec, $macro.attr('data-action'));
        // empty the container and replace it
        $(el).empty().append($list);
    });
});

simple-inventory.min.js

// simple-inventory.min.js, for SugarCube 2, by Chapel
// v2.3.0, 2022-07-21, 3bdbdfbe5ae47a46e4f4e52766d78701939ae9a6
;!function(){"use strict";var r={tryGlobal:!0,defaultStrings:{empty:"The inventory is empty...",listDrop:"Discard",separator:"\n"}};function i(r,i,t,n){$(document).trigger({type:"initialized"===n?":inventory-init":":inventory-update",instance:r,receiving:i,moved:t,context:n})}function t(r){if(r=r?(r=[].slice.call(arguments)).flatten():[],!(this instanceof t))return new t(r);this.inv=r,i(this,null,r=r.length?r:null,"initialized")}Object.assign(t,{is:function(r){return r instanceof t},log:function(r){return t.is(r)?"Inventory.log() -> "+r.toArray().join(" - "):"Inventory.log() -> object is not an inventory..."},removeDuplicates:function(r){if(t.is(r)){var i,n=r.toArray();return i=[],n.forEach((function(r){i.includes(r)||i.push(r)})),i}}}),Object.assign(t.prototype,{transfer:function(r){if(arguments.length<2)return this;if(!t.is(r))return this;for(var n=[].slice.call(arguments),e=[],s=0,a=(n=n.slice(1).flatten()).length;s<a;s++)this.inv.includes(n[s])&&(this.inv.delete(n[s]),e.push(n[s]));return e.length?(r.inv=r.inv.concat(e),i(this,r,e,"transfer"),this):this},has:function(){var r=[].slice.call(arguments).flatten();return!(!r||!r.length)&&this.inv.includesAny(r)},hasAll:function(){var r=[].slice.call(arguments).flatten();return!(!r||!r.length)&&this.inv.includesAll(r)},pickUp:function(r){var t=[].slice.call(arguments).flatten(),n=this;return t&&t.length&&("unique"!==r&&"unique"!==t[0]||(t=function(r){var i=[];return r.forEach((function(r){n.inv.includes(r)||i.includes(r)||i.push(r)})),i}(t=t.splice(1))),this.inv=this.inv.concat(t),i(this,null,t,"pickup")),this},drop:function(){var r,t=[].slice.call(arguments).flatten(),n=this;if(t&&t.length){var e=[];t.forEach((function(i){n.has(i)&&(e.push(i),r=n.inv.indexOf(i),n.inv.deleteAt(r))})),i(this,null,e,"drop")}return this},sort:function(){return this.inv=this.inv.sort(),i(this,null,null,"sort"),this},show:function(i){return i&&"string"==typeof i||(i=r.defaultStrings.separator),this.inv.length?this.inv.join(i):r.defaultStrings.empty},empty:function(){var r=clone(this.inv);return this.inv=[],i(this,null,r,"drop"),this},toArray:function(){return this.inv},count:function(r){if(r&&"string"==typeof r){var i=0;return this.toArray().forEach((function(t){t===r&&i++})),i}return this.toArray().length},isEmpty:function(){return 0===this.toArray().length},linkedList:function(i,n){i&&t.is(i)||(i=!1);var e=this.toArray(),s=this,a=$(document.createElement("span"));return e&&e.length?(e.forEach((function(t,e,o){var l=$(document.createElement("span")),u=$(document.createElement("a")),h=n||r.defaultStrings.drop,c=function(r,i){var t=Math.random().toString(36).substring(7);return arguments.length<2&&(r=Math.random().toString(36).substring(7),i=random(99)),"simple-inv-"+i+"-"+Date.now()+"-"+r.replace(/[^A-Za-z0-9]/g,"")+"-"+t}(t,e);u.wiki(h).addClass("simple-inv drop-link"),u.ariaClick((function(){i?s.transfer(i,t):s.drop(t),$("#"+c).empty()})),l.attr("id",c).addClass("simple-inv link-listing").wiki(t+" ").append(u),e<o.length-1&&l.wiki("<br />"),a.append(l)})),a):(a.wiki(r.defaultStrings.empty),a)},constructor:t,toJSON:function(){return JSON.reviveWrapper("new setup.Inventory("+JSON.stringify(this.inv)+")")},clone:function(){return new t(this.inv)}}),setup.Inventory=t,setup.simpleInv={inventory:t},r.tryGlobal&&(window.Inventory=window.Inventory||t),Macro.add("newinventory",{handler:function(){if(this.args.length<1)return this.error("incorrect number of arguments");var r=this.args[0].trim();if("$"!==r[0]&&"_"!==r[0])return this.error('variable name "'+this.args[0]+'" is missing its sigil ($ or _)');Wikifier.setValue(r,new t(this.args.slice(1).flatten()))}}),Macro.add("pickup",{handler:function(){if(this.args.length<2)return this.error("incorrect number of arguments");var r=this.args[0].trim();if("$"!==r[0]&&"_"!==r[0])return this.error('variable name "'+this.args[0]+'" is missing its sigil ($ or _)');var i=Wikifier.getValue(r);if(!t.is(i))return this.error("variable "+r+" is not an inventory!");i.pickUp(this.args.slice(1).flatten())}}),Macro.add("drop",{handler:function(){if(this.args.length<2)return this.error("incorrect number of arguments");var r=this.args[0].trim();if("$"!==r[0]&&"_"!==r[0])return this.error('variable name "'+this.args[0]+'" is missing its sigil ($ or _)');var i=Wikifier.getValue(r);if(!t.is(i))return this.error("variable "+r+" is not an inventory!");i.drop(this.args.slice(1).flatten())}}),Macro.add("transfer",{handler:function(){if(this.args.length<3)return this.error("incorrect number of arguments");var r=this.args[0].trim();if("$"!==r[0]&&"_"!==r[0])return this.error('variable name "'+this.args[0]+'" is missing its sigil ($ or _)');var i=Wikifier.getValue(r);if(!t.is(i))return this.error("variable "+r+" is not an inventory!");var n=this.args[1].trim();if("$"!==n[0]&&"_"!==n[0])return this.error('variable name "'+this.args[1]+'" is missing its sigil ($ or _)');var e=Wikifier.getValue(n);if(!t.is(e))return this.error("variable "+n+" is not an inventory!");i.transfer(e,this.args.slice(2).flatten())}}),Macro.add("dropall",{handler:function(){if(1!==this.args.length)return this.error("incorrect number of arguments");var r=this.args[0].trim();if("$"!==r[0]&&"_"!==r[0])return this.error('variable name "'+this.args[0]+'" is missing its sigil ($ or _)');var i=Wikifier.getValue(r);if(!t.is(i))return this.error("variable "+r+" is not an inventory!");i.empty()}}),Macro.add("clear","dropall",!1),Macro.add("sort",{handler:function(){if(1!==this.args.length)return this.error("incorrect number of arguments");var r=this.args[0].trim();if("$"!==r[0]&&"_"!==r[0])return this.error('variable name "'+this.args[0]+'" is missing its sigil ($ or _)');var i=Wikifier.getValue(r);if(!t.is(i))return this.error("variable "+r+" is not an inventory!");i.sort()}}),Macro.add("inventory",{handler:function(){if(this.args.length<1||this.args.length>2)return this.error("incorrect number of arguments");var r=this.args[0].trim();if("$"!==r[0]&&"_"!==r[0])return this.error('variable name "'+this.args[0]+'" is missing its sigil ($ or _)');var i=Wikifier.getValue(r);if(!t.is(i))return this.error("variable "+r+" is not an inventory!");var n=$(document.createElement("span")),e=!!this.args[1]&&this.args[1];n.wiki(i.show(e)).addClass("macro-"+this.name).appendTo(this.output)}}),Macro.add("linkedinventory",{handler:function(){if(this.args.length<2||this.args.length>3)return this.error("incorrect number of arguments");var r=!1,i="",n=this.args[1].trim(),e="string"==typeof this.args[0]&&this.args[0];if(!e)return this.error("first argument should be the link text");if("$"!==n[0]&&"_"!==n[0])return this.error('variable name "'+this.args[1]+'" is missing its sigil ($ or _)');var s=Util.slugify(n);s=this.name+"-"+s;var a=Wikifier.getValue(n);if(!t.is(a))return this.error("variable "+n+" is not an inventory!");if(this.args.length>2){if("$"!==(i=this.args[2].trim())[0]&&"_"!==i[0])return this.error('variable name "'+this.args[2]+'" is missing its sigil ($ or _)');if(r=Wikifier.getValue(i),!t.is(r))return this.error("variable "+i+" is not an inventory!")}a.linkedList(r,e).attr({id:s,"data-rec":i,"data-self":n,"data-action":e}).addClass("macro-"+this.name).appendTo(this.output)}})}();
// end simple-inventory.min.js
kiltedken commented 1 year ago

I've decided to use the beta version as it fits what I'm looking for more! You can just close this as far as I'm concerned. Thanks again!

ChapelR commented 1 year ago

I should still look into this. Not sure what the first error about Drop and Take not having a sigil is about, that seems like a major bug.

ChapelR commented 4 months ago

Ending support for SI2