Recipe for an Inventory system in Twine Sugarcube
The anatomy of an inventory system: (a) the arbitrarily long return function (b) creating the YourInventory passage with a [noreturn] tag (c) creating the StoryMenu passage so we can link to YourInventory (d) give the player some starting inventory items (optional)
(a) The Arbitrarily Long Return function
/* Trigger the following code at the start of navigation to a new passage. */
$(document).on(":passagestart", function (event) {
/* Make sure the current passage doesn't have a "noreturn" tag. */
if (!tags().includes("noreturn")) {
/* If it doesn't, then set $return to the current passage name. */
State.variables.return = passage();
}
});
In case the above inline code doesn't display correctly, or breaks at some point, here is the Github gist of the above Arbitrarily Long Return function.
Next I provide the code for the YourInventory
passage and the two widgets it makes use of.
the passage code:
<<nobr>>
<<if $inventory eq undefined>>
Inventory is undefined
<<else>>
<<InventoryItemCount>>
<<InventoryItemListing>>
<</if>>
<</nobr>>
and the code for the two widgets:
<<widget "InventoryItemCount">>
/* This widget prints a message to the browser window telling the player how many items are in her inventory. I still need to add the Twinescript needed to accomplish this -- but all I have to do is copy/paste it from the YourInventory passage. */
<<nobr>>Your inventory contains:
<<if $inventory.length lt 1>>
nothing
<<elseif $inventory.length eq 1>>
1 item
<<else>>
<<= $inventory.length>> items
<</if>>
<</nobr>><</widget>>
<<widget "InventoryItemListing">>
/* This widget prints the inventory's items,
one per line */
<<nobr>><<if $inventory.length eq 1>>
$inventory[0]
<</if>>
<<if $inventory.length gt 1>>
<<= $inventory.join(`<br>`)>><br>
<</if>>
<</nobr>><</widget>>
And, against future need, here is a gist of the above passage code and code for the two widgets.
One option for making the YourInventory
passage available during play is to add the following line to special passage StoryMenu
:
<<link "Inventory">><<goto YourInventory>><</link>>
One way to give the player some beginning inventory items would be to set them in special passage StoryInit
:
<<set $inventory to ['a canteen', 'a pocket knife', 'a handkerchief', 'a flashlight', 'a revolver']>>