Early development: IFLoom can change until 1.0. What's stable
IFLoom
First-party plugins

Shop

The shop plugin adds vendors who sell things for any spendable stat, with stock, restocking, selling back and daily discounts.

@ifloom/plugin-shop adds vendors the player buys things from and sells them back to, for prices in any spendable stat, such as coins, energy or both. A vendor is an entity carrying the shop/vendor trait, and the plugin keeps how many of each good it has left.

The shop is an optional shortcut. A game in the Twine style writes a purchase as a choice that costs coins and sets a kv key, and the shop saves writing that for every good: prices in any stat, stock, restocking, discounts, selling back and refusals with reasons. It hands a bought thing over with receive, so the game's receivers, such as the wardrobe or the inventory, keep it, in the game's receivers order. A good with deliver: false gives nothing and only runs its onBuy, so a shop works in a game with no receivers at all. The shop names no plugin to deliver to. It needs no other plugin, and it cooperates with the calendar for opening hours and days, and with places for where a vendor stands. Add a plugin installs it, and Open a shop, a job board or another panel opens a vendor's counter.

In the showcase: examples/showcase/src/story/cafe.ts, whose counter sells sandwiches, two flapjacks a day and the newspaper, buys back at half price and marks one good down each day, with the prices in examples/showcase/src/world/things.ts.

import {
  shop,
  vendorsOf,
  vendorOf,
  sellableOf,
  type DiscountDef,
  type GoodDef,
  type GoodView,
  type Restock,
  type Sellable,
  type ShopOptions,
  type ShopState,
  type Stock,
  type ShopView,
  type StockRecord,
  type Vendor,
  type VendorDef,
  type VendorView,
} from '@ifloom/plugin-shop'

shop

The plugin's factory, which returns the plugin with the id shop. It takes ShopOptions. The vendors are entities, so a mod can change them. Every field of its result is in shop, and its helpers are listed under Functions.

The plugin brings the kind vendor in its own content, unique and not listed. A vendor holds nothing: the plugin keeps each good's stock in its own state.

import { loadGame, type Content } from '@ifloom/engine'
import { calendar } from '@ifloom/plugin-calendar'
import { places } from '@ifloom/plugin-places'
import { shop } from '@ifloom/plugin-shop'

declare const town: Content

export const { game } = loadGame([town], { id: 'small-town', title: 'Small Town', plugins: [calendar(), places({ start: 'flat' }), shop()] })

ShopOptions

The plugin's settings. onBuy runs for each one of anything bought from any vendor, after the good's and the vendor's own, and onSell for each one sold back. In both, '$' is the thing. Every field is in ShopOptions.

shop({ onBuy: [{ kv: 'purchases', by: 1 }] })

Content

VendorDef

A vendor the game declares in entities, written with shop.vendor(): the entity's fields and the Vendor trait's fields side by side. Every field is in VendorDef.

shop.vendor() returns an EntityDef of the kind vendor with the trait's fields in traits['shop/vendor']. The plugin's calls name a vendor of that kind by its bare id, shop.buy('counter', …), and its entity is vendor:counter. of makes the vendor an entity of another kind, such as a person who sells, and the calls then name it by its whole reference, shop.buy('character:ava', 'food:bun').

import type { Content } from '@ifloom/engine'
import { places } from '@ifloom/plugin-places'
import { shop } from '@ifloom/plugin-shop'

export const cafe: Content = {
  kinds: [{ id: 'food', label: 'Food', listed: false }],
  entities: [
    { id: 'sandwich', of: 'food', name: 'sandwich', description: 'Cheese and pickle.', traits: { ...shop.sellable({ coins: 4 }) } },
    { id: 'flapjack', of: 'food', name: 'flapjack', description: 'Oats and syrup.' },
    shop.vendor({
      id: 'counter',
      name: 'The counter',
      blocked: [places.onlyAt(['cafe'], { string: 'shop/notHere' }, { hide: true }), shop.hours(['morning', 'afternoon'])],
      buysBack: 0.5,
      discounts: { off: 0.5 },
      goods: [{ entity: 'food:sandwich' }, { entity: 'food:flapjack', price: { coins: 2 }, stock: 2, restock: 'day' }],
    }),
  ],
}

The loader merges entities by reference, so a pack's vendor:counter replaces the counter whole. A pack that changes only the goods gives a traits row instead, which replaces the whole trait and keeps the entity's name.

GoodDef

One thing a vendor sells, an entry of its goods. Every field is in GoodDef.

entity names the thing by reference, and a vendor sells each thing once. Goods always name an entity: a game that keeps things in kv keys declares a light one, a name and no traits. price is what one costs, by stat, and with no price the good costs the thing's Sellable price. A good whose when doesn't hold isn't on offer, so the view leaves it out and shop/buy refuses it as if the vendor didn't sell it.

stock is a Stock. deliver says where buying one puts it:

  • Left out, buying runs { receive: entity }, so whichever receiver claims the thing first keeps it.
  • A plugin's id gives it to that receiver only, as a receive's via does, such as deliver: 'wardrobe'.
  • false gives nothing, so the purchase is only its onBuy.

onBuy runs for each one bought, after it's given, then the vendor's onBuy, then the game's (ShopOptions). onSell runs the same way for each one sold back. In both, '$' is the thing. A coffee machine that goes straight to the kitchen is a kv flag:

import type { Content } from '@ifloom/engine'
import { shop } from '@ifloom/plugin-shop'

export const homeStore: Content = {
  kinds: [{ id: 'gadget', label: 'Gadget', listed: false }],
  entities: [
    { id: 'coffeeMachine', of: 'gadget', name: 'coffee machine' },
    shop.vendor({
      id: 'homeStore',
      name: 'Home store',
      goods: [{ entity: 'gadget:coffeeMachine', price: { coins: 80 }, stock: 'once', deliver: false, onBuy: [{ kv: 'kitchen.coffeeMachine', to: true }] }],
    }),
  ],
}

Stock

How many of a good a vendor has. Its values are in Stock.

  • A number is what the vendor starts with, and the good is sold out when none are left. With restock, it's topped back up to that number. Selling one back adds one.
  • 'unlimited', the default, never runs out.
  • 'once' sells out after one, for upgrades and unique things. It's the default for a unique thing, which also shows as sold out while the player owns it.

Restock

When a good with a number stock comes back up to it, 'turn' or 'day'. Its values are in Restock.

A day is the calendar's day, or a turn in a game without the calendar. A good with no restock is never topped up. The stock is worked out when it's read, so nothing writes a restock until play changes the good again.

DiscountDef

How a vendor marks goods down each day, in its discounts. Every field is in DiscountDef.

Each day, count of the vendor's goods (1 if left out) cost off less, a fraction such as 0.25. The plugin draws which ones from the save's seed, the vendor and the day, so the pick is the same every time the player looks that day, on every replay, and after a reload. The plugin rounds a marked-down price to the nearest whole number.

Traits

Vendor

The data of the shop/vendor trait, which makes any entity carrying it a vendor the player buys from. Every field is in Vendor. The plugin types it in TraitRegistry, so traitOf reads a Vendor.

FieldMeaning
blockedBlocked entries that refuse buying and selling while their when holds, with the reason of the first that holds. An entry with hide says where the vendor is, and while it holds the vendor isn't here. Any other entry closes the vendor, and its reason is the view's closed. The vendor trades everywhere and always with none.
goodsThe goods on offer, in the order the view lists them.
buysBackThe fraction of a thing's full price the vendor pays to take one back, from 0 to 1. The vendor takes nothing back if left out.
discountsThe vendor's daily discounts. None if left out.

shop.hours(periods, reason?) writes a blocked entry that closes the vendor outside these periods of the calendar's day, { when: shop.outside(...periods), reason }. Its reason is the shop/closed string if left out, so a game rewords every closed counter at once. In a game without the calendar there is no period, so opening hours never close a vendor. For days of the week, add an entry beside it, such as { when: calendar.weekend(), reason: 'No market at weekends.' }.

A vendor that stands somewhere lists places.onlyAt() in its blocked with hide, as the counter does above. Away from the café, buying and selling are refused with the entry's reason, and the vendor's here is false, so a UI that lists the vendors here leaves it out. The entry's when is places.away('cafe'), which never holds in a game without places, so there the vendor sells everywhere.

A vendor's blocked and its location's blocked are separate. The location's stops the player walking in, and the vendor's stops it trading, so the showcase sets both to close the café and its counter together.

Sellable

The data of the shop/sellable trait, a thing's price wherever a vendor sells it without a price of its own. Every field is in Sellable.

shop.sellable(price) writes the trait, to spread into traits beside other plugins' traits, such as the inventory's usable. The trait goes on a kind as a default, on an entity, or in content's traits table, where a mod can change a price. A thing made in play like a sellable one has its price.

import type { Content } from '@ifloom/engine'
import { shop } from '@ifloom/plugin-shop'

export const market: Content = {
  kinds: [{ id: 'fruit', label: 'Fruit', listed: false, traits: { ...shop.sellable({ coins: 1 }) } }],
  entities: [
    { id: 'apple', of: 'fruit', name: 'apple' },
    { id: 'fig', of: 'fruit', name: 'fig', traits: { ...shop.sellable({ coins: 3 }) } },
  ],
}

Conditions

Each condition is a plugin call, written by the helper beside it. An unknown vendor or thing is false.

shop/open

Holds while the vendor is open, when none of its blocked entries without hide holds. Where the player is doesn't matter.

{ 'shop/open': { vendor: 'counter' } } // shop.vendorOpen('counter')

shop/outside

Holds while the calendar's period of the day is none of these. It never holds in a game without the calendar. shop.hours() closes a vendor with it.

{ 'shop/outside': { period: ['morning', 'afternoon'] } } // shop.outside('morning', 'afternoon')

shop/inStock

Holds while the vendor offers the thing now and has at least one left. It always holds for a good that never runs out, while the good is on offer.

{ 'shop/inStock': { vendor: 'counter', entity: 'food:flapjack' } } // shop.inStock('counter', 'food:flapjack')

Commands

Both commands list the effects they apply, so a lock with effect sees them, and a lock names them shop/buy and shop/sell, or both as shop/*. Paying applies a stat effect for each stat, so the game's onStat hook sees it. "You" is whoever the player is playing, 'you'.

shop/buy

Pays today's price for count of the thing (1 if left out), takes them from the stock, gives them to you with { receive: entity, by: count } (unless the good's deliver is false), then runs the onBuy effects for each one.

{ 'shop/buy': { vendor: 'counter', entity: 'food:flapjack' } } // shop.buy('counter', 'food:flapjack')

The command tells the engine what it spends (the spends of a plugin command), so a button that sends it shows today's price, discount included, written through each stat's format. Its disabled is the reason the command would be refused. A location's action that sends shop.buy is a shop on its own, with no counter.

The plugin refuses it, in this order:

  1. With That isn’t for sale here. (shop/unknown) for a vendor or thing the game doesn't have, or a good whose when doesn't hold.
  2. With the reason of the vendor's first blocked entry that holds, such as You aren’t at that shop. or Closed..
  3. With Sold out. (shop/soldOut) when the vendor has fewer than count left.
  4. With the stat's lacking line, such as You need 4 coins., when you have too little.

shop/sell

Takes count of the thing back from you with { release: entity, by: count } (1 if left out), pays the vendor's buysBack fraction of its full price, rounded down for each one, and runs the onSell effects for each one. A good with a number stock, or 'once', goes back into stock.

{ 'shop/sell': { vendor: 'counter', entity: 'food:sandwich' } } // shop.sell('counter', 'food:sandwich')

The plugin refuses it, in this order:

  1. With That isn’t for sale here. for a vendor or thing the game doesn't have, or a good whose when doesn't hold.
  2. With They don’t buy things back. (shop/noBuyBack) for a vendor with no buysBack.
  3. With the reason of the vendor's first blocked entry that holds.
  4. With You don’t have that. (shop/notOwned) when you own fewer than count, across every receiver (owned).

State

ShopState

The stock a save keeps at state.plugins.shop, in stock, by vendor and then by thing: only the goods play changed, each as a StockRecord. The plugin reads the goods and their starting stock from content. Every field is in ShopState. A UI reads ShopView instead.

StockRecord

What a save keeps of one good's stock once play changed it. Every field is in StockRecord.

left is how many the vendor had left then, and at is the turn or the day it was written, which a restock compares with now, or 0 for a good that never restocks. When the turn or the day moves past at, the stock reads as full again before anything writes it.

View

The plugin adds nothing to the room or the screen. A vendor shows when content opens its counter in the shop panel with shop.open(vendor), or when a UI lists the vendors itself.

ShopView

The vendors as the player sees them, in view.plugins.shop. Every field is in ShopView.

vendors lists every vendor, in the order the game declares them, those made in play last. panel is the vendor whose counter the open shop panel shows, found by its with.vendor as an id or a whole reference through the engine's panelOf, or null while no shop panel is open.

{ vendors: [{ id: 'counter', ref: 'vendor:counter', name: 'The counter', here: true, closed: null, buysBack: true, goods: [ … ] }], panel: null }

VendorView

One vendor as the player sees it, an entry of vendors. Every field is in VendorView.

id is how the commands name the vendor, its bare id for one of the vendor kind and its whole reference for any other. here is true while none of its blocked entries with hide holds. closed is the reason of its first blocked entry without hide that holds, or null while it's open. goods lists the goods on offer now, leaving out one whose when doesn't hold or whose thing the game doesn't have.

GoodView

One good as the player sees it, an entry of a vendor's goods. Every field is in GoodView.

buy and sell are RenderedChoice buttons labelled with the thing's name, each with today's price and the reason it's refused in disabled. sell and sellFor are null for a vendor that takes nothing back. stock is null for a good that never runs out, owned counts what you own across every receiver, and off is today's discount. fullPrice is the price before the discount, and null on a day the good isn't marked down.

Render a shop counter renders this view in Plain JS, React and Vue.

React UI

The React UI is optional: the @ifloom/plugin-shop/react subpath renders a vendor's counter for a game that uses @ifloom/react, and a game rendered another way never loads it. Show plugins in the React UI adds it to a game.

shopUi

The plugin's PluginUi, listed in mountGame's plugins. It renders the shop panel as the open vendor's ShopCounter, titled with its name, and adds nothing else to the layout. Its type is in shopUi.

SHOP_WORDS

The words the shop UI uses, by key, which a game rewords as ui.<key> in its strings as it does the React UI's own. Its value is in SHOP_WORDS.

KeyMeaning
ui.buyBuy, the label of a good's buy button.
ui.sellForSell for {price}, the label of a good's sell button.
ui.stockLeft{n} left, the stock of a good that can run out.
ui.ownedYou have {n}, the count you hold.
ui.percentOff{percent}% off, the badge on a good marked down today.
ui.noGoodsNothing for sale., the line of a vendor with nothing on offer.

ShopCounter

Renders one vendor's goods from its VendorView. Its props are in ShopCounterProps.

A closed vendor shows its closed line above its goods. Each good shows its picture, name and description, today's discount with the full price struck out, the stock left and the count you hold. Its Buy button is a ChoiceButton from the good's buy, so it shows the price and the reason it's refused, such as Sold out.. A Sell for 2 coins button from the good's sell follows while the vendor buys back and you hold one.

A game replaces it as ShopCounter in components. Its parts are shop (with data-vendor, and data-closed while closed), shop-closed, shop-empty, goods, good (with data-good), good-image, good-name, good-desc, good-details, good-off, good-full-price, good-stock, good-owned, good-actions and choice.

ShopDialog

Renders the vendor with the id vendorId as a ShopCounter in a dialog titled with its name, closed while vendorId is null or names no vendor. Its props are in ShopDialogProps.

It sends no command and keeps nothing in the state, so it suits a button that is only UI. Content opens a counter that the save remembers with shop.open() instead. A game replaces it as ShopDialog in components, and its parts are dialog, dialog-overlay, dialog-title and dialog-close.

import { useState } from 'react'
import { Button } from '@ifloom/react/kit'
import { ShopDialog } from '@ifloom/plugin-shop/react'

export function CounterButton() {
  const [open, setOpen] = useState<string | null>(null)
  return (
    <>
      <Button variant="outline" onClick={() => setOpen('counter')}>
        The café counter
      </Button>
      <ShopDialog vendorId={open} onClose={() => setOpen(null)} />
    </>
  )
}

useShop

Returns the shop's view from the running game with the vendors here and a buy and a sell that send its commands, or null in a game without the plugin. It re-renders when the view changes. Its signature is in useShop.

ShopControls

The value useShop returns, a ShopView with here, buy(vendor, entity, count?) and sell(vendor, entity, count?). Every field is in ShopControls. here lists the vendors whose here is true, and buy and sell return the runner's Result, so a refusal comes back with its reason.

import { useShop } from '@ifloom/plugin-shop/react'

export function QuickSandwich() {
  const shop = useShop()
  const counter = shop?.here[0]
  const sandwich = counter?.goods.find((good) => good.entity === 'item:sandwich')
  if (!shop || !counter || !sandwich) return null
  return (
    <button disabled={Boolean(sandwich.buy.disabled)} onClick={() => shop.buy(counter.id, 'item:sandwich')}>
      A sandwich to go
    </button>
  )
}

Functions

The helpers are properties of shop and write its calls, typed:

  • shop.vendor(def) returns a vendor's EntityDef.
  • shop.vendorRef(vendor) returns a vendor's entity reference, 'vendor:counter' for 'counter', and a reference as written.
  • shop.sellable(price) returns the shop/sellable trait, to spread into traits.
  • shop.hours(periods, reason?) returns a blocked entry for opening hours.
  • shop.buy(vendor, entity, count?) and shop.sell(vendor, entity, count?) return the commands as a CommandRef.
  • shop.vendorOpen(vendor), shop.outside(...periods) and shop.inStock(vendor, entity) return the conditions.
  • shop.open(vendor) returns the engine's panel effect that opens the vendor's counter, { panel: 'shop', with: { vendor } }.

The café's action opens the counter:

import type { ActionDef } from '@ifloom/engine'
import { shop } from '@ifloom/plugin-shop'

export const counter: ActionDef = { id: 'counter', label: 'Go to the counter', effects: [shop.open('counter')] }

vendorsOf

Returns every entity in the game now that carries the shop/vendor trait, as references, those content declares in its order and then those made in play. Its signature is in vendorsOf.

vendorOf

Returns the Vendor trait of the vendor with this id or reference, leaving out any good that names no thing, or undefined for anything that isn't a vendor. Its signature is in vendorOf.

sellableOf

Returns a thing's Sellable trait, read through the thing it was made like, or undefined for a thing without one. Its signature is in sellableOf.

import { sellableOf, vendorOf, vendorsOf } from '@ifloom/plugin-shop'

vendorsOf(state, game) // ['vendor:counter']
vendorOf(state, game, 'counter')?.buysBack // 0.5
sellableOf(state, game, 'food:sandwich')?.price // { coins: 4 }

Checks

When the game loads, the plugin checks the shop/vendor trait on each vendor. A vendor's problems are pinned on the content or pack it came from, with where as trait shop/vendor on <ref>.

ProblemCause
a vendor needs its goods: goods: [] for noneThe trait has no goods list.
a good names no thing: write { entity: "kind:id" }A good has no entity.
good gem:ruby: unknown entity "gem:ruby"A good, its price or its when names something the game doesn't have.
sells "food:apple" twiceTwo goods name the same thing.
good gem:ruby: no price: give the good a price, or the thing a shop/sellable traitA good has no price, and its thing has no shop/sellable trait.
good stone:moon: price in stat "charm", which is not spendableA price is in a stat that isn't spendable, or one that is derived.
good stone:moon: price must be 0 or moreA price is negative.
good stone:moon: stock must be a whole number, 0 or more, stock is a number, "unlimited" or "once"A stock isn't one of its forms.
good stone:moon: restock needs a number stockA good has restock and no number stock.
good stone:moon: deliver is false or a plugin's idA deliver isn't one of its forms.
no plugin of the game keeps things, so this does nothing: …A good is delivered in a game with no receiver. Give it deliver: false, or add a receiver such as the inventory.
via names "box", which keeps no thingsA deliver names a plugin that isn't a receiver.
good gem:ruby: a unique thing has a stock of 1 at mostA unique thing's stock is above 1.
buysBack must be between 0 and 1, discounts.off must be more than 0 and at most 1buysBack or discounts.off is out of range.
blocked: unknown entity "location:moon"A blocked entry names something the game doesn't have, such as a location in places.onlyAt(), which places reports.

A shop/buy, shop/sell or condition that names a vendor or thing the game doesn't have gives unknown entity "vendor:kiosk" where it's written, and one that names an entity without the trait gives "item:paper" has no shop/vendor trait. A count that isn't a whole number from 1 is reported too. A shop panel opened for a vendor the game doesn't have gives unknown entity "vendor:kiosk", and one with no vendor gives the shop panel needs a vendor: { vendor: "<id>" }. The shop/sellable trait's price is checked on each entity that carries it.

Strings

A game, a pack or a translation rewords these by their full key in its strings.

KeyMeaning
shop/unknownThat isn’t for sale here., the refusal of a vendor, thing or good that isn't on offer.
shop/notHereYou aren’t at that shop., a reason for a vendor's places.onlyAt() entry, written { string: 'shop/notHere' }. The plugin doesn't use it itself.
shop/closedClosed., the reason shop.hours() writes when given none.
shop/soldOutSold out.
shop/noBuyBackThey don’t buy things back.
shop/notOwnedYou don’t have that.

Caveats

  • A traits row replaces the whole shop/vendor trait, so a mod that changes a vendor's goods gives every field the vendor needs, its blocked included.
  • Selling back pays from the full price, not from today's discounted one.
  • Selling back takes the thing from whichever receivers keep it, in the game's receivers order.
  • Opening a counter doesn't move the player, so a counter opened away from a vendor with a places.onlyAt() entry shows every button refused with that entry's reason.

Last updated on

On this page