<<include "Inventory">>\
!! Store
<<nobr>>
<<for _item, _price range $store_inventory>>
<<set _lbl to `_item - $${_price}`>>
<<if $player_inventory.includes(_item)>>
<<set _err to `You already have the ${_item}.`>>
<<elseif $gold < _price>>
<<set _err to `You can't afford the ${_item}.`>>
<<else>>
<<set _err to null>>
<</if>>
<p class="store_item">
<<if _err>>
<button disabled @title=_err>_lbl</button>
<<else>>
<<capture _item, _price>>
<<button _lbl>>
<<run
$gold -= _price;
$player_inventory.push(_item);
Engine.play(passage());
>>
<</button>>
<</capture>>
<</if>>
</p>
<</for>>
<</nobr>><<run
$gold = 50;
$player_inventory = ["ratty wallet"];
$store_inventory = {
"cheap shirt" : 10,
"novelty socks": 30,
"expensive shirt": 50
};>>[[Explanation]]!!! Representing the inventory
The player's inventory is stored as an array of item names.
The shop's inventory is represented as an associative array where the keys are the item names and the values are their prices.
Although the player's gold appears in the inventory section, it is stored as a separate value.
This demo assumes that the player will only have one of each item.
!!! Adding a second shop
To display the items on sale, the shop page iterates over the key-value pairs of {{{$store_inventory}}} with a {{{for}}} loop.
Since {{{$store_inventory}}} only appears once at the start of the {{{for}}} loop, you can add another store in three steps:
<ol><li>Duplicate and rename the "Shop Demo" passage.</li><li>Define another associative array of items and their prices.</li><li>Change the variable name in the {{{for}}} statement.</li></ol>\
!!! Tooltips
Items that can't be purchased are shown as greyed-out buttons.
Hovering over a disabled button will bring up a tool tip that explains why you can't buy the item. Either it has already been purchased, or you don't have enough money.
!!! Using variables in HTML attributes
In the following code, Sugarcube replaces {{{_lbl}}} with its current value but it treats {{{_err}}} as a regular string that doesn't need to be replaced:
{{{
<button disabled title=_err>_lbl</button>
}}}
Prefix the {{{title}}} attribute with an @ sign to properly set the title attribute to the value of {{{_err}}}.
{{{
<button disabled @title=_err>_lbl</button>
}}}
Here's an interactive example:
<<set _tooltip to "This tooltip is displaying correctly.">>\
<p><button title=_tooltip>Goofus</button> <button @title=_tooltip>Gallant</button></p>\
!!! Updating the store after a purchase
Clicking a button does not automatically update the page when it changes something.
Calling {{{Engine.play(passage())}}} re-runs the current passage and shows the player what has been changed.!! Inventory
<<nobr>>
<ul>
<li>$gold gold</li>
<<for _item range $player_inventory>>
<li>_item</li>
<</for>>
</ul>
<</nobr>>