RB §9.1. Food

Inform provides an either/or property called "edible" and an action, "eating", for consuming edible things:

The lardy cake is edible. After eating the lardy cake, say "Sticky but delicious."

For eating something not immediately to hand, see Lollipop Guild ★★★. Delicious, Delicious Rocks ★★★, conversely, adds a sanity check which prevents the player from automatically taking inedible things only to be told they can't be eaten.

Inform does not normally simulate taste or digestion, but to provide foods with a range of flavours, see Would you...?; to make eating different foods affect the player differently, see Stone, or for the extreme case of poisoning foods, Candy. In MRE, hunger causes the player problems unless he regularly finds and eats food.

See also

Liquids for things to drink
Dispensers and Supplies of Small Objects for a pizza buffet table from which the player may take all the slices he wants

Examples

48. Would you...?

For instance, if we want to give some objects a flavor:

paste.png "Would you...?"

The House is a room. The mouse is an animal in the House.

The player carries some green eggs and a ham.

A food is a kind of thing that is edible. Food has some text called flavor. The flavor of food is usually "Tolerable."

Things are, in general, not edible by default, so we have to make them edible specifically in order to allow them to be eaten by the player. Here we've defined food to be edible by default, and we have given it a standard piece of flavor text.

The ham and the green eggs are food. The flavor of the green eggs is "Delicious!"

After eating something:
    if the noun provides the property flavor, say "[the flavor of the noun][paragraph break]";
    otherwise say "It's [noun]-flavored."

Note that we use "if the noun provides a flavor..." to make sure that the property exists before attempting to use it. Otherwise, there is the risk that we will try to print a property that does not exist, resulting in errors in the game.

We will only get the "It's [noun]-flavored." response if we successfully eat something that is not a food and does not have flavor text. To test this feature, let's suppose something that isn't exactly food but can theoretically be chewed on:

The player carries some paper. The paper is edible.

Test me with "eat ham / eat green eggs / eat paper".

133. Candy

Suppose we want to give the player a bag of candies, of which a random one is poisonous. We can pick which one should be poisoned at the start of play, like this:

paste.png "Candy"

The plural of piece of candy is pieces of candy. A piece of candy is a kind of thing. A piece of candy is always edible. Four pieces of candy are in the Halloween bag.

Toxicity is a kind of value. The toxicities are safe and poisonous. A piece of candy has a toxicity. A piece of candy is usually safe.

The Porch is a room. The player carries the Halloween bag.

After eating a poisonous piece of candy:
    say "Oh, that didn't taste right at all. Oh well!"

When play begins:
    now a random piece of candy is poisonous.

Test me with "eat candy / g / g / g".

143. MRE

Many older interactive fiction games required the player to find food and eat on a regular basis in order to avoid death. This effect was often unrealistic (since most people can survive much longer than a few hours without eating) and is often seen as an annoyance. However, for the sake of argument, suppose that we do want to construct a hunger-and-death system.

To make things a little more interesting, we will postulate that different foods are differently filling, so that if the player manages to find something really caloric, he is off the hook on his hunger search for a while.

We will also implement the system so that the player gets messages when he is hungry, then dies a short time later. (The times involved are ludicrously short, but this allows us to see the effects within a simple example. In a real game we would want to allow a considerably longer timer for the hunger to play out.)

First, a little scene-setting:

paste.png "MRE"

When play begins:
    now the right hand status line is "[time of day]";
    say "The procedure was painless at first: increased strength was the first sign, followed by a sensation of delayed time, as though everyone around you moved more slowly. Your ability to dodge and perform feats of agility doubled, then trebled. You were heralded as a triumph of medicine. They told you there would be no side effects worth speaking of.

They were wrong."

The Base Camp Larder is a room. "This room has been reinforced after each incident -- and there have been dozens in the last two months -- so that it now rivals Fort Knox. Only your new skill and speed enabled you to dodge the motion sensors, knock out the computerized security system, fool the retinal scanner, and punch a hole in the steel containment grating. But you're inside now."

Now we define our food, and add some special instructions for what happens to our hunger counters when the food is eaten:

Food is a kind of thing. Food is usually edible. Food has a time called the satisfaction period. The satisfaction period of a food is usually 5 minutes.

A person can be hungry or replete. The player is hungry.

The Larder contains an apple, a candy bar, and a large plate of pasta. The apple, the candy bar, and the pasta are food. The satisfaction period of the apple is 2 minutes. The satisfaction period of the pasta is 125 minutes.

Check eating something which is not food:
    say "[The noun] might be edible, but it's not what you'd consider really food."

Check eating something when the player is not hungry:
    say "You're not hungry right now."

Carry out eating something:
    now the player is replete;
    hunger resumes in the satisfaction period of the noun from now.

The first of those two phrases, "now the player is replete", causes the player to cease to be hungry; the second one sets up a future event in which the hunger sets in again. The length of time until that event depends on how satisfying the specific food is. Now we define that event:

At the time when hunger resumes:
    starvation occurs in three minutes from now;
    now the player is hungry.

At the time when starvation occurs:
    if the player is hungry, end the story saying "You have starved".

Note "if the player is hungry": it is possible that the starvation event will be set up but the player will eat before it occurs; in that case, we want it not to take effect.

And now, since we really ought to give the player some warning of what is happening to him:

Every turn when the player is hungry:
    choose a random row in the Table of Hunger Complaints;
    say "[hunger entry][paragraph break]".

Table of Hunger Complaints
hunger
"Gosh, you're starving."
"It feels as though you haven't eaten in days. Weeks, almost."
"The world seems to slow down and everything becomes sharper and brighter. You are a hunter, a hunter of foodstuffs."
"You find yourself staring at [the random visible thing that is not the player] and wondering how it would taste."

Test me with "eat apple / z / z / z / eat candy bar / z / z / z / z / z / z / z / z / z".

390. Stone

A thing can have a rule as a property, if we like. Here we are going to allow the player to make a soup whose effects will depend on its ingredients. Each ingredient will have its own "food effect" rule, to be followed when the food is eaten.

Note that there are other, slightly less cumbersome ways to do the same thing -- we will see in the chapter on Rulebooks that we could make a "food effects rulebook" and then write a number of rules such as "food effects rule for carrots" or "food effects rule for the stone". Nonetheless, we demonstrate rules-as-properties here for the sake of thoroughness.

So:

paste.png "Stone"

A food is a kind of thing that is edible. A food has a rule called the food effect.

Carry out eating a food:
    if a food is part of the noun:
        repeat with item running through things which are part of the noun:
            if item is a food, follow the food effect of the item;
    follow the food effect of the noun.

Report eating a food:
    say "You eat [the noun]. [diagnosis of the player]";
    stop the action.

To say diagnosis of (victim - a person):
    if the victim is ill:
        say "You are ill.";
        rule succeeds;
    otherwise:
        say "You are healthy. ";
    if the victim is awake, say "You are wide awake. ";
    otherwise say "You are sleepy. ";
    if the victim is bright-eyed, say "Your eyesight is clear. ";
    otherwise say "Your eyesight is dim. ";
    if the victim is weak, say "You are weak. ";
    otherwise say "You are strong. ";
    if the victim is hungry, say "You are hungry.";
    otherwise say "You are well-fed."

And now to provide some particular foods:

Some carrots are a food. The food effect of carrots is the bright-eye rule. This is the bright-eye rule: now the player is bright-eyed.

Some potatoes are a food. The food effect of the potatoes is the sleepiness rule. This is the sleepiness rule: now the player is sleepy.

The broth is a food. The indefinite article of the broth is "some". The food effect of broth is the filling rule. This is the filling rule: now the player is full.

The hambone is a food. The food effect of the hambone is the heartiness rule. This is the heartiness rule: now the player is strong. Instead of eating the hambone: say "You cannot just eat a bone!"

The poison ivy is a food. "Poison ivy grows nearby." The food effect of poison is the illness rule. This is the illness rule: now the player is ill.

A person can be bright-eyed or blind. The player is blind.

A person can be well or ill. The player is well.

A person can be hungry or full. The player is full.

A person can be strong or weak. The player is weak.

A person can be awake or sleepy. The player is sleepy.

The broth is in the kettle. The kettle is on the fire. The fire is in the Clearing. The Clearing is a room.

The player carries the hambone, the potatoes, and the carrots. The ivy is in the clearing.

Instead of examining the broth:
    if something is part of the broth, say "In the broth, [a list of things that are part of the broth] float[if exactly one thing is part of the broth]s[end if].";
    otherwise say "It is just a thin broth with no other ingredients."

Instead of inserting something into the broth: try inserting the noun into the holder of the broth.

Instead of taking the broth: say "You cannot take the broth in your bare hands."

And the following is a relatively unimportant nicety:

To sink is a verb.

After inserting a food which is not the broth into a container which contains the broth:
    now the noun is part of the broth;
    say "[The noun] [sink] into [the second noun], making the broth richer."

Test me with "x broth / eat hambone / put hambone in kettle / x broth / put potatoes in broth / x broth / eat carrots / eat broth / put ivy in kettle / eat ivy".

197. Delicious, Delicious Rocks ★★★

In some cases, we may want to add new stages to action processing. One possibility is a stage where we check the sanity of what the player is trying to do before executing any of the other commands; so that we avoid, for instance

>EAT ROCK
(first taking the rock)
That's plainly inedible.

Here is how we might insert such a stage in our action processing, using rulebook manipulation.

paste.png "Delicious, Delicious Rocks"

Section 1 - Procedure

The sanity-check rules are a rulebook.

This is the sanity-check stage rule:
    abide by the sanity-check rules.

The sanity-check stage rule is listed after the before stage rule in the action-processing rules.

Section 2 - Scenario

Candyland is a room. The lollipop tree is an edible thing in Candyland. The genuine rock is a thing in Candyland.

Sanity-check eating an inedible thing:
    say "Your digestion is so delicate -- you're sure [the noun] wouldn't agree with you." instead.

Test me with "eat lollipop / eat rock".

Notice that now Inform does not try taking the rock before rejecting the player's attempt to eat it.

It is of course possible to get the same effect with

Before eating an inedible thing:
    say "Your digestion is so delicate -- you're sure [the noun] wouldn't agree with you." instead.

...and in a small game with few rules, there's not much reason to add an extra stage. The ability to modify the stages of action processing becomes useful when we have a fairly large game with sophisticated modeling and want to be sure that some kinds of message (such as the sanity-check) are always handled before other things that we might be doing at the before stage (such as generating implicit actions like opening doors before going through them).

RB §9.2. Bags, Bottles, Boxes and Safes

The kind "container" allows one thing to contain others. Things are sometimes containers automatically, sometimes by instruction:

The match is in the matchbox. The bucket is a container.

The matchbox, like the bucket, is a container. Containers come in all sizes and have a variety of behaviours, mainly controlled by the properties we give them: they can be "open" or "closed", "opaque" or "transparent" (when closed), "openable" or not, "lockable" or not, "enterable" or not. The basic ideas of containment are to do with carrying and sometimes hiding the contents, and Inform makes this easy. Allowing for locking and unlocking is again straightforward:

The strongbox is a locked container. The little steel key unlocks the strongbox.

Two built-in extensions enhance and modify the behavior of locks and keys: Locksmith automates a number of steps, automatically unlocking doors when trying to open them (for instance). Skeleton Keys allows us to define multiple keys that unlock the same object, rather than being restricted to one matching key per item.

For a container with a combination lock, rather than a key, see Safety; for a more sophisticated safe requiring digits dialed over multiple turns, see Eyes, Fingers, Toes.

Trachypachidae Maturin 1803 ★★ provides a bottle that is stoppered with a cork: when it is closed, the cork is part of the bottle, but otherwise the cork becomes a separate object we can carry around.

The normal assumption is that there is no problem with any two portable items being carried together, but in reality they may affect each other. (For effects like magnetism, or getting each other wet, or setting each other on fire, see the Physics chapter.) Here is a cat which, if boxed up with one or more items of food, will eat something each turn until all is gone:

The player carries a wicker basket and a scarlet fish. The cat is an animal in the wicker basket. The fish is edible.

Every turn when the cat is in a container (called the bag) and something edible (called the foodstuff) is in the bag:
    remove the foodstuff from play;
    say "With mingled sounds of mewing and chomping, the cat nibbles up [the foodstuff]."

The examples below provide subtler effects, adapting text to the current situation. In Cinco, the container's name changes depending on what it contains: putting beef in a taco allows the player to call it a SHREDDED BEEF TACO. In Unpeeled and Shipping Trunk, the description of something inside a container changes according to other things are alongside it. This is taken further in Hudsucker Industries ★★, which describes the contents of a container as a group.

Finally, any action that destroys a container has to consider what to do with the things inside. Fallout Enclosure ★★★ demonstrates a zapping action that destroys cash registers and shelves but leaves their contents tidily behind.

See also

Liquids for a SHAKE command that makes containers rattle when there are contents
Glass and Other Damage-Prone Substances for opening containers by cutting into them
Fire for fire damage that spreads between containers and their contents, leaving fireproof objects intact
Volume, Height, Weight for containers breaking under the weight of their contents
Heat for keeping things warm in insulated containers
Furniture for chests with lids that can support other objects
Modifying Existing Commands for ways to allow the player to unlock with a key he isn't currently holding

Examples

299. Safety

paste.png "Safety"

The Vault is a room. "Snug yet paranoid, this represents the state of the art in cheerless security." The Safe is here. "A mammoth safe, with a dial which can spin to any number, has pride of place. It must weigh about the same as a small car, so don't get any ideas." Instead of opening the safe, say "The safe opens only when turned to the correct combination."

In the Safe is a silver florin. The Safe is closed and fixed in place. Understand "dial" as the Safe.

Spinning it to is an action applying to one thing and one number. Check spinning it to: if the noun is not the Safe, say "[The noun] does not spin." instead. Report spinning it to: say "Click! and nothing else happens."

Understand "spin [something] to [a number]" as spinning it to.

After spinning the closed Safe to 1384: now the Safe is open; say "Clonk! and the safe door swings slowly open, revealing [a list of things in the Safe]."

Test me with "open safe / spin safe to 1131 / open safe / spin safe to 1384 / x safe / get florin".

321. Cinco

It's fairly common that we want to be able to refer to a container in terms of what it has in it: a bottle of wine, a salt shaker, a chicken sandwich. The player is free to remove the contents again, and the object will go back to using its usual name:

paste.png "Cinco"

Cinco de Mayo Fundraiser is a room.

The taco shell is an edible thing in the Fundraiser. It is a portable container. It has carrying capacity 1.

Understand "[something related by containment] taco" as the taco.

Rule for printing the name of the taco shell while not inserting or removing:
    if the taco contains something (called filling), say "[filling] taco";
    otherwise say "taco shell";
    omit contents in listing.

The player carries shredded beef. It is edible.

The taking action has an object called source (matched as "from").

Setting action variables for taking:
    now source is the holder of the noun.

Report taking something from the taco shell:
    say "You gingerly pick [the noun] out of the taco shell." instead.

Test me with "x taco / put shredded beef in taco / get taco / i / x shredded beef taco / get shredded beef / x shredded beef taco".

339. Shipping Trunk

First to lay some groundwork:

paste.png "Shipping Trunk"

A chest is a kind of container. A chest is always openable. A lid is a kind of supporter. A lid is part of every chest.

Before opening a chest when something (called the obstruction) is on a lid which is part of the noun:
    say "Better remove [the obstruction]." instead.

A thing can be innocent or smelly.

The Storage Unit is a room. The shipping trunk is a closed chest in the Storage Unit. The trunk contains some garlic, a loaf of moldy sourdough, a mildewy bathtowel, a pair of unwashed socks, two dead trout, and a box of baking powder. The garlic, trout, sourdough, bathtowel, and socks are smelly. The baking powder is innocent.

The shipping trunk's lid supports a small card. The description of the small card is "'Please, please do not open this trunk.'"

After opening the trunk:
    if the trunk had been open:
        say "You steel yourself...";
        continue the action;
    otherwise:
        say "There roils up from inside an indescribable funk, which, when you can see straight, you have no trouble attributing to the presence of [a list of smelly things in the trunk]. You also note [a list of innocent things in the trunk] in the corner.".

And now, with that preparation:

Before printing the name of the baking powder when the powder is in a container which contains a smelly thing: say "completely ineffective ".

Test me with "open trunk / examine card / get card / open trunk / get powder / inventory".

344. Unpeeled

paste.png "Unpeeled"

Scullery is a room. A sack is carried by the player. The sack contains a yellow onion. The player carries a cork.

Before printing the name of the onion while listing contents:
    if the holder of the onion contains exactly 1 thing, say "single ".

Test me with "i / put cork in sack / i".

435. Eyes, Fingers, Toes

It is not difficult to implement a safe which can be set to a single number to open; but a more common scenario in the real world is for the safe to open on a sequence of numbers when they have been dialed in the right order.

For IF, this means that we have to keep running track of the last N digits the player has dialed, dropping the first digit and adding a new one to the end each time the player re-dials the safe. This is a perfect occasion for lists:

paste.png "Eyes, Fingers, Toes"

The Addams Wine Cellar is a room. It contains a closed lockable locked container called a safe.

The safe has a list of numbers called the current combination.

The safe has a list of numbers called the true combination. The true combination of the safe is {2, 10, 11}.

Understand "set [something] to [a number]" as setting it numerically to. Setting it numerically to is an action applying to one thing and one number.

Instead of examining the safe:
    if the number of entries in the current combination of the safe is 0,
        say "You haven't dialed the safe to any combination yet.";
    otherwise say "You have dialed the safe to [the current combination of the safe].".

Check setting something numerically to (this is the block setting numerically rule):
    say "[The noun] cannot be set."

Instead of setting the safe numerically to the number understood:
    truncate the current combination of the safe to the last 2 entries;
    add the number understood to the current combination of the safe;
    if the safe is locked and the current combination of the safe is the true combination of the safe:
        say "You dial [the number understood], and [the safe] gives a joyous CLICK.";
        now the safe is unlocked;
    otherwise if safe is unlocked and the safe is closed and the current combination of the safe is not the true combination of the safe:
        say "You spin the dial, and [the safe] snicks locked.";
        now the safe is locked;
    otherwise:
        say "You dial [the number understood] on the safe."

Test me with "x safe / set safe to 10 / x safe / set safe to 29 / x safe / set safe to 2 / x safe / set safe to 10 / x safe / set safe to 11 / open safe / set safe to 14 / close safe / set safe to 15 / open safe".

340. Trachypachidae Maturin 1803 ★★

paste.png "Trachypachidae Maturin 1803"

A bottle is a kind of container. Bottles are usually openable, transparent, and closed. A cork is a kind of thing. A cork is in every bottle.

Understand "cork [something]" as corking.

Understand the command "stopper" as "cork".

Understand "uncork [something]" as uncorking.

Corking is an action applying to one thing.

Check corking:
    if the noun is not a bottle, say "[The noun] cannot be corked." instead.

Carry out corking:
    try closing the noun.

Uncorking is an action applying to one thing.

Check uncorking:
    if the noun is not a bottle, say "[The noun] cannot be uncorked." instead.

Carry out uncorking:
    try opening the noun.

Understand "close [something] with [something preferably held]" as corking it with.

Understand "cork [something] with [something preferably held]" as corking it with.

Corking it with is an action applying to one thing and one carried thing.

Check corking it with:
    if the noun is not a bottle, say "[The noun] cannot be corked." instead;
    if the second noun is not a cork, say "[The second noun] will not fit in [the noun]." instead.

Carry out corking it with:
    try inserting the second noun into the noun instead.

Instead of closing a bottle:
    if a cork (called the item) is carried by the player, try inserting the item into the noun instead;
    otherwise say "You need a stopper of some kind."

Instead of opening a bottle:
    if a cork (called the item) is in the noun, try taking the item instead;
    otherwise say "[The noun] has no stopper."

Carry out inserting a cork into a bottle:
    now the second noun is closed.

After inserting a cork into a bottle:
    say "You stopper [the second noun] with [the noun]."

Before taking a cork when the noun is in a closed bottle (called the item):
    now the item is open.

Instead of taking a cork when the noun is in a bottle (called the item):
    move the noun to the player;
    say "You pull [the noun] from [the item]." instead.

Before printing the name of a bottle (called target) while not inserting, taking, searching, or removing:
    if the target is closed, say "sealed ";
    otherwise say "now open ".

After printing the name of a bottle (called target) while not inserting, searching, examining, or removing:
    if the target contains a noncork thing, say " containing [a list of noncork things in the target]";
    omit contents in listing.

Instead of examining a bottle:
    say "[The noun] contains [a list of noncork things in the noun]."

Definition: a thing is noncork if it is not a cork.

The Doctor's Cabin is a room. "A dark, cramped triangle, like a slice of cake, except that its sharp end has been cut off: and so low that a moderately tall man would strike his head on the deck above if he were to stand upright. Every free surface is covered with sheets of best Venetian looking-glass, to increase the light filtering in. Long use and the carpenter's ingenuity have packed in a folding cot and table, and lockers are built into unlikely places: lockers filled with specimens, skeletons, sketches, drafts and serial letters." The jug is a bottle in the Doctor's Cabin. The jug contains a beetle. The description of the beetle is "The doctor assures you that it is a nondescript."

Test me with "get jug / x jug / open jug / x jug / i / x cork / cork jug / i / uncork jug / i / x jug / get beetle / i / close jug / i / x jug".

342. Hudsucker Industries ★★

In this scenario, the player starts with a bag full of unsorted letters. These can be polite or rude, but he won't know which until he has examined them. What's more, he is allowed to sort the letters, in which case a group of letters will be shown as (for instance) "two polite letters"; but a group of mixed letters, even if they have all been read, will be called "unsorted letters".

Further, the player should be allowed to refer to sorted letters by tone, but not unsorted letters.

To do this, we'll need printing the name... and printing the plural name..., as well as some special understanding rules.

paste.png "Hudsucker Industries"

Tone is a kind of value. The tones are effusive, affectionate, polite, curt, and flamingly rude.

A letter is a kind of thing. The description of a letter is usually "On inspection, it turns out to be quite [tone]." A letter has a tone. The tone of a letter is usually polite.

A letter can be read or unread. A letter is usually unread. Carry out examining a letter: now the noun is read.

Before printing the name of a read letter: say "[tone] ".

Before printing the name of an ungrouped letter: say "random ".

Before printing the plural name of a letter (called the subject):
    if the subject is grouped:
        say "[tone] ";
    otherwise if the number of unread letters which are next to the subject is 0:
        say "unsorted ".

After printing the plural name of a letter (called the subject):
    if the number of read letters which are next to the subject is 0, say " (all unread, at the moment)" instead;
    if the number of unread letters which are next to the subject is greater than 0, say " (some as yet unread)" instead.

Proximity relates a thing (called X) to a thing (called Y) when the holder of X is the holder of Y. The verb to be next to means the proximity relation.

Definition: a letter is grouped:
    if it is unread, no;
    if the number of unread letters next to it is greater than 0, no;
    repeat with item running through letters which are next to it:
        if the tone of item is not the tone of it, no;
    yes.

Definition: a letter is ungrouped if it is not grouped.

The Mailroom is a room. "Usually a thrumming hive of bee-like workers, but you got in early to get a jump on the day's work."

The satchel is carried by the player. Two flamingly rude letters are in the satchel. Five polite letters are in the satchel.

The mail wall are fixed in place in the mailroom. "Before you is a wall of mailboxes, including [a list of mailboxes which are part of the mail wall]."

The plural of mailbox is mailboxes. A mailbox is a kind of container. The CEO box is a mailbox. The Hold box is a mailbox. The Trash box is a mailbox. Understand "mailbox" as a mailbox.

Now, there's a good bit of interaction to streamline. We intend that the player will be taking letters from the satchel, reading them, and putting them (perhaps grouped) into boxes. Our interaction rules should assist in this process as much as possible. To start with, the player will be most likely to examine letters he hasn't read yet:

Does the player mean examining a letter (called the subject):
    if we have examined the subject, it is very unlikely;
    it is very likely.

The rules about taking are more subtle: the player is more likely to want to take an ungrouped letter than a grouped one; he is more likely to want one from the satchel than not; and he is most unlikely to want to take a letter (grouped or ungrouped) that he is already holding.

Does the player mean taking a letter (called subject) which is grouped:
    if the player carries the subject, it is very unlikely;
    if the subject is in the satchel, it is possible;
    it is unlikely.

Does the player mean taking a letter (called subject) which is ungrouped:
    if the player carries the subject, it is very unlikely;
    if the subject is in the satchel, it is very likely;
    it is possible.

And finally, we will assume by default that anything other than examining or taking is most likely to apply to a letter he's already identified:

Does the player mean doing something other than examining or taking with a letter (called the subject):
    if we have examined the subject, it is likely;
    it is unlikely.

And we would also like to understand properties under the same circumstances as printing -- a letter will be identifiable as "polite" if it's already been read and it is either by itself or in a sorted stack of polite letters, but otherwise not. What's more, to make it possible to disambiguate commands in the other direction, we'll call any unsorted letter "random", to represent that the player doesn't know what it is.

Understand the tone property as referring to a letter when the item described is grouped. Understand "random" as a letter when the item described is ungrouped.

When play begins:
    now every mailbox is part of the mail wall;
    repeat with switch count running from 1 to 5:
        move a random letter to the satchel.

Test me with "inventory / examine letter / get letter / i / put letter in ceo box / inventory / get letter / x letter / g / g / i / x letter / g / g / i / put letter in hold box / get letter / g / g / i".

That last "repeat" is merely a device to shuffle the order of items in the satchel so that the player will not always encounter the letters in a neatly presorted order, despite our defining them that way. (Of course, that means that the test produced by TEST ME cannot be very exciting...)

36. Fallout Enclosure ★★★

It may not be immediately obvious why we might want to create new intermediate categories of the kinds hierarchy. But there may be times, for instance, where we would like to make an action that applies in the same way to both containers and supporters, but to nothing else in the game. To avoid creating two nearly-identical rules, we would instead roll the two categories together into one, on the principle that duplicating source text is usually a sign of bad design.

So for instance let's say the player is able to zap objects to make them go away, but any contents -- things inside a container or on top of a supporter -- should always be left as residue. Here's one way we might do this:

paste.png "Fallout Enclosure"

Section 1 - Procedure

An enclosure is a kind of thing. A container is a kind of enclosure. A supporter is a kind of enclosure.

Understand "zap [something]" as zapping. Zapping is an action applying to one thing. The Zapping action has a list of things called the remnants.

Carry out zapping an enclosure:
    if the noun holds something:
        now the remnants is the list of things held by the noun;
        repeat with N running through the remnants:
            move N to the holder of the noun.

Carry out zapping:
    now the noun is nowhere.

Report zapping:
    say "You zap [the noun], destroying [them][if the remnants is not empty] and leaving [the remnants with indefinite articles] behind[end if]."

Section 2 - Scenario

SuperDuperMart is a room. SuperDuperMart contains some shelves and a cash register.

The shelves support a bottle of Buffout and a container of Jet.

The cash register contains some prewar money, a coin purse, and a bottle cap. The coin purse contains a prewar nickel. It is closed.

The cash register is closed and locked.

Test me with "zap shelves / zap buffout / zap register / zap purse".

RB §9.3. Clothing

A person can wear any (portable) thing which has the "wearable" property. (This property seldom needs to be quoted because it is deduced automatically from sentences like "Trevor wears a red hat.")

In most traditional IF, clothing is only used when it is exceptional in some way. That is, we ignore the three to eight different garments most people are wearing at any given time - the everyday clothes which people wear without thinking about them - and only simulate the unexpected extras: a borrowed jaunty red hat, a radiation-proof space suit, and so on.

These unusual garments turn up only occasionally in play and usually one at a time, so Inform does not normally provide rules to restrict how much or little is worn, or in what unlikely combinations. Get Me to the Church on Time ★★★ categorises clothing by body area (trousers for lower body, shirts for upper); Bogart ★★★ by layer, distinguishing underwear from outer garments. What Not To Wear ★★ combines both into a general-purpose system adequate for most kinds of clothing situations.

Hays Code is a somewhat stripped down version.

Clothes are normally single things which have no function other than display and concealment, but Being Prepared gives them pockets which act as containers, and Some Assembly Required allows clothes to be stitched together from pieces of cloth.

See also

Kitchen and Bathroom for a simple mirror implementation, which could be adapted to reflect what the player is currently wearing

Examples

56. Being Prepared

paste.png "Being Prepared"

A jacket is a kind of thing. A jacket is always wearable.

A pocket is a kind of container. A pocket is part of every jacket. The carrying capacity of a pocket is always 2.

After examining a jacket:
    let target be a random pocket which is part of the noun;
    say "[The target] contains [a list of things in the target]."

Now we've created the rules that will govern any specific jackets we might happen to put in our game: each one will always have one pocket, which will be able to contain no more than two things. The description of "a list of things" is text with a list, which we will learn about further in a few sections.

Next we might want to create the environment and an actual example of the jacket kind:

Tent is a room. "A dome made of two flexible rods and a lot of bright green ripstop nylon. It bills itself as a one-man tent, but you'd call it a two-dwarf tent: there is no way to arrange yourself on its square floor so that you can stretch out completely."

The hoodie is a jacket. "Your hoodie is balled up in the corner." The description of the hoodie is "Both elbows are stained from yesterday's entrenching project."

The hoodie's pocket contains a Swiss army knife and a folded map. The hoodie is in the Tent.

Notice that, since Inform has created a pocket for the hoodie, we can now refer to it by name in our source, giving it any additional properties we need to define. Here we simply put a few items into it.

The player wears a whistle. The description of the whistle is "To frighten bears."

Test me with "x hoodie / get hoodie / get knife / get map / i / put hoodie in pocket / put whistle in pocket / put map in pocket / put knife in pocket / i".

Notice that Inform automatically refuses to put the hoodie into its own pocket: as a default, a container cannot contain something of which it is itself a part.

332. Some Assembly Required

We now have the mechanisms in place to do some fairly sophisticated renaming of objects. For instance:

paste.png "Some Assembly Required"

Garment type is a kind of value. The garment types are vest, t-shirt, polo shirt, mandarin blouse, button-down, shell, experiment.

Every turn:
    assign identities.

When play begins: assign identities.

To assign identities:
    repeat with item running through torsos:
        reassess item.

To reassess (item - a torso):
    if the number of things which are part of the item is 0:
        now garment type of the item is vest;
        rule succeeds;
    if exactly two short sleeves are part of the item:
        if a collar is part of the item,
            now garment type of the item is polo shirt;
        otherwise now garment type of the item is t-shirt;
        rule succeeds;
    if exactly two long sleeves are part of the item:
        if a collar is part of the item,
            now garment type of the item is button-down;
        otherwise now garment type of the item is mandarin blouse;
        rule succeeds;
    if a collar is part of the item and the number of sleeves which are part of the item is 0, now garment type of the item is shell;
    otherwise now garment type of the item is experiment.

Before cutting something which is worn by the player:
    try taking off the noun.

Instead of cutting something when something is part of the noun:
    say "You cut up [the noun], snipping off [a list of things which are part of the noun].";
    now every thing which is part of the noun is in the holder of the noun.

Instead of cutting something which is part of something:
    say "You carefully snip [the noun] free.";
    now the player carries the noun.

Rule for printing the name of a torso: say "[garment type]".

A torso is a kind of thing. A torso is always wearable. Understand "shirt" or "blouse" as a torso. A torso has a garment type. Understand the garment type property as describing a torso. A sleeve is a kind of thing. A short sleeve is a kind of sleeve. A long sleeve is a kind of sleeve. A collar is a kind of thing.

Understand "sew [something] to [something]" as affixing it to. Affixing it to is an action applying to two things. Carry out affixing something to something: now the noun is part of the second noun. Report affixing something to something: assign identities; say "You sew [the noun] on, creating [a second noun]." Understand the command "stitch" as "sew".

Instead of affixing something to something when the second noun is worn: say "You're wearing [the second noun]!"

Instead of affixing a torso to something:
    if the second noun is a torso, say "Couture for Siamese twins is a daring field, but a bit of a niche market.";
    otherwise try affixing the second noun to the noun.

Instead of affixing a sleeve to something when at least two sleeves are part of the second noun: say "[The second noun] already sports [a list of sleeves that are part of the second noun]."

Instead of affixing a collar to something when a collar is part of the second noun: say "[The second noun] already sports [a list of collars that are part of the second noun]."

Instead of examining something when something is part of the noun: say "Stitched to [the noun] [is-are a list of things which are part of the noun]."

Here is where the issue of precedence arises. We want to encourage Inform to select a cuttable object that is part of something else, rather than one of the spares:

Definition: a thing is removable if it is part of something. Understand "cut [removable thing]" as cutting.

The Boutique is a room. "Still festively strewn with the confetti and streamers of the Grand Opening party, and still almost totally customer-free."

The player carries a torso. The player carries three short sleeves. The player carries two long sleeves. The player carries two collars.

Test me with "sew collar to shirt / i / sew short sleeve to shirt / g / i / x polo shirt / cut collar / i / cut shirt / sew long sleeve to shirt / i / sew long sleeve to shirt / i / sew collar to shirt / g / i / wear button-down".

338. Hays Code

The following burlesque was considered too much for the tender readers of Chapter 3, since it involved explicit use of listing and persuasion:

paste.png "Hays Code"

The Movie Set is a room. Clark Gable is a man in the Movie Set. "Clark leans on a polystyrene pillar, wearing [a list of unconcealed things worn by Clark] with his usual aplomb." Persuasion rule for asking Clark to try doing something: persuasion succeeds.

Clark is wearing a pin-striped suit and a pink thong. Rule for deciding the concealed possessions of Clark: if the particular possession is the thong and Clark is wearing the suit, yes; otherwise no.

Test me with "clark, remove suit / look / clark, remove thong / look".

241. What Not To Wear ★★

paste.png "What Not To Wear"

Section 1 - Overlying and Underlying

We start by borrowing some of the same ideas from the Bogart example, but we're also going to make a kind called "garment-element". This kind will include both garments (objects of clothing) and body parts (things that can be covered by clothing); using it allows us to restrict the way our underlying and overlying relations apply, which will make them a bit faster at run-time.

A garment-element is a kind of thing.

Underlying relates various garment-elements to various garment-elements with fast route-finding. The verb to underlie means the underlying relation. The verb to be under implies the underlying relation.

Check taking off:
    if the noun underlies something (called the impediment) which is worn by the player, say "[The impediment] [are] in the way." instead.

Carry out taking off:
    now the noun is not underlaid by anything.

Report taking off something:
    say "[We] [are] now wearing [a list of uppermost things worn by the player]." instead.

Definition: a garment-element is uppermost if it is not under something opaque.

Here we've expanded on the previous ideas of 'uppermost' because it is possible for an upper layer to reveal what lies beneath: a tie, a clear plastic trenchcoat, an open-knit sweater, etc. We'll make such items transparent.

Before taking off something which underlies something which is worn by the player:
    while the noun underlies something (called the impediment) which is worn by the player:
        say "(first removing [the impediment])[command clarification break]";
        silently try taking off the impediment;
        if the noun underlies the impediment, stop the action.

Overlying relates various garment-elements to various garment-elements. The verb to overlie means the overlying relation.

Covering relates a garment-element (called A) to a garment-element (called B) when the number of steps via the overlying relation from A to B is greater than 0. The verb to cover means the covering relation.

Before wearing something when a garment which covers the noun is worn by the player:
    while the player wears a garment (called the impediment) which covers the noun:
        say "(first removing [the impediment])[command clarification break]";
        silently try taking off the impediment;
        if the player is wearing the impediment, stop the action.

Carry out wearing:
    repeat with hidden item running through things worn by the player:
        if the noun covers the hidden item, now the hidden item underlies the noun.

Instead of looking under something which is worn by the player:
    if something (called the underwear) underlies the noun, say "[We] [peek] at [the underwear]. Yup, still there.";
    otherwise say "Just [us] in there."

Instead of taking inventory:
    say "[if the player carries something][We]['re] carrying [a list of things carried by the player][else][We]['re] empty-handed[end if][if the player wears something]. [We] [are] wearing [a list of uppermost garments worn by the player][end if]."

To peek is a verb.

Section 2 - Regional Coverage

Here we draw in the idea that different clothes go over different areas of the body, and that they should be in competition with each other only if both sets of clothes belong at the same level over the same body area.

Before wearing something:
    let N be the layering depth of the noun;
    repeat with item running through things worn by the player:
        if the layering depth of the item is N and the item covers a body-part which is covered by the noun:
            say "(first taking off [the item])[command clarification break]";
            silently try taking off the item;
            if the player wears the item, stop the action.

This may seem like overkill, but it allows us to create garments that cover different subsets of the body -- pants and shirt vs. a dress, for instance.

To decide what number is the layering depth of (chosen garment - a thing):
    let N be 0;
    if the chosen garment covers a body-part (called base):
        let N be the number of steps via the overlying relation from the chosen garment to the base;
    decide on N.

To help with modeling, we'll give everyone body parts, broken down according to their relevance to clothing:

A body-part is a kind of garment-element. A torso, a seat, a head, pair of legs, and pair of feet are kinds of body-part.

If we wanted to allow gloves, we might put in hands as well; but this is enough for now.

One head is part of every person. One torso is part of every person. One pair of legs is part of every person. One pair of feet is part of every person. One seat is part of every person.

And now we make some categories of clothing:

A garment is a kind of garment-element. A garment can be transparent. A pair of pants, a pair of underpants, a foundation garment, a pair of socks, a pair of shoes, a jacket, a hat, a dress, and a shirt are kinds of garment.

The plural of pair of pants is pairs of pants. The plural of pair of underpants is pairs of underpants. The plural of pair of socks is pairs of socks. The plural of pair of shoes is pairs of shoes.

A pair of pants, a pair of underpants, a foundation garment, a pair of socks, a pair of shoes, a jacket, a hat, a dress, and a shirt are usually wearable.

When play begins:
    now every pair of socks overlies every pair of feet;
    now every pair of shoes overlies every pair of socks;
    now every pair of underpants overlies every seat;
    now every pair of pants overlies every pair of underpants;
    now every foundation garment overlies every torso;
    now every jacket overlies every shirt;
    now every jacket overlies every dress;
    now every hat overlies every head;
    now every dress overlies every pair of underpants;
    now every dress overlies every foundation garment.

Section 2 - The Scenario

The Dressing Room is a room.

The player carries some capris, some jeans, a corset, a plunge bra, a thong, boy-shorts, black satin D'Orsay pumps, brown leather boots, a camisole, a cocktail dress, a bolero, a cashmere shrug, a sheer wrap, and a linen tunic.

The woolly socks are a pair of socks.
The D'Orsay pumps and the brown leather boots are pairs of shoes.
The thong and the boy-shorts are pairs of underpants.
The capris and the jeans are pairs of pants.
The tunic is a shirt.
The camisole, the corset, and the plunge bra are foundation garments.
The cocktail dress is a dress.
The bolero, the cashmere shrug, and the sheer wrap are jackets. The shrug and the wrap are transparent.

Test me with "wear capris / wear jeans / i / wear thong / i / wear dress / wear corset / wear dress / i / wear wrap / i / wear boots / wear pumps / i".

46. Get Me to the Church on Time ★★★

Inform's default handling of wearable things does not make any rules about what can be worn together. Suppose, however, we have a game in which there are a large number of different garments, and we want to keep the player from wearing (say) more than one pair of pants at once:

paste.png "Get Me to the Church on Time"

A pair of pants and a shirt are kinds of thing. A pair of pants and a shirt are usually wearable.

Some golf pants are a pair of pants. The description is "Checked in red and green, with tiny frolicking gophers every few inches."

Some tuxedo trousers are a pair of pants. The description is "Black, pressed, and slimming."

The frilly shirt is a shirt. The description of the frilly shirt is "She insisted."

The polo shirt is a shirt. The description is "Turquoise and bright yellow, the colors selected by your golfing buddies."

The player wears the golf pants and the polo shirt. The player carries the tuxedo trousers and the frilly shirt.

The Wedding Chapel Dressing Room is a room. "The bride's dressing room is a lavish suite with closets, hangers, dressmaker's dummies, boxes of straight pins and sewing notions, combs, lotions, brushes, and hair fixatives, plus room for fifteen female attendants and a photographer. Before they shoved you out of the room you even got a glimpse of a small reference library including '1001 French Braids' and 'Corset-Lacing For Beginners.'

This is the groom's dressing room. You get a framed photograph of Elvis, a dusty mirror, and the floor space of an average toilet stall."

The dusty mirror and the photograph of Elvis are scenery in the Dressing Room. The description of the mirror is "You can't really get more than a silhouette impression of yourself." The description of Elvis is "He reminds you that you'd better get out there before the organist switches to Hound Dog."

And now the rule itself, borrowed from a later chapter:

Instead of wearing a pair of pants when the player is wearing a pair of pants (called the wrong trousers):
    say "You'll have to take off [the wrong trousers] first."

Instead of wearing a shirt when the player is wearing a shirt (called the wrong top):
    say "You'll have to take off [the wrong top] first."

When play begins:
    say "From the other side of the door, you hear the organist move on from his instrumental interpretation of 'I Wanna Hold Your Hand' to a somewhat more spirited rendition of 'Help! I Need Somebody!'. Okay, okay, but you've been rushing things along since the 16th fairway, and you can't be more than a half-hour late... Surely that mother of hers can't blame you for that?"

Test me with "i / x trousers / wear trousers / x golf pants / take off golf pants / wear trousers / x frilly shirt / x polo shirt / wear frilly shirt / doff polo shirt / wear frilly shirt".

If we wanted to, we could make similar kinds for hats, shoes, and so on, and have a simple but effective system of clothing. A more complicated treatment might keep track of layering and describe the player's outfit differently depending on which clothes were outermost -- an example for a later chapter.

234. Bogart ★★★

We have two things to keep track of with our layering clothing: what currently is covering something else; and what can cover something else. This implementation goes for a fairly simple treatment, assuming that each item of clothing will completely conceal those beneath it, and that we are not implementing entire sets of shirts, jackets, etc. But it will do for a demonstration.

paste.png "Bogart"

Section 1 - Clothing Behavior

First we make our relation to represent what *is* underneath another item:

Underlying relates one thing to various things. The verb to underlie means the underlying relation. The verb to be under implies the underlying relation.

And now we prevent taking a lower layer off before the thing that is worn over it:

Before taking off something which underlies something (called the impediment) which is worn by the player:
say "(first removing [the impediment])[command clarification break]";
silently try taking off the impediment;
if the noun underlies something which is worn by the player, stop the action.

Check taking off:
    if the noun underlies something (called the impediment) which is worn by the player, say "[The impediment] [are] in the way." instead.

Carry out taking off:
    now the noun is not underlaid by anything.

Report taking off something:
    say "[We] [are] now wearing [a list of uppermost things worn by the player]." instead.

Definition: a thing is uppermost if it is not under something.

That covers order of clothing removal, but we also want to restrict what can be worn on top of what else. This time we need Inform to have some idea of what customarily can be layered on top of what other clothing:

Overlying relates one thing to various things. The verb to overlie means the overlying relation.

Covering relates a thing (called A) to a thing (called B) when the number of steps via the overlying relation from A to B is greater than 0. The verb to cover means the covering relation.

With these definitions, we can say that a jacket should go over a shirt and a shirt over an undershirt (say), and then Inform will know that a jacket will cover both shirt and undershirt.

Before wearing something when something (called the impediment) which covers the noun is worn by the player:
    while the player wears something which covers the noun:
        say "(first removing [the impediment])[command clarification break]";
        silently try taking off the impediment;
        if the player is wearing the impediment, stop the action.

Carry out wearing:
    if the noun covers something (called the hidden item) worn by the player, now the hidden item underlies the noun.

Instead of looking under something which is worn by the player:
    if something (called the underwear) underlies the noun, say "[We] [peek] at [the underwear]. Yup, still there.";
    otherwise say "Just [us] in there."

Instead of taking inventory:
    say "[if the player carries something][We]['re] carrying [a list of things carried by the player][else][We]['re] empty-handed[end if][if the player wears something]. [We] [are] wearing [a list of uppermost things worn by the player][end if]."

To peek is a verb.

Notice that our inventory only describes the things that the player can see as the upper layer of clothing.

Section 2 - The Scenario

The Trailer is a room. "A full-length mirror is the main amenity in here, and that suits you just fine." The full-length mirror is scenery in the Trailer. Instead of examining or searching the mirror, try taking inventory.

The player wears a fedora, a jacket, a shirt, some undershorts, an undershirt, some slacks, a pair of socks, and a pair of shoes.

The shirt underlies the jacket. The pair of socks underlies the pair of shoes. The undershorts underlie the slacks. The undershirt underlies the shirt.

The jacket overlies the shirt. The shoes overlie the socks. The slacks overlie the undershorts. The shirt overlies the undershirt.

Test me with "x mirror / remove fedora / remove jacket / remove shirt / remove slacks / remove undershirt / remove shoes / remove socks / remove shorts / remove undershorts".

If we further wanted to prevent the player from taking off clothes in inappropriate places, we might add something like this:

Instead of taking off something in the presence of someone who is not the player:
    say "[We] [are] far too modest to strip in public."

RB §9.4. Money

Money could be anything which the two people in a bargain both agree is valuable. Here, the player and an ogre agree on a copper coin as money:

The player carries a copper coin. The ogre carries a rock cake. The cake is edible.

Instead of giving the coin to the ogre:
    now the ogre carries the coin;
    now the player carries the cake;
    say "The ogre grunts and hands you a rock cake."

Now Inform does provide an action, "buying", and a command for it, BUY, but they ordinarily respond simply "Nothing is on sale." This is no longer true, so we should make BUY CAKE work. The difficulty here is that a command like BUY CAKE does not specify what should be handed over in exchange. Here we just check that the player has the coin, but in principle we could check for any of a range of monetary tokens - coins, notes, cheque book, debit card, and so on.

Instead of buying the cake:
    if the player has the coin, try giving the coin to the ogre;
    otherwise say "You have no money."

In more advanced economies, where shopping replaces barter, the seller will stock a wide range of differently priced goods. For a tabulated catalogue of wares, see Introduction to Juggling ★★★: to allow the player to negotiate prices, see Money for Nothing ★★. In both of those examples, the player's current financial worth is simulated only as a current total amount of money carried - say, $2.50. This is typical, because in most situations what matters is how much money is in the pocket, not how it is made up. Money behaves more like a liquid than a set of items: hence terms like "liquidity", "cash flow" or Frozen Assets - the name of the simplest example demonstrating this. If we really need a comprehensive simulation down to pieces of currency - where it makes a difference carrying four quarters rather than a dollar bill, because the quarters can be fed into a vending machine - see Nickel and Dimed ★★★.

Fabrication ★★ takes the problem in a different direction, making calculations about the cost of a new garment based on the price of the pattern, the quantity of fabric required, and the value of the fabric type chosen -- showing off what we can do with unit multiplication in Inform.

Widget Enterprises explores the challenge of pricing widgets for maximum profit, given certain necessary costs and customers with varying willingness to pay.

See also

Actions on Multiple Objects for an implementation of giving that allows the player to offer multiple objects at once, where their combined value determines whether they are accepted

Examples

263. Widget Enterprises

Suppose the player is responsible for pricing at Widget Enterprises. Widget production entails a certain fixed cost as well as a cost per unit; and somewhere out in the world there are a number of customers interested in purchasing widgets, but the player starts without knowing what this distribution looks like.

We can express the profits as an equation: the total made by selling widgets, minus the cost thereof.

The Table of Customers holds the data about customer preferences, and whenever the player selects a widget price, we consult it to determine how many customers in total would be willing to buy at that price.

paste.png "Widget Enterprises"

Widget Stand is a room.

A monetary value is a kind of value. $1.99 specifies a monetary value with parts dollars and cents.

Equation - Profit Equation
    P = nV - (F + nC)
where P is a monetary value, F is the fixed cost, C is the unit cost, V is a monetary value, and n is a number.

The fixed cost is a monetary value that varies. The fixed cost is $5.00.
The unit cost is a monetary value that varies. The unit cost is $10.66.

Table of Customers

base

maximum value

2

$26.00

5

$20.00

8

$15.00

2

$13.50

1

$9.00

To decide what number is the units sold at (V - a monetary value):
    let total units be 0;
    repeat through the Table of Customers:
        if V is less than the maximum value entry:
            increase total units by the base entry;
    decide on total units.

Understand "set price to [monetary value]" as setting price to. Setting price to is an action applying to one monetary value.

Carry out setting price to:
    let V be the monetary value understood;
    let n be the units sold at the monetary value understood;
    let P be given by the Profit Equation;
    say "You set the price of your widgets to [V], resulting in sales of [n] unit[s] and ";
    if P is less than $0.00:
        let L be $0.00 - P;
        say "a loss of [L].";
    otherwise if P is $0.00:
        say "break even.";
    otherwise:
        say "a profit of [P].".

Test me with "set price to $0.00 / set price to $100.00 / set price to $15.00 / set price to $8.00 / set price to $25.00 / set price to $14.99".

As written this will be a rather dull guessing game for the player; more interesting would be to enhance it into a fuller economic simulator with more control over fixed costs and customer price points.

264. Frozen Assets

In our brave new world, everything will have a price, so we had better spell this out.

paste.png "Frozen Assets"

Price is a kind of value. $10.99 specifies a price. A thing has a price. The price of a thing is usually $0.00. After examining something for sale, say "It can be yours for [the price of the noun]."

Now we assume a simple shopping model in which the player can't take anything without paying for it.

Definition: a thing is free if the price of it is $0.00.
Definition: a thing is for sale if it is not free.

Instead of taking something for sale:
    say "You'll have to pay for that."

Before buying something for sale when the money is not in the wallet:
    say "You're broke." instead.

Before buying something for sale when the money is free:
    say "You're broke." instead.

Before buying something for sale when the price of the money is less than the price of the noun:
    say "Your funds do not run to the price of [the noun]." instead.

Instead of buying something:
    decrease the price of the money by the price of the noun;
    say "You fork over [the price of the noun] for [the noun], leaving yourself with [the price of the money].";
    if the money is free:
        now the money is nowhere;
    now the price of the noun is $0.00;
    now the player is carrying the noun.

The player's money object is going to be a bit unusual, because it has value but cannot itself be bought.

The player carries a wallet. The wallet contains money. The price of the money is $4.50. The printed name of the money is "[price of the money] in cash". Understand "cash" as the money.

Instead of taking the money:
    say "Best to leave it alone until you need to buy something."

Instead of buying something free:
    say "[The noun] is yours already."

Instead of buying the money:
    say "The money belongs to you; you buy things with it."

Now we just need something to buy.

The Dessert Parlor is a room. "An underlit, over-crowded room campily furnished with a lot of gilt-frame mirrors and twinkle lights: it is essentially a brothel of food. The service is slow at best, and on Saturday nights glacial. However. The wares on display more than make up for these trivial inconveniences."

The vanilla ice cream is an edible thing in the Parlor. The price of the ice cream is $2.45. The description is "In the scale of ice creams, you recognize this as a very inferior vanilla because it has no adjectives in the title."

The raspberry tart is an edible thing in the Parlor. The price of the tart is $4.50. The description is "An almond-laced shell packed with raspberries-under-glaze."

The syllabub is an edible thing in the Parlor. The price of the syllabub is $4.25. The description is "Whipped cream, alcohol, and lime juice, a substance without any redeeming food value whatever."

The espresso cake is an edible thing in the Parlor. The price of the espresso cake is $5.50. The description is "A lethal wedge of purest blackness."

Test me with "inventory / examine syllabub / get syllabub / buy syllabub / drop it / get it / buy raspberry tart".

Implementing caloric units for this scenario is left as an exercise for the reader.

265. Money for Nothing ★★

paste.png "Money for Nothing"

Section 1 - Prices and Bargaining

Price is a kind of value. $10.99 specifies a price with parts dollars and cents (optional, preamble optional).

A person has a price called wealth. The wealth of the player is $15.

A thing has a price called minimum value. The minimum value of a thing is usually $0.50.

A thing has a price called desired value. The desired value of a thing is usually $5.00.

Offering it for is an action applying to one price and one visible thing.

Understand "offer [price] for [something]" as offering it for.

After taking inventory, say "You have [the wealth of the player]."

Check offering it for:
    if the price understood is greater than the wealth of the player, say "You don't have that kind of cash." instead;
    if the second noun is not carried by someone, say "There's no one in a position to sell you [the second noun]." instead;
    if the second noun is carried by the player, say "[The second noun] is already yours." instead;
    if the minimum value of the second noun is greater than the price understood, say "[The holder of the second noun] cackles disdainfully. 'If yer just here to insult me you can take your business elsewhere!' he says." instead;
    if the desired value of the second noun is greater than the price understood:
        let difference be the desired value of the second noun minus the price understood;
        let difference be difference divided by two;
        decrease the desired value of the second noun by difference;
        now the last object offered is the second noun;
        say "'How about [desired value of the second noun]?' suggests [the holder of the second noun]." instead;
    otherwise:
        unless the desired value of the second noun is the price understood:
            say "From the avaricious gleam in the eye of [the holder of the second noun], you guess you could've gotten this purchase for less..."

Carry out offering it for:
    increase the wealth of the holder of the second noun by the price understood;
    decrease the wealth of the player by the price understood;
    move the second noun to the player.

Report offering it for:
    say "You spend [the price understood], and now you possess [the second noun]."

When play begins: now right hand status line is "Your funds: [wealth of the player]".

Now, since the man does make counter-offers, it would be reasonable to let the player accept or reject those, as well:

The last object offered is a thing that varies.

Instead of saying yes when the last object offered is carried by a person (called seller) who is not the player:
    if the seller is not visible:
        continue the action;
    otherwise:
        now the price understood is the desired value of the last object offered;
        try offering the desired value of the last object offered for the last object offered.

Instead of saying no when the last object offered is carried by a person (called seller) who is not the player:
    if the seller is not visible:
        continue the action;
    otherwise:
        now the last object offered is the player;
        say "You reject the offer firmly."

And we borrow just a line or two from a later chapter to take care of some alternate syntax the player might try:

Understand "offer [price] to [someone]" as a mistake ("You'll need to specify what you want to buy -- try OFFER $1000.00 FOR BROOKLYN BRIDGE."). Understand "offer [someone] [price]" as a mistake ("You'll need to specify what you want to buy -- try OFFER $1000.00 FOR BROOKLYN BRIDGE.").

Understand "buy [something]" as a mistake ("You'll have to name your price: try OFFER $1000.00 FOR BROOKLYN BRIDGE.").

Section 2 - The Scenario

The Flea Market is a room. The crotchety man is a man in the Market. "A crotchety man here is selling [the list of things carried by the crotchety man]." The crotchety man carries a broken television set, a Victorian rhinestone brooch, and a cracked shaving mug.

The minimum value of the brooch is $2.50.

Test me with "offer $0.50 for mug / offer $0.50 to man / offer $6.00 for mug / offer $50.00 for brooch / offer $1.50 for brooch / offer $4.50 for brooch / no / offer $4.50 for brooch / yes".

270. Fabrication ★★

When we make a new kind of value, the new named values can themselves have properties. That is convenient because, for instance, we might want to associate a material (itself the property of an object) with certain features, such as price.

paste.png "Fabrication"

Section 1 - Procedure

A material is a kind of value. The materials are silk, velvet, cotton, and wool.

Price is a kind of value. $1.99 specifies a price.

Area is a kind of value. 5 sq yards specifies an area.

Cost is a kind of value.. $1.99 per sq yard specifies a cost. A cost times an area specifies a price.

A material has a cost.

The cost of silk is usually $5.75 per sq yard. The cost of velvet is usually $9.50 per sq yard. The cost of cotton is usually $2.29 per sq yard. The cost of wool is usually $4.75 per sq yard.

A pattern is a kind of thing. A pattern has a material. A pattern has an area. A pattern has a price. The price of a pattern is usually $9.99. Understand "pattern" as a pattern. Understand "patterns" as the plural of a pattern.

After printing the name of a pattern:
    if planning:
        do nothing;
    otherwise:
        say " pattern".

To decide what price is the material price of (chosen item - pattern):
    let C be the cost of the material of the chosen item;
    let A be the area of the chosen item;
    decide on C * A.

To decide what price is the overall price of (chosen item - pattern):
    let P be the price of the chosen item;
    let M be the material price of the chosen item;
    decide on P + M.

Understand "plan [material] [pattern]" as planning it for.

Planning it for is an action applying to one material and one thing.

Carry out planning it for:
    now the material of the second noun is the material understood.

Report planning it for:
    say "You lay plans for a [material understood] [second noun], running [material price of the second noun] for materials and [price of the second noun] for the pattern itself, for a total of [overall price of the second noun]."

Section 2 - Scenario

Joanne's Fabrics is a room. Joanne's Fabrics contains a pattern bin.

The cape is a pattern. The material of the cape is velvet. The area of the cape is 9 sq yards.

The bodice is a pattern. The material of the bodice is silk. The area of the bodice is 2 sq yards. The price of the bodice is $11.99.

The cape and the bodice are in the pattern bin.

Test me with "plan silk bodice / plan velvet bodice / plan velvet cape / plan wool cape".

262. Nickel and Dimed ★★★

Typically games which keep track of the player's wealth need only do so as an abstract number, but occasionally it becomes useful to represent money as physical coins and bills. Here is an example that does exactly that:

paste.png "Nickel and Dimed"

Section 1 - Currency

Price is a kind of value. $10.99 specifies a price with parts dollars and cents. A thing has a price. The price of a thing is usually $0.00.

Money is a kind of thing. Coin is a kind of money.

A dollar bill is a kind of money. The price of a dollar bill is $1.00. The printed name of a dollar bill is "dollar bill". Rule for printing the plural name of a dollar bill: say "dollar bills". The description of a dollar bill is "It has George Washington's head on the front, which with a bit of creative folding can be scrunched to look like a mushroom. All important things really are learned in kindergarten."

A five-dollar bill is a kind of money. The price of a five-dollar bill is $5.00. Understand "five" or "five dollar" as the five-dollar bill. The description of a five-dollar bill is "Abraham Lincoln. He looks slightly less dignified here than he does on the penny."

A hundred-dollar bill is a kind of money. The price of the hundred-dollar bill is $100.00. Understand "hundred" or "hundred dollar" as the hundred-dollar bill. Understand "dollar" as the dollar bill. The description of a hundred-dollar bill is "It's got Benjamin Franklin, who always gets shafted: a denomination too large for anyone to carry conveniently, and a lot of local fame in Philadelphia."

Our choice of understand rules guarantees that "five dollar" will be understood as the five, but "dollar" alone as the single. We will learn more about "understand" in later chapters, but here is a test to check the functionality:

Test bills with "x hundred dollar bill / x five dollar bill / x hundred / x five / x dollar / x dollar bill".

A quarter is a kind of coin. The price of a quarter is $0.25. The description of a quarter is "One of the old-fashioned variety, not a state quarter."

A dime is a kind of coin. The price of a dime is $0.10. The description of a dime is "Franklin Roosevelt, trying not to look too annoyed that his coin is so small and thin."

A nickel is a kind of coin. The price of a nickel is $0.05. The description of a nickel is "A chubby coin, but you've always liked Thomas Jefferson, and the Monticello on the back is a nice touch."

A penny is a kind of coin. The price of a penny is $0.01. The description of the penny is "A profile of Abe Lincoln. Sometime soon they'll stop minting these, you're sure of it."

Section 2 - Ownership

Ownership relates one person (called the owner) to various things. The verb to own means the ownership relation.

Definition: a thing is owned if the player owns it.

Instead of buying something which is owned by the player:
    say "You already own [the noun]."

Instead of going somewhere when the player encloses something (called the stolen goods) which is not owned by the player:
    if the owner of the stolen goods is not a person:
        now the player owns the stolen goods;
        continue the action;
    if the owner of the stolen goods can see the player,
        say "'Hey there buddy, not so fast,' says [the owner of the stolen goods]. 'You going to buy [the stolen goods] first, or am I gonna call the cops?'";
    otherwise continue the action.

After taking inventory:
    say "Altogether, you've got [the player's cash] on your person."

To decide what price is the player's cash:
    let sum be the total price of money enclosed by the player;
    decide on sum.

To decide what price is the sum in (item - a container):
    let sum be the total price of the money in the item;
    decide on sum.

When play begins: now every thing carried by the player is owned by the player.

Section 3 - Purchasing and Sales

Definition: a thing is worthless if the price of it is $0.00. Definition: a thing is valuable if it is not worthless.

A thing can be for sale.

Rule for printing room description details of something (called target) which is for sale (this is the disclose prices in room description rule): say " ([price of the target])".

Before listing contents: group money together giving articles.

Instead of examining a for sale thing (this is the describe things by price rule):
    say "[The noun] costs [the price of the noun], payable to [the owner of the noun]."

The cashbox is a theoretical construct, not something the player will ever encounter in the course of the game. It contains all the money that is available for non-player characters to use in making change. If we wanted, we could give each character his own stash of change, but this would increase the likelihood that any given person would run out of cash to make change with. (And in this example there is only one vendor anyway.)

The cashbox is a container. The cashbox contains 10 pennies. The cashbox contains 10 nickels. The cashbox contains 10 dimes. The cashbox contains 10 quarters. The cashbox contains 10 dollar bills. The cashbox contains 10 five-dollar bills.

The block buying rule is not listed in the check buying rules.

Check buying something:
    if the noun is not for sale, say "[The owner of the noun] does not want to sell you [the noun]." instead;
    if the player's cash is less than the price of the noun, say "You can't afford the asking price of [the price of the noun] for [the noun]." instead.

Carry out buying something:
    let sum paid be $0.00;
    while sum paid is less than the price of the noun:
        let current target be the price of the noun minus the sum paid;
        let bill offered be the best money from the player for the current target;
        if the bill offered is money:
            move the bill offered to the owner of the noun;
            now the bill offered is spent;
            increase the sum paid by the price of the bill offered;
            let current target be the price of the noun minus the sum paid;
    say "You hand [the owner of the noun] [a list of spent money]. [run paragraph on]";
    let change be $0.00;
    if the sum paid is greater than the price of the noun:
        now the change is the sum paid minus the price of the noun;
    if change is greater than the sum in the cashbox:
        now the player carries every spent money;
        now every spent thing is fresh;
        say "'Whoa,' says [the owner of the noun], handing the cash back to you. 'I can't make change for that, man, sorry.'" instead;
    now every spent thing is in the cashbox;
    now every spent thing is fresh;
    while change is greater than $0.00:
        let change bill be the best money from the cashbox for change;
        decrease change by the price of the change bill;
        now change bill is spent;
        move change bill to player;
    if money is spent, say "[The owner of the noun] makes change with [a list of spent money]. [run paragraph on]";
    now every spent thing is fresh;
    if the noun is not enclosed by the player and the owner of the noun can touch the noun:
        say "'Here ya go,' says [the owner of the noun], handing [the noun] to you. [run paragraph on]";
        move the noun to the player;
    now the player owns the noun.

Money can be spent or fresh.

Report buying something:
    if the player owns the noun,
        say "Your transaction is now complete, leaving you with [the player's cash]."

We've skipped over defining what makes a denomination the best for a given transaction, so we'd better do that now. Our goal is to avoid ever having the player gratuitously overpay -- he should always offer the smallest amount of money that will meet the price of what he's buying.

We also assume that all money "enclosed by the buyer" -- that is, somewhere in the buyer's possession -- is available for use. This might not be true in a game where the player could pick up, say, a sealed lucite container with a ten-dollar bill inside; in that case we would have to define our terms more rigorously, perhaps by requiring that the bills be both enclosed and touchable by the buyer. The touchability check adds an extra layer of calculation, however, and since it is not necessary in this example (and probably not in most other cases either), we'll leave it out:

Definition: money is costly if its price is $2.50 or more. Definition: money is cheap if its price is $0.99 or less.

Functional relation is a kind of value. The functional relations are overpayment, underpayment and irrelevant. Money has a functional relation.

To decide what money is the best money from (buyer - a thing) for (cost - a price):
    repeat with bill offered running through money:
        if the bill offered is enclosed by the buyer:
            if the price of the bill offered is the cost, decide on the bill offered;
            if the price of the bill offered is greater than the cost, now the functional relation of bill offered is overpayment;
            otherwise now the functional relation of the bill offered is underpayment;
        otherwise:
            now the functional relation of the bill offered is irrelevant;
    [say "underpayment: [a list of underpayment money]
    overpayment: [a list of overpayment money]";]
    if the total price of underpayment money is less than the cost:
        decide on the cheapest money which is overpayment;
    otherwise:
        decide on the costliest money which is underpayment.

Notice the "say underpayment/overpayment section..." noted out, above. This is for debugging purposes: when writing complex code, it is sometimes useful to put in lines that will say explicitly what is going on. We can enclose them in brackets and Inform will ignore them as though they were comments; if we run into any problems with the code later, we can erase the brackets and see the diagnostic printed to the screen as we play.

Instead of giving money to someone:
    say "Best to keep the transaction simple by buying whatever you want."

Section 4 - The Scenario

The player carries 2 dollar bills. The player carries a nickel. The player carries 2 pennies. The player carries a five-dollar bill. The player carries 1 hundred-dollar bill.

The Subway Station is a room.

The Bitterly Cold Street is north of the Subway Station. "Even though there is no actual snow or ice, the street is about as cold as you can stand, for which reason walking the twenty blocks uptown is not an acceptable option." The Bitterly Cold Street contains a dollar bill.

The newspaper man is a man in the Subway Station. "A newspaper man in a knit cap and fingerless gloves is hopping up and down behind his stand[if the turn count is 1]. Cold weather, caffeine overdose, or mental illness? You may never know. Welcome to New York[end if]." The description is "Eye contact with strangers is something to avoid around here."

The stand is a supporter in the Station. The stand is scenery.

A copy of the New York Times is on the stand. The price of the New York Times is $1.25.

A pack of gum is on the stand. The price of the gum is $0.40.

A paperback novel is on the stand. The price of the paperback novel is $7.99.

A packet of trading cards is on the stand. The price of the packet is $0.99.

When play begins:
    now every thing on the stand is owned by the newspaper man;
    now every thing on the stand is for sale.

We could have done all that by hand, but the initialization requires a little less work.

The ticket machine is a container in the Subway Station. It is fixed in place. The description of the ticket machine is "An LED screen on the front instructs you to insert [remaining ticket total] to complete your purchase. You also notice that the NO CHANGE light is lit up." The light is part of the ticket machine. The printed name of the light is "no change light". Understand "no change" or "no change light" as the light.

The description of the light is "In the whole of your recollection, the ticket machine has actually had change a total of twice. Usually, as now, the no-change light gleams angrily, daring you to put in more than you owe." A cash return button is part of the ticket machine. Instead of pushing the cash return button: say "The ticket machine regurgitates [the list of things in the ticket machine]."; now every thing in the ticket machine is carried by the player. Instead of taking something which is in the ticket machine: say "The ticket machine has swallowed your money, but it can be retrieved (you hope) with the cash return button."

Instead of inserting a hundred-dollar bill into the ticket machine:
    say "What, are you nuts?"

To decide what price is the remaining ticket total:
    let absolute cost be $2.25;
    let remaining cost be absolute cost minus the total price of things in the ticket machine;
    if remaining cost is less than $0.00, decide on $0.00;
    decide on remaining cost.

Instead of inserting something which is not money into the ticket machine: say "The ticket machine only accepts money, not other tokens of your esteem and regard."

Instead of inserting a penny into the ticket machine:
    say "The penny rattles out again mockingly: not even the ticket machine thinks these are worth anything."

A subway pass is a kind of thing. 15 subway passes are in the cashbox. The description of a subway pass is usually "A rectangle of thick lavender paper with a black magnetic stripe running up the back side. It is good for one trip on the subway."

After inserting something into the ticket machine:
    if the remaining ticket total is $0.00:
        let purchased ticket be a random subway pass in the cashbox;
        if purchased ticket is not a subway pass, say "The ticket machine grunts disobligingly and then the unwelcome word MALFUNCTION parades across the LED screen, three letters at a time." instead;
        repeat with item running through things in the machine:
            now the item is nowhere;
        move purchased ticket to player;
        say "The ticket machine beeps obligingly and disgorges a single subway pass.";
    otherwise:
        say "The ticket machine beeps obligingly and adjusts its price down to [remaining ticket total]."

And because even though the ticket machine is a container, we don't want to say (empty) after it in the room description:

Rule for printing room description details of the ticket machine:
    do nothing instead.

Test me with "buy novel / n / get dollar / s / buy novel".

After all that, we should probably give the player a chance to win, as well:

The turnstile is south of the Subway Station. "A turnstile is all that separates you from the subway platform stairs." The turnstile is north of the Platform. The turnstile is a door. Before going down in the presence of the turnstile, try going south instead. The turnstile is openable. The turnstile is open.

Instead of going through the turnstile when the player carries a subway pass: say "You enter the turnstile and begin your journey uptown..."; end the story finally saying "At last". Instead of going through the turnstile: say "You can't go through the turnstile without a subway pass. They're very strict about this."

Instead of inserting money into the turnstile: say "The turnstile takes passes, not money." Instead of inserting a subway pass into the turnstile, try entering the turnstile.

Test more with "buy times / put all but five-dollar bill in machine / press button / buy gum / buy cards / i / put dollar in machine / g / put quarter in machine / i / d".

In fairness to the Metropolitan Transit Authority, we should admit that most of the ticketing machines in the real New York subway are better than this, and will accept, say, a debit card. But that would be so much less exciting to implement.

283. Introduction to Juggling ★★★

Suppose we have a whole catalog-full of equipment that the player might want to purchase and use. We'll start by defining our purchasing rules:

paste.png "Introduction to Juggling"

We allow things to have prices, and the player's price to indicate how much money the player has:

Section 1 - Mail-ordering defined

Price is a kind of value. $100.99 specifies a price.

The player has a price. The price of the player is $60.00.

Because we're allowing the player to order things that he can't currently see, we need to borrow a special kind of grammar from the Understanding chapter. All our orderable items in this example are toys, so "any toy" means any object of the toy kind, whether or not it is in view at the moment:

Understand "buy [any toy]" as ordering. Understand the command "order" as something new. Understand the command "order" as "buy".

Ordering is an action applying to one visible thing.

Check ordering:
    if the cost of the noun is greater than the price of the player, say "You only have [price of the player], while [the noun] would cost [cost of the noun]." instead.

Carry out ordering:
    move the noun to the player;
    decrease the price of the player by the cost of the noun.

Report ordering:
    say "You order [a noun], which is delivered instantly."

We should also handle the situation where the player orders another of something he has already bought and which is right in front of him:

Instead of buying something:
    say "You already have [a noun]."

So much for the general rules for this scenario. Now we move on to particulars: the actual items the player is allowed to order. Each item will have a description, a price, and a difficulty representing how skilled the player must be in order to make use of that item.

Since we are going to use price and difficulty in the table that defines our juggling equipment, we need to mention these kinds of value before the line that says how toys are defined.

Section 2 - The Scenario

Difficulty is a kind of value. The difficulties are easy, moderate, hard. The player has a difficulty. The difficulty of the player is easy.

The plural of toy is toys. A toy is a kind of thing. Some toys are defined by the Table of Juggling Equipment.

Table of Juggling Equipment

toy

cost

restriction

description

difficulty

outcome

an economy bounce ball set

$10.00

"comes in set of three"

"A fairly ordinary rubber ball, solid color."

moderate

"You create of the balls a cascade of moving color."

an acrylic contact ball

$14.00

"should be bought with ball polish"

"A large clear ball, not for throwing but for using in various hand tricks."

hard

"You rotate the ball between your fingers and pass it over the backs of your hands."

a UV-reactive contact ball

$55.00

"appears to glow in dark rooms"

"Similar to the ordinary acrylic contact ball, but UV-reactive."

hard

"The ball glows as it passes between your fingers and over the backs of your hands, rolls up to your wrist, snaps through the air-- all apparently of its own accord."

a ball polish set

$10.00

"useful only with acrylic contact balls"

"Three bottles of polish and a rag for keeping acrylic contact balls scratch-free."

hard

"You juggle the polish bottles with difficulty, since they are full of sloshing liquid."

a teaching beanbag set

$8.00

"set of three"

"Soft, easily-juggled bag."

easy

"You juggle the beanbags with basic competence."

a stage ball set

$13.50

"comes in set of three"

"Not much different in appearance from the economy bounce ball, but larger so as to be visible from a stage."

moderate

"You create of the balls a cascade of moving color, visible from quite a distance."

a fireball set

$33.00

"will not be sold to minors"

"A ball has wicking and a fuel-source inside so that it will burn while being juggled."

hard

"You juggle the fireballs rapidly, careful never to hold any of them a moment longer than necessary."

Notice that we are allowed to define "description" and other already-known properties in the table as well.

Backstage is a room. "A muffled black room with felt on the floors and walls. A glowing sign over the stage door says SHOW IN PROGRESS."

The Juggling Equipment Catalog is a thing in Backstage.

Instead of examining the Catalog:
    say "You read through the offerings, including: [paragraph break]";
    repeat through Table of Juggling Equipment:
        say "[bold type][toy entry][roman type]: [description entry] [cost entry], [restriction entry]. [paragraph break]".

When play begins:
    now right hand status line is "Budget: [price of the player]";
    now left hand status line is "[location], feeling [if the difficulty of player is easy]incompetent[end if][if the difficulty of player is moderate]moderately skilled[end if][if the difficulty of player is hard]highly skilled[end if]".

And of course this will be no fun unless the player is allowed to use the equipment:

Understand "juggle [something]" as juggling.

Juggling is an action applying to one thing.

Check juggling:
    if the noun is not a toy listed in the Table of Juggling Equipment, say "You can't juggle [a noun]!" instead;
    if the difficulty of the noun is greater than the difficulty of the player, say "You're not quite ready to juggle something like [the noun]. Better to start with an easier toy." instead.

Carry out juggling:
    if a random chance of 1 in 3 succeeds:
        if the difficulty of the player is less than hard and the difficulty of the player is the difficulty of the noun:
            now the difficulty of the player is the difficulty after the difficulty of the player.

Report juggling:
    say "[outcome of the noun][paragraph break]".

Instead of burning the fireball set:
    say "It will flame by itself when you use it."

Test me with "read catalog / buy economy / buy beanbag / juggle economy / juggle beanbag / juggle beanbag / juggle beanbag / juggle beanbag / juggle beanbag / juggle beanbag / juggle economy / juggle economy / juggle economy / buy fireball set / juggle fireball".

RB §9.5. Dice and Playing Cards

Most toys are single things, and no harder to create than any other small items, but games often require a multitude of tokens to be combined, and this can be logistically tricky.

The classic example is a pack of playing cards, where the player must individually control 52 items but without fussy commands or verbose text being printed back. Jokers Wild ★★ provides a simple "one card at a time" approach; Tilt 1 ★★★ is more sophisticated, with 52 independently accessible cards; Tilt 2 ★★★ can further judge the value of a selection of cards - the ranking of a poker hand.

Drawing cards from a shuffled pack is only one source of randomness. Games of chance also involve items drawn from a bag: Wonka's Revenge provides just such a lottery. More often, dice are thrown. A single die is easy enough:

The die is carried by the player. After dropping the die: say "It lands with [a random number from 1 to 6] uppermost." Understand "roll [something]" as dropping.

Quick, but not very good. Most dice games involve rolling more than one die at a time, to get a more interesting distribution of outcomes: they may also involve special rules applying to doubles, for instance. See Do Pass Go.

See also

Typography for on-screen notations for chess and card games

Examples

130. Do Pass Go

paste.png "Do Pass Go"

Go is a room. "A giant square area, where you and your other pewter ornament friends gather before setting out to purchase London."

The pair of dice is carried by the player.

The pair of dice has a number called first die. The pair of dice has a number called second die. The first die of the pair is 6. The second die of the pair is 6. Rule for printing the name of the pair of dice while taking inventory: say "pair of dice".
Rule for printing the name of the pair of dice: say "pair of dice showing [first die of the pair plus second die of the pair]".

To say detailed state of the dice:
    if the first die of the pair is the second die of the pair, say "double [first die of the pair]";
    otherwise say "[first die of the pair] and [second die of the pair]".

The description of the pair of dice is "The pair of dice are [if the dice are carried]itching to be rolled[otherwise]showing [detailed state of the dice][end if]."

Rolling is an action applying to one carried thing. Understand "roll [something preferably held]" as rolling.

Check rolling when the noun is not the pair of dice: say "Not something you can roll." instead.
Carry out rolling:
    now the pair of dice is in the holder of the actor;
    now the first die of the pair of dice is a random number from 1 to 6;
    now the second die of the pair of dice is a random number from 1 to 6.
Report rolling:
    say "You roll [detailed state of the dice]."

Test me with "i / roll dice / look / x dice / get dice / x dice / roll dice / roll dice / roll dice / roll dice / roll dice / roll dice / roll dice".

Because we remember the states of the individual dice, not just a total, we can make use of the combination rolled.

The doubles count is a number that varies.
After rolling:
    if the first die of the pair is the second die of the pair, increment the doubles count;
    otherwise now the doubles count is 0;
    continue the action.

Jail is a room. "This is Jail, and not the Just Visiting periphery, either."

Every turn when the doubles count is 3:
    say "The blue-uniformed policemen blows his whistle and beckons you sternly...";
    now the player carries the pair of dice;
    now the player is in Jail;
    now the doubles count is 0.

Every turn when the doubles count is 1 and the player is in Jail:
    say "The warden gruffly releases you.";
    now the player carries the pair of dice;
    now the player is in Go.

175. Wonka's Revenge

paste.png "Wonka's Revenge"

The Caribou Lodge is a room. "Hundreds of expectant faces are turned your way from every table." A lottery drum is in the Lodge. "Before you is the lottery drum[if we have spun the drum], ready to disgorge a ticket[otherwise], waiting to be spun[end if]." In the drum are a red ticket, an orange ticket, a yellow ticket, a green ticket, a blue ticket, a purple ticket, and a ticket of pure gold. The drum is closed and openable.

Understand "spin [something]" as spinning.

Spinning is an action applying to one thing.

Check spinning: if the noun is an open container which contains something, say "[The list of things in the noun] would fly out." instead.

Carry out spinning a container:
    shuffle the contents of the noun.

Report spinning:
    if the noun contains something, say "You rattle [if the noun is transparent][the list of things in the noun][otherwise]the stuff[end if] in [the noun].";
    otherwise say "Nothing results of your shaking [the noun]."

Inform keeps track of the order in which things have been put into a container. If we want to change that order without the player's intervention, we can move the things ourselves.

To shuffle the contents of (basket - a container):
    let moves be the number of things in the basket;
    repeat with counter running from 1 to moves:
        move a random thing in the basket to the basket.

After opening the drum when we have spun the drum for the first time:
    if something (called the pick) is in the drum:
        try searching the drum;
        say "[The pick] it is, then.";
        silently try taking the pick;
        if the pick is the ticket of pure gold, end the story finally;
        otherwise end the story saying "Oh well, better luck next time."

Test me with "open drum / look in drum / close drum / spin drum / open drum".

275. Jokers Wild ★★

Suppose we want a deck of cards which the player can shuffle and draw from. Our first (rather tedious) task is merely to set up the deck as a table:

paste.png "Jokers Wild"

Suit is a kind of value. The suits are hearts, clubs, diamonds, and spades.

Table of Cards

suit

value

diamonds

1

diamonds

2

diamonds

3

diamonds

4

diamonds

5

diamonds

6

diamonds

7

diamonds

8

diamonds

9

diamonds

10

diamonds

11

diamonds

12

diamonds

13

spades

1

spades

2

spades

3

spades

4

spades

5

spades

6

spades

7

spades

8

spades

9

spades

10

spades

11

spades

12

spades

13

hearts

1

hearts

2

hearts

3

hearts

4

hearts

5

hearts

6

hearts

7

hearts

8

hearts

9

hearts

10

hearts

11

hearts

12

hearts

13

clubs

1

clubs

2

clubs

3

clubs

4

clubs

5

clubs

6

clubs

7

clubs

8

clubs

9

clubs

10

clubs

11

clubs

12

clubs

13

We're going to describe the higher numbers as face cards, so it helps to write a new "to say" phrase.

To say (count - a number) as a card value:
    choose row with a value of count in the Table of Value Names;
    say "[term entry]".

Table of Value Names

value

term

1

"ace"

2

"deuce"

3

"three"

4

"four"

5

"five"

6

"six"

7

"seven"

8

"eight"

9

"nine"

10

"ten"

11

"jack"

12

"queen"

13

"king"

Now we get the shuffling of the deck from "sort in random order", so:

Understand "shuffle" as shuffling. Shuffling is an action applying to nothing.

Carry out shuffling:
    sort the Table of Cards in random order;
    say "You expertly rearrange the cards.".

When play begins:
    sort the Table of Cards in random order.

This will continue to work properly even as the deck is partially depleted. Speaking of which, suppose we want the player to be able to toss the cards one-by-one into a hat. They are going to need to be removed from the deck, so:

Understand "toss" or "toss a card" or "toss card" as tossing.

Tossing is an action applying to nothing.

Check tossing:
    if the number of filled rows in the Table of Cards is 0, say "The deck is empty." instead.

Carry out tossing:
    repeat through the Table of Cards:
        let new value be value entry;
        let new suit be suit entry;
        say "You throw the [value entry as a card value] of [suit entry] at the top hat, and [if a random chance of 1 in 3 succeeds]hit[otherwise]miss[end if].";
        blank out the whole row;
        rule succeeds.

If we wanted to simulate a slightly more stimulating game, we could instead have a second table to represent the player's hand of cards and record each card drawn. That would get long for the purposes of example, however, so instead we will just admit that the player's life is an empty husk of existence:

The Empty Room is a room. "It has come to this: sitting on the bare floor of Lulu's apartment with nothing to amuse you but a deck of cards and the top hat from last year's act. You reckon [the number of filled rows in the Table of Cards in words] cardtosses are all that stand between you and the utter pointlessness of existence.

Once again you curse Lulu for running off with that joker."

The player is carrying the deck of cards. The top hat is an open container in the Empty Room. It is scenery.

Test me with "toss / again / again / again / again / again / again / again".

316. Tilt 1 ★★★

We've simulated a deck of cards before, but only as entries in a table. This time we're going to do it more completely, with card objects that can be drawn and discarded, and referred to by name. The tedious way to do this would be to make 52 objects by hand and laboriously write out their names and understand rules.

A more sensible way is to make 52 identical card objects, assign them ranks and suits, and allow Inform to generate and parse their names automatically.

So:

paste.png "Tilt"

Section 1 - Cards

Suit is a kind of value. The suits are hearts, clubs, diamonds, and spades. Understand "heart" as hearts. Understand "club" as clubs. Understand "diamond" as diamonds. Understand "spade" as spades. [Providing the singular forms means that Inform will also understand >EXAMINE SPADE, >DISCARD CLUB, and so on.]

A card is a kind of thing. A card has a suit. A card has a number called rank. Understand the suit property as describing a card. Understand the rank property as describing a card.

52 cards are in the card repository.

Now, we're going to describe the higher numbers as face cards, so it helps to write a new "to say" phrase, just as we did in Jokers Wild. (A subsequent version of this example shows how to print card values with red and black symbols representing the different suits; see "Tilt 3".)

To say (count - a number) as a card value:
    choose row count in the Table of Value Names;
    say "[term entry]".

Rule for printing the name of a card (called target):
    say "[rank of the target as a card value] of [suit of the target]"

Table of Value Names

term

value

topic

"ace"

"1"

"ace/A/one"

"deuce"

"2"

"deuce/two"

"three"

"3"

"three"

"four"

"4"

"four"

"five"

"5"

"five"

"six"

"6"

"six"

"seven"

"7"

"seven"

"eight"

"8"

"eight"

"nine"

"9"

"nine"

"ten"

"10"

"ten"

"jack"

"11"

"jack/knave/J"

"queen"

"12"

"queen/Q"

"king"

"13"

"king/K"

This is enough already to let inform understand things like "ten clubs", but we want to add a couple of refinements. For one thing, we'd like to accept "of" when it appears in phrases such as "ten of clubs" (but not generically otherwise); for another, we'd like the player to be able to use various names for ranks. To this end, we need to borrow from the Activities chapter and modify the player's command before attempting to understand it:

After reading a command:
    if the player's command includes "of [suit]":
        while the player's command includes "of":
            cut the matched text;
    repeat through the Table of Value Names:
        while the player's command includes topic entry:
            replace the matched text with value entry.
    [This allows Inform to understand "ace", "deuce", "king", etc., as numerical ranks.]

It may be a bit confusing that the Table of Value Names has both a topic column and a term column, to all appearances essentially identical. But items in the topic column can be matched against the player's input, whereas items in other kinds of text column can be printed out; the two kinds of text are not treated identically by Inform, so we need to have both. Notice that the topic column contains entries like "jack/knave," which will match either "jack" or "knave" in the player's input.

Now to set up the deck at the outset. With some intelligent looping, we avoid having to declare every combination of suit and number individually:

When play begins:
    reconstitute deck.

To reconstitute deck:
    let current suit be hearts;
    now every card is in the card repository;
    while a card is in the card repository:
        repeat with current rank running from 1 to 13:
            let item be a random card in card repository;
            now rank of item is current rank;
            now suit of item is current suit;
            now item is in the deck of cards;
        now current suit is the suit after the current suit.

And now we need a simple setting and some actions to manipulate the deck with:

Section 2 - The Deck and the Discard Pile

The Empty Room is a room. "Nothing to see here."

The deck of cards is in the Empty Room. It is a closed unopenable container. The description is "A standard poker deck."

The discard pile is a closed unopenable container. The description is "Cards in this game are discarded face-down, so the discard pile is not very interesting to see. All you can observe is that it currently contains [if the number of cards which are in the discard pile is less than ten][the number of cards which are in the discard pile in words][otherwise]about [the rounded number of cards which are in the discard pile in words][end if] card[s]."

To decide what number is the rounded number of (described set - a description of objects):
    let N be the number of members of the described set;
    let R be N divided by 5;
    let total be R times 5;
    decide on total.

The above phrase rounds a number to the nearest five, so that the player is not autistically able to count a large number of cards in the discard pile at a single glance.

This next bit is an optional borrowing from the Activities chapter: we want to prevent Inform printing things like "You can see a discard pile (closed) here.", since we don't want the player to think of the piles as containers, even though Inform thinks of them in those terms.

Rule for printing room description details of something: do nothing instead.

Finally, we want the player to use "draw" and "discard" to manipulate his hand of cards:

Section 3 - Drawing and Discarding Actions

Understand the commands "take" and "carry" and "hold" and "get" and "drop" and "throw" and "discard" as something new.

Understand "take [text]" or "get [text]" or "drop [text]" as a mistake ("Here, you only draw and discard. Nothing else matters at the moment.").

Understand "draw" or "draw card" or "draw a card" as drawing. Drawing is an action applying to nothing. The drawing action has an object called the card drawn.

Setting action variables for drawing:
    now the card drawn is a random card which is in the deck of cards.

Check drawing:
    if the card drawn is nothing, say "The deck is completely depleted." instead.

Check drawing:
    if the number of cards carried by the player is greater than four,
        say "This is a five-card game; you must discard something before drawing anything further." instead.

Carry out drawing:
    move the card drawn to the player.

Report drawing:
    say "You draw [a card drawn]."

Understand "discard [card]" as discarding. Discarding is an action applying to one thing.

Check discarding:
    if the player does not carry the noun, say "You can only discard cards from your own hand." instead.

Carry out discarding:
    now the noun is in the discard pile;
    if the discard pile is not visible, move the discard pile to the location.

Report discarding:
    say "You toss [the noun] nonchalantly onto the discard pile."

Seeding is an action out of world. Understand "seed" as seeding. Carry out seeding: seed the random-number generator with 5681.

Test me with "seed / draw / g / g / g / g / i / discard seven of spades / draw / discard six / draw / i / discard hearts / discard six of diamonds card / draw / draw / i / discard spades card / draw / discard king card".

407. Tilt 2 ★★★

In our previous implementations of playing cards, we've gotten as far as creating decks of individual cards that the player can draw and discard. But in a poker game, one doesn't just have a collection of cards: one has a hand of a specific kind.

Here we take on the job of writing an inventory listing for a poker hand that will reflect the real value of what the player has drawn. To do this, we create a rulebook to sort and assess the cards in the player's hand; its possible return values are limited to the kinds of poker hands that exist, from "high card" to "royal flush".

The first three sections, creating the deck of cards and the means to parse their names, are identical to those we've already seen in Tilt 1; new material begins at section 4.

For the purposes of demonstration, we're simulating something akin to five-card draw without wilds; stud or hold-em variations would add some other complexities.

paste.png "Tilt"

Section 1 - Cards

Suit is a kind of value. The suits are hearts, clubs, diamonds, and spades. Understand "heart" as hearts. Understand "club" as clubs. Understand "diamond" as diamonds. Understand "spade" as spades.

A card is a kind of thing. A card has a suit. A card has a number called rank. Understand the suit property as describing a card. Understand the rank property as describing a card.

52 cards are in the card repository.

To say (count - a number) as a card value:
    choose row count in the Table of Value Names;
    say "[term entry]".

Rule for printing the name of a card (called target):
    say "[rank of the target as a card value] of [suit of the target]"

Table of Value Names

term

value

topic

"ace"

"1"

"ace/A/one"

"deuce"

"2"

"deuce/two"

"three"

"3"

"three"

"four"

"4"

"four"

"five"

"5"

"five"

"six"

"6"

"six"

"seven"

"7"

"seven"

"eight"

"8"

"eight"

"nine"

"9"

"nine"

"ten"

"10"

"ten"

"jack"

"11"

"jack/knave/J"

"queen"

"12"

"queen/Q"

"king"

"13"

"king/K"

After reading a command:
    if the player's command includes "of [suit]":
        while the player's command includes "of":
            cut the matched text;
    repeat through the Table of Value Names:
        while the player's command includes topic entry:
            replace the matched text with value entry.

When play begins:
    reconstitute deck.

To reconstitute deck:
    let current suit be hearts;
    now every card is in the card repository;
    while a card is in the card repository:
        repeat with current rank running from 1 to 13:
            let item be a random card in card repository;
            now rank of item is current rank;
            now suit of item is current suit;
            now item is in the deck of cards;
        now current suit is the suit after the current suit.

Section 2 - The Deck and the Discard Pile

The Empty Room is a room. "Nothing to see here."

The deck of cards is in the Empty Room. It is a closed unopenable container. The description is "A standard poker deck."

The discard pile is a closed unopenable container. The description is "Cards in this game are discarded face-down, so the discard pile is not very interesting to see. All you can observe is that it currently contains [if the number of cards which are in the discard pile is less than ten][the number of cards which are in the discard pile in words][otherwise]about [the rounded number of cards which are in the discard pile in words][end if] card[s]."

To decide what number is the rounded number of (described set - a description of objects):
    let N be the number of members of the described set;
    let R be N divided by 5;
    let total be R times 5;
    decide on total.

Rule for printing room description details of something: do nothing instead.

Section 3 - Drawing and Discarding Actions

Understand the commands "take" and "carry" and "hold" and "get" and "drop" and "throw" and "discard" as something new.

Understand "take [text]" or "get [text]" or "drop [text]" as a mistake ("Here, you only draw and discard. Nothing else matters at the moment.").

Understand "draw" or "draw card" or "draw a card" as drawing. Drawing is an action applying to nothing. The drawing action has an object called the card drawn.

Setting action variables for drawing:
    now the card drawn is a random card which is in the deck of cards.

Check drawing:
    if the card drawn is nothing, say "The deck is completely depleted." instead.

Check drawing:
    if the number of cards carried by the player is greater than four,
        say "This is a five-card game; you must discard something before drawing anything further." instead.

Carry out drawing:
    move the card drawn to the player.

Report drawing:
    say "You draw [a card drawn]."

Understand "discard [card]" as discarding. Discarding is an action applying to one thing.

Check discarding:
    if the player does not carry the noun, say "You can only discard cards from your own hand." instead.

Carry out discarding:
    now the noun is in the discard pile;
    if the discard pile is not visible, move the discard pile to the location.

Report discarding:
    say "You toss [the noun] nonchalantly onto the discard pile."

New material begins here. We want to start by grouping cards together, but identifying poker hands only if the player holds a full five cards.

Section 4 - Assessing Hands

Before listing contents while taking inventory: group cards together.

Before grouping together cards:
    if the number of cards carried by the player is 5:
        say "[run paragraph on]";
        follow the hand-ranking rules;
        if the rule succeeded, say "[the outcome of the rulebook]";
        otherwise say "some random cards";
        if the outcome of the rulebook is pair outcome, say " of [rank of the first thing held by the player as a card value]s";
    otherwise:
        say "[number of cards carried by the player in words] assorted cards";
    say " (".

Rule for grouping together cards:
    say "[list hand]".

To say list hand:
    let chosen card be the first thing held by the player;
    while chosen card is a card:
        say "[chosen card]";
        now chosen card is the next thing held after chosen card;
        if chosen card is a card, say ", ".

After grouping together cards:
    say ")".

The ranking of poker hands traditionally depends on three features: 1) whether all the cards are of the same suit (flush); 2) whether the cards constitute a numerical run of ranks (straight); and 3) how many cards or sets of cards are of matching rank (pairs, three of a kind, and four of a kind). Here we will start by assessing our hand to determine these qualities:

The hand-ranking rules is a rulebook. The hand-ranking rules have outcomes royal flush, straight flush, four of a kind, full house, flush, straight, three of a kind, two pairs, pair, high card.

The hand-ranking rulebook has a truth state called the flushness.
The hand-ranking rulebook has a truth state called the straightness.

The hand-ranking rulebook has a number called the pair count.
The hand-ranking rulebook has a number called the triple count.
The hand-ranking rulebook has a number called the quadruple count.

For convenience in identifying hand features, and for elegance when we print the hand-listing, we start by sorting the cards in the player's hand so that the high-ranked cards are listed first. It is rare that we want to concern ourselves with this, but as we saw in the section on "Looking at containment by hand" in the chapter on Change, Inform keeps an ordered list of the items inside any given container; so it does order the objects in the player's hand, and the ordering depends on which things were added to the hand most recently. By moving something to the player's hand again (even if it was already there), we change this ordering, and wind up with a sorted hand.

A card can be sorted or unsorted. A card is usually unsorted.

Definition: a card is high if its rank is 11 or more.
Definition: a card is low if its rank is 4 or less.

A hand-ranking rule (this is the initial sort rule):
    now every card is unsorted;
    while the player carries an unsorted card:
        let item be the lowest unsorted card held by the player;
        move item to the player;
        now the item is sorted;
    if sort-debugging is true, say "-- after initial sort: [list hand]".

This last printing instruction is there for diagnostic purposes: later we'll add a testing command to turn debugging on and off; when it's on, the game will print out its card list at various stages in sorting, to help us trouble-shoot any problems. In normal play, however, this will be off.

Next up, a check to see whether the player has a flush:

A hand-ranking rule (this is the finding flushness rule):
    let called suit be the suit of a random card carried by the player;
    if every card carried by the player is called suit, now flushness is true.

Now we check for straights; this is slightly complicated by the fact that an ace can be either the bottom of a low straight (lower than 2) or the top of a high straight (higher than king), so we explicitly check both possibilities.

A hand-ranking rule (this is the finding straightness rule):
    now straightness is true;
    let N be the rank of the highest card which is carried by the player;
    repeat with current rank running from N - 4 to N:
        now the test rank is the current rank;
        unless the player carries a matching card:
            if the current rank is N - 4 and the current rank is 9 and the player carries an ace card, do nothing; [this covers the case where an ace could be the top card of the sequence]
            otherwise now straightness is false.

And finally, we need to identify any groups of cards of the same rank. We want to know how many groups there are and how large each group is (though in practice there can only be one group of three or four in a standard-sized poker hand). We also want to mark any grouped cards so that we can move them to the front of the player's hand when we take inventory.

A card can be quadrupled, tripled, paired or uncombined.

Test rank is a number that varies. Definition: a card is matching if its rank is the test rank.

This definition is a convenience so that we don't have to write so many explicit loops in the following rule:

A hand-ranking rule (this is the counting multiples rule):
    now every card is uncombined;
    repeat with current rank running from 1 to 13:
        now test rank is current rank;
        let N be the number of matching cards held by the player;
        if N is 4:
            increment the quadruple count;
            now every matching card held by the player is quadrupled;
        if N is 3:
            increment the triple count;
            now every matching card held by the player is tripled;
        if N is 2:
            increment the pair count;
            now every matching card held by the player is paired.

Next we tweak our sorting to reflect the make-up of the hand. There are two reasons why this might differ from the straight highest-to-lowest sort we did earlier:

1) we want to list aces as high unless they are serving as the bottom of a low straight, in which case they should appear last;

2) we want combinations to appear at the front of the list, sorted from highest value to lowest value: larger combinations first, then smaller combinations, and combinations of equal size sorted by rank.

A hand-ranking rule (this is the move aces up unless there's a low straight rule):
    unless the straightness is true and the lowest card carried by the player is an ace card and the rank of the highest card carried by the player is 5,
        now every ace card which is carried by the player is carried by the player;
    if sort-debugging is true, say "-- after ace movement rule: [list hand]".

A hand-ranking rule (this is the move pairs forward rule):
    while the player carries a paired card:
        let selection be the lowest paired card which is carried by the player;
        move the selection to the player;
        now the selection is uncombined;
    if sort-debugging is true, say "-- after pairs movement: [list hand]".

A hand-ranking rule (this is the raise ace pairs rule):
    if the player carries exactly two ace cards:
        repeat with item running through ace cards which are carried by the player:
            move item to the player;
    if sort-debugging is true, say "-- after paired-ace movement: [list hand]".

A hand-ranking rule (this is the move multiples forward rule):
    while the player carries a tripled card:
        let selection be the lowest tripled card which is carried by the player;
        move the selection to the player;
        now the selection is uncombined;
    while the player carries a quadrupled card:
        let selection be the lowest quadrupled card which is carried by the player;
        move the selection to the player;
        now the selection is uncombined;
    if sort-debugging is true, say "-- after multiples movement rule: [list hand]".

Definition: a card is ace if its rank is 1.
Definition: a card is king if its rank is 13.

Now, having determined the salient qualities of our hand, we run through rules in order from the highest kind of poker combination to the lowest. Because of the order of the source, Inform will choose whichever combination applies first.

A hand-ranking rule (this is the royal-flush rule):
    if flushness is true and straightness is true and the highest card carried by the player is king and the lowest card carried by the player is ace, royal flush.

A hand-ranking rule (this is the straight-flushes rule):
    if flushness is true and straightness is true, straight flush.

A hand-ranking rule (this is the four-of-a-kind rule):
    if the quadruple count is 1, four of a kind.

A hand-ranking rule (this is the full-house rule):
    if the pair count is 1 and the triple count is 1, full house.

A hand-ranking rule (this is the flushes rule):
    if flushness is true, flush.

A hand-ranking rule (this is the straights rule):
    if straightness is true, straight.

A hand-ranking rule (this is the three-of-a-kind rule):
    if triple count is 1, three of a kind.

A hand-ranking rule (this is the two-pair rule):
    if the pair count is 2, two pairs.

A hand-ranking rule (this is the pair rule):
    if the pair count is 1, pair.

A hand-ranking rule (this is the default rule):
    high card.

And finally, we need to define our debugging variable here, even though we won't give the player the ability to turn it on and off except in the special testing section.

Sort-debugging is a truth state that varies.

For many examples, a test-me script is enough to prove that the example does what it ought. This example, though, is a bit more complicated, and hard to test randomly. The remainder of the source here shows how we might write a test to verify the desired behavior of our rulebook. Those who are only interested in the rulebook itself can stop reading at this point.

Section 5 - Testing hand identification - Not for release

For the sake of testing our rules, we provide an apparatus that will load the player's hand up with sample hands of each kind, then show the result to make sure that the hand is being correctly identified.

Understand "debug sorting" as debugging hand sorting. Debugging hand sorting is an action out of world.

Carry out debugging hand sorting:
    if sort-debugging is false, now sort-debugging is true;
    otherwise now sort-debugging is false.

Report debugging hand sorting:
    say "Sort debugging is now [if sort-debugging is true]on[otherwise]off[end if]."

Test me with "draw / g / g / g / g / force hand / g / g / g / g / g / g / g / g / g / g / g / g".

The somewhat rough-and-ready principle of this table is that we will overwrite the cards in the player's hand by resetting their ranks and suits; every five rows of the table represent a new poker hand for the game to attempt to sort and identify. These include one example of each of the major kinds of poker hand, plus a couple of variations involving aces which test the special sorting rules.

Table of Testing Hands

set suit

set rank

spades

1

[royal flush]

spades

13

spades

12

spades

11

spades

10

clubs

12

[straight flush]

clubs

11

clubs

10

clubs

9

clubs

8

diamonds

8

[four of a kind]

hearts

8

spades

8

clubs

8

clubs

3

clubs

1

[full house]

spades

1

hearts

10

spades

10

clubs

10

hearts

2

[flush]

hearts

5

hearts

7

hearts

11

hearts

12

hearts

1

[straight]

spades

13

diamonds

12

clubs

11

hearts

10

hearts

2

[three of a kind]

spades

2

clubs

2

clubs

4

spades

3

diamonds

6

[two pairs]

spades

6

clubs

7

diamonds

7

hearts

9

diamonds

6

[two pairs, ace high]

spades

6

clubs

1

diamonds

7

hearts

1

hearts

12

[pair]

spades

12

diamonds

10

spades

7

clubs

4

diamonds

13

[high]

hearts

11

spades

9

clubs

7

diamonds

5

hearts

1

[tricky sorting: low straight]

diamonds

2

spades

3

diamonds

4

diamonds

5

Understand "force hand" as forcing a hand. Forcing a hand is an action out of world.

Current marker is a number that varies.

Carry out forcing a hand:
    repeat with item running through cards which are carried by the player:
        increment current marker;
        if current marker is greater than the number of filled rows in the Table of Testing Hands, now current marker is 1;
        choose row current marker in the Table of Testing Hands;
        now the suit of item is the set suit entry;
        now the rank of item is the set rank entry.

Report forcing a hand:
    try taking inventory.

RB §9.6. Reading Matter

Many things can be read, from warning notices to encyclopaedias, and a range of techniques is needed to provide them because the quantity of text, and how it presents itself, can vary so much. With a small amount of very large type, the player should not need any command at all to read the text:

The road sign is in the Junction. The road sign is fixed in place. "A road sign points north: 'Weston on the Green - 6'."

If the print is smaller, or the object portable, the player will expect to use the EXAMINE command:

The business card is in the Junction. The description is "'Peter de Sèvres: consultant mnemonicist.'"

But if the object is a leaflet, say, EXAMINE should only describe the cover: READ would be the command a player would expect to use to get at the text itself. Inform normally defines READ to be the same command as EXAMINE, which is good for things like the business card, but counter-productive here. The Trouble with Printing shows how to separate these two commands, allowing any thing to have a property called its "printing" for text produced by READ, which will be different from its "description", the text produced by EXAMINE.

If the object is a lengthy diary, say, nobody would read it from cover to cover in a single IF turn. We might then want to allow the player to turn the pages one by one, with commands like READ PAGE 4 IN DIARY or READ THE NEXT PAGE: see Pages.

If the object is an encyclopaedic reference work, the player would consult named entries: see Costa Rican Ornithology ★★★, which allows commands like LOOK UP QUETZAL IN GUIDE.

Still larger sources of text often occur in IF: libraries or bookshelves, where many books are found together, and it is clumsy to write them as many individual items. One approach is to simulate an entire bookshelf with a single thing: see Bibliophilia ★★. (This is much like looking up topics in a single book, except that each topic is a book in itself.) Another is to provide each book as an individual item, but have them automatically join together into a single portable collection: see AARP-Gnosis ★★.

Signs, leaflets and encyclopaedias, being printed, have a wording which will never change during play. But sometimes the player reads something which acts of its own accord. Text substitutions are usually all that is needed to achieve this:

The computer display is on the desk. The description is "Giant green digits read: [the time of day]."

This is easy because we know all the variations we want. But what if we want the player to write his own text, for instance, adding to a diary? This is trickier, because it means storing text as the player typed it, and replaying it later. (And suppose the player types reams and reams of text, not just a few words as we might have hoped?) The Fourth Body and The Fifth Body ★★ show how to use an external file - a multimedia trick requiring features only available if the project is set to the Glulx story file format - to handle even the most difficult cases.

Should we want a computer that responds to vocal commands, as in ASK COMPUTER ABOUT KLINGONS, the built-in extension Inanimate Listeners will allow the player to talk to inanimate objects as well as people.

Examples

292. The Trouble with Printing

paste.png "The Trouble with Printing"

A thing has some text called printing. The printing of a thing is usually "blank".

Understand the command "read" as something new. Understand "read [something]" as reading. Reading is an action applying to one thing, requiring light. Check reading: if the printing of the noun is "blank", say "Nothing is written on [the noun]." instead. Carry out reading: say "You read: [printing of the noun][line break]". Report reading: do nothing.

The Archive is a room.

Berkeley's report is a thing in the Archive. The description is "A report from Governor Sir William Berkeley of Virginia, in 1671, in answer to the queries sent by the Commissioners of Plantations the year previous. Of this report the better part is burned and only a tail fragment remains." The printing of Berkeley's report is "I thank God, [italic type]there are no free schools[roman type] nor [italic type]printing[roman type], and I hope we shall not have these hundred years; for [italic type]learning[roman type] has brought disobedience, and heresy, and sects into the world, and [italic type]printing[roman type] has divulged them..."

Test me with "examine report / read report".

Since we defined reading as an action requiring light, we could further distinguish reading and examining (if we wanted) by writing some different visibility rules for it.

303. Pages

Suppose we have a book that the player must consult page-by-page, and we want to be able to accept all of the following input:

> READ BOOK (to choose a random page and read it)
> READ PAGE 1 IN BOOK
> READ PAGE 2
> READ THE LAST PAGE OF THE BOOK
> READ THE NEXT PAGE
> READ PREVIOUS PAGE IN BOOK
> READ THE FIRST PAGE

One approach would be to write many different understand rules and actions: one action for reading randomly, one for reading a specific page, one for reading the first page, one for reading the previous page, one for reading the next page, and one for reading the last page. But this gets tedious to construct and maintain.

More usefully, we could consider that all of the last four options are essentially the same action at heart: the player is asking to read a page in the book using a name rather than a number, and we will have to perform a minor calculation to discover what the number should be. Here's an implementation using named values to resolve this problem:

paste.png "Pages"

The Library is a room. The sinister book is carried by the player. The sinister book has a number called the last page read. The sinister book has a number called the length. The length of the sinister book is 50.

Understand the command "read" as something new.

Understand "read [something]" or "consult [something]" or "read in/from [something]" as reading. Reading is an action applying to one thing, requiring light.

Understand "read [number] in/from/of [something]" or "read page [number] in/from/of [something]" or "look up page [number] in/from/of [something]" or "consult page [number] in/from/of [something]" as reading it in. Reading it in is an action applying to one number and one thing, requiring light.

Named page is a kind of value. The named pages are first page, last page, next page, previous page.

To decide what number is the effective value of (L - last page):
    decide on the length of the book.

To decide what number is the effective value of (F - first page):
    decide on 1.

To decide what number is the effective value of (N - next page):
    let X be the last page read of the book plus 1;
    decide on X.

To decide what number is the effective value of (P - previous page):
    let X be the last page read of the book minus 1;
    decide on X.

Understand "read [named page] in/from/of [something]" or "read the [named page] in/from/of [something]" as reading it relatively in. Reading it relatively in is an action applying to one named page and one thing, requiring light.

Does the player mean reading something in the sinister book: it is very likely.

This is the book requirement rule:
    if the player is not carrying the sinister book, say "You're not reading anything." instead.

Check reading it relatively in:
    if the second noun is not the sinister book, say "There are no pages in [the second noun]." instead;
    abide by the book requirement rule.

Carry out reading it relatively in:
    let N be the effective value of the named page understood;
    now the number understood is N;
    try reading N in the book.

Check reading it in:
    if the second noun is not the sinister book, say "There are no pages in [the second noun]." instead;
    abide by the book requirement rule.

Check reading it in:
    if the number understood is greater than the length of the sinister book, say "There are only [length of sinister book in words] pages in the book." instead;
    if the number understood is less than 1, say "The page numbering begins with 1." instead.

Carry out reading it in:
    read page number understood.

Check reading:
    if the noun is not the sinister book, say "There are no pages in [the noun]." instead;
    abide by the book requirement rule.

Carry out reading:
    let N be a random number between 1 and the length of the sinister book; now the number understood is N;
    say "You flip the pages randomly and arrive at page [the number understood]:[paragraph break]";
    try reading the number understood in the sinister book.

Table of Book Contents

page

content

2

"dhuma jyotih salila marutam / samnipatah kva meghah / samdes arthah kva patukaranaih / pranibhih prapaniyah"

13

"amathesteron pws eipe kai saphesteron"

50

"Rrgshilz maplot..."

To read page (N - a number):
    now the last page read of the sinister book is N;
    if there is a content corresponding to a page of N in the Table of Book Contents:
        choose row with a page of N in the Table of Book Contents;
        say "You read: '[content entry]'[paragraph break]";
    otherwise:
        say "Page [N] appears to be blank."

To read page (N - 47):
    say "Your eyes burn; your ears ring. Beneath your gaze, the dreadful sigils writhe, reminding you of that which lies outside the edges of the universe...";
    end the story saying "You have lost your remaining sanity".

Test me with "read from the sinister book / read the book / read the next page / read page 2 / read previous page / g / read the first page / read the last page of the book / read the next page / read 47 in book".

443. The Fourth Body

Some mystery games supply the player with an in-game system for taking notes, in case he doesn't want to rely on scraps of paper next to the computer. One way of doing this is to write out all the player's notes and observations into a notebook file, whose contents can be retrieved during play (or, indeed, after it).

We'll first invent a general system for writing text into notebooks, by creating a new kind called jotter. Each individual jotter will have its own disc file, and there will be basically three things which can be done with jotters: erasing, reading and writing.

paste.png "The Fourth Body"

A jotter is a kind of thing. A jotter has an external file called the text file. A jotter can be fresh or used. A jotter is usually fresh. A jotter has a text called the heading.

The currently erased jotter is an object that varies.
To erase (pad - a jotter):
    now the currently erased jotter is the pad;
    write "[heading of the currently erased jotter][paragraph break]" to the text file of the pad;
    now the pad is fresh.

To write in (pad - a jotter):
    append "[the time of day]: [topic understood][line break]" to the text file of the pad;
    now the pad is used.

To read (pad - a jotter):
    say "You read: [paragraph break][text of the text file of the pad]".

This is all as might be expected, except perhaps for the business of the "currently erased jotter". Why copy "pad" into this - why not simply write "[heading of the pad]"? The answer is that "pad" is a temporary "let" value, and cannot be used inside other phrases, such as the "write ... to ..." phrase.

We want to erase any jotters when play begins, as otherwise text left over from any previous games will still be visible:

When play begins:
    repeat with pad running through jotters:
        erase the pad.

Now we need to create rules to allow the player to control reading, writing and erasing. Reading we will handle with the ordinary examining action, but we create new actions for writing and erasing. A nice little trick allows WRITE WHATEVER to default to writing WHATEVER in a notebook being carried.

Instead of examining a used jotter (called the pad):
    read the pad.

Instead of examining a fresh jotter (called the pad):
    say "There is nothing of note in [the pad]."

Understand "write [text] in [something preferably held]" as writing it in. Understand "write [text]" as writing it in. Writing it in is an action applying to a topic and one thing. Rule for supplying a missing second noun while writing: if a jotter (called the pad) is carried, now the second noun is the pad; otherwise say "You will have to specify what to write that it."

Check writing it in:
    if the second noun is not a jotter, say "It would be better to write in a notebook." instead.

Carry out writing it in:
    write in the second noun.

Report writing it in:
    say "Under the current time, you write '[the topic understood]' into [the second noun]."

Understand "erase [something preferably held]" as erasing. Erasing is an action applying to one carried thing.

Check erasing:
    if the noun is not a jotter, say "It's hard to see how." instead.

Carry out erasing:
    erase the noun.

Report erasing:
    say "You scrub out all the entries in [the noun]."

That completes a general-purpose implementation of jotters, and we put it to use:

The player carries a jotter called your notebook. The file of Player's Observations is called "notebook". The text file of your notebook is the file of Player's Observations. The heading of your notebook is "Observations in the Pottingham Green Case".

The Damp Hillside is a room. "It is just after dawn: among the trees there is misty and pale blue light. [if Havers is in the location]The only saturated color in view is the orange-and-yellow jacket of [Detective Havers]. She is trying unsuccessfully to light a cigarette. [end if][paragraph break]The body itself is further down, closer to the bottom of the ravine. It would be foolish to speculate before seeing it, but the odds are that the corpse was rolled down after death. The ground is not steep enough for the fall itself to be deadly."

Detective Havers is a woman in the Damp Hillside. The description is "She gives you a weak smile when you look at her: you know she hasn't slept more than three hours any of the last few nights." Havers is scenery.

Havers is carrying a jotter called Barbara's notebook. The file of Barbara's Observations is called "barbara". The text file of Barbara's notebook is the file of Barbara's Observations. The heading of Barbara's notebook is "I could murder a cup of tea".

The time of day is 6:32 AM.

Instead of examining your notebook when your notebook is fresh:
    say "Your notebook is blank. Back in the office, of course, there are a stack of others. But you brought a fresh notebook in a kind of weary hope. You're going to pretend, just for now, that this body might be unrelated to the graphic string of murders you're already investigating."

324. Bibliophilia ★★

Suppose we want a bookshelf with a very large number of books on it. They aren't to be taken or carried around in the game, but they should be mentioned, and the player should be allowed to look them up by name. Furthermore, the player's attempts to examine something unrecognized should be understood as an attempt to look up a title -- but only when the player is in the presence of the books. The rest of the time such requests should be rejected in the usual way.

paste.png "Bibliophilia"

The Graduate Lounge is a room. "Shabby sofas; plastic cups remaining from the afternoon's pre-lecture espresso; a collection of Xena and Hercules figurines posed for ironic effect. It's somewhat depressing at this hour, when everyone has gone home."

The Classics Reading Room is south of the Lounge. "Not as large a collection as the one in the Library, but it contains copies of everything really essential for reference."

Understand "examine [text]" as examining as a book when the player is in the Reading Room. Understand "look up [text]" as examining as a book when the player is in the Reading Room.

Examining as a book is an action applying to one topic.

Carry out examining as a book:
    say "You can't find any such text."

Instead of examining as a book a topic listed in the Table of Book Titles:
    say "[description entry][paragraph break]"

Table of Book Titles

topic

title

description

"Reading Greek Death" or "reading/greek/death" or "greek death"

"Reading Greek Death"

"A dense orange paperback treatise on the development of Greek eschatology."

"TAPA/Transactions/134-2"

"TAPA 134-2"

"Transactions of the American Philological Association from 2004."

"Oxford Classical Dictionary" or "OCD/dictionary/classical/oxford"

"Oxford Classical Dictionary"

"A hefty reference with short articles on everything from Greek meter to ancient cosmetics."

"Collected Dialogues of Plato" or "Plato/dialogues/hamilton/cairns"

"Collected Dialogues of Plato"

"All the Platonic dialogues -- some, admittedly, in rather tired translations -- but still a useful single volume, ed. Edith Hamilton and Huntington Cairns."

"Adobe Illustrator CS User Guide" or "user guide" or "adobe illustrator" or "adobe/illustrator/cs/user/guide"

"Adobe Illustrator CS User Guide"

"Hello, how did this get here? A suspiciously familiar name is scribbled inside the front cover..."

Some books are scenery in the Reading Room. Understand "copies" or "book" or "shelf" or "shelves" as the books. Instead of examining the books:
    choose a random row in the Table of Book Titles;
    say "You scan the shelves and notice, among others, a volume entitled [italic type][title entry][roman type]."

Test me with "south / examine ocd / examine books / examine books / examine plato / n / x hercules / s / x hercules".

Now if we type >X HERCULES in the Lounge, we will get

>x hercules
You can't see any such thing.

thanks to our somewhat slovenly implementation of the Lounge scenery; but in the Reading Room,

>x hercules
You can't find any such text.

In practice we might also want to extend our coverage somewhat to handle a case where the player tried to take books from the bookshelf: currently that would not be understood.

335. AARP-Gnosis ★★

Suppose we have a complete Encyclopedia in our game. The player is allowed to pick up the whole set (there must not be too many volumes), but also to do things with individual volumes, and indeed to scatter these volumes all over the place. Putting a volume back in the same place as the rest of the Encyclopedia should, however, restore it to the collective. We will start out by defining general rules for collectives like this:

paste.png "AARP-Gnosis"

Fitting relates various things to one thing (called the home). The verb to fit means the fitting relation. Definition: a thing is missing if it is not part of the home of it.

A collective is a kind of thing.

Before doing something to something which is part of a collective:
    let space be the holder of the home of the noun;
    move the noun to the space.

Instead of examining a collective:
    say "[The noun] consists of [the list of things which are part of the noun]."

Now the real work begins. One reason to make this an activity is that we might easily want to override it for specific objects; for instance, the generic collecting activity here would not deal properly with collectives of clothing where some items might be worn and others not. In that case, we would want to write another, more specific "collecting" activity to handle the complexities of fashion.

Collecting something is an activity.

Every turn:
    repeat with item running through collectives:
        carry out the collecting activity with the item.

To remove (item - a thing) when empty:
    let space be the holder of the item;
    if the number of things which are part of the item is 0:
        now the item is nowhere;
    if the number of things which are part of the item is 1:
        let the last thing be a random thing which is part of the item;
        move the last thing to the space;
        now the item is nowhere.

Before collecting a thing (called the item):
    remove item when empty;
    let space be the holder of the item;
    if space is not a thing and space is not a room:
        if something (called the other space) contains at least two things which fit the item, move item to the other space;
        if a room (called the other space) contains at least two things which fit the item, move item to the other space;
        if someone (called the owner) carries at least two things which fit the item, move item to the owner.

Rule for collecting a thing (called the item):
    let space be the holder of the item;
    if space is a thing or space is a room:
        repeat with component running through things held by the space:
            if the component fits the item, now the component is part of the item;
        remove item when empty.

And now for a cheerful scenario:

The Boise Memorial Library is a room. "A concrete box of a room, roughly eight feet by fourteen, which contains all the fallout shelter has to offer by way of entertainment. Someone with a grim sense of humor has tacked a READ! literacy poster to the door, as though there were anything else to do while you await the calming of the Geiger counters." The shelf is a supporter in the Library. "A battered utility shelf stands against the south wall."

The New Idahoan Encyclopedia Set is a collective. Volume A-Aalto fits the Encyclopedia. It is part of the Set. Volume AAM-Aardvark fits the Encyclopedia. It is part of the Set. Volume Aarhus-Aaron fits the Encyclopedia. It is part of the Set. Volume AARP-Gnosis fits the Encyclopedia. It is part of the Set. Volume Gnu-Zygote fits the Encyclopedia. It is part of the Set. The Set is on the shelf.

Let's have the Encyclopedia describe itself differently depending on whether it's all in one place:

After printing the name of the Set when something missing fits the Set:
    say " (missing [a list of missing things which fit the Set])"

Before printing the name of the Set when the number of missing things which fit the set is 0:
    say "complete ".

Test me with "get aarhus-aaron / look / inventory / get aam-aardvark / look / get gnu-zygote / look / get aarp-gnosis / look / inventory / drop set / look / get set / get a-aalto / inventory".

444. The Fifth Body ★★

The implementation here is much like that of the previous example, except that we allow the player to write his notebook input as a separate command, leading to an exchange such as

>write in my notebook
You open your notebook and prepare to write in it.

>>Am beginning to think that HT and BGG are in this together.
You finish writing and fold your notebook away.

>read my notebook
You read:

Wednesday morning

Am beginning to think that HT and BGG are in this together.

The opening is much as before:

paste.png "The Fifth Body"

A jotter is a kind of thing. A jotter has an external file called the text file. A jotter can be fresh or used. A jotter is usually fresh. A jotter has a text called the heading.

The currently erased jotter is an object that varies.

To erase (pad - a jotter):
    now the currently erased jotter is the pad;
    write "[heading of the currently erased jotter][paragraph break]" to the text file of the pad;
    now the pad is fresh.

To write in (pad - a jotter):
    append "[the time of day]: [player's command][line break]" to the text file of the pad;
    now the pad is used.

To read (pad - a jotter):
    say "You read: [paragraph break][text of the text file of the pad]".

When play begins:
    repeat with pad running through jotters:
        erase the pad.

Instead of examining a used jotter (called the pad):
    read the pad.

Instead of examining a fresh jotter (called the pad):
    say "There is nothing of note in [the pad]."

Target jotter is an object that varies. The target jotter is usually nothing.

Understand "write in [something preferably held]" as writing in. Writing in is an action applying to one thing.

Check writing in:
    if the noun is not a jotter, say "It would be better to write in a notebook." instead.

Carry out writing in:
    now the command prompt is ">>";
    now the target jotter is the noun.

Report writing in:
    say "You open [the noun] and prepare to write in it."

Now what happens is that the player, having typed WRITE IN NOTEBOOK, will be faced with a ">>" prompt instead of the usual ">": a sign that the input mode has changed.

The next code is to react to reading a command. Whatever the player types at the >> prompt when the target jotter is set will now be recorded in the notebook, though with a character limit of about 60-100 characters depending on how much upper-case and punctuation he uses. (There are ways to lift the character length restriction as well, but they would take us into deeper waters.)

After reading a command when target jotter is a jotter:
    now the command prompt is ">";
    write in target jotter;
    now target jotter is used;
    say "You finish writing and fold your notebook away.";
    now the target jotter is nothing;
    reject the player's command.

Understand "erase [something preferably held]" as erasing. Erasing is an action applying to one carried thing.

Check erasing:
    if the noun is not a jotter, say "It's hard to see how." instead.

Carry out erasing:
    erase the noun.

Report erasing:
    say "You scrub out all the entries in [the noun]."

The player carries a jotter called your notebook. The file of Player's Observations is called "notebook". The text file of your notebook is the file of Player's Observations. The heading of your notebook is "Sunday Morning".

The Vestry is a room. "[Havers] hangs back by the door: the forensics expert is not finished with a preliminary examination of the body. From here you can't see much, except that the expert has peeled back and laid to one side a liturgical vestment that someone at the church used to cover the corpse until the police came. What was once a cream silk with festive Easter embroidery is now stained with blood-colored handprints."

Detective Havers is a woman in the Vestry. The description is "She looks glumly back. There's still a purple-ish bruise on her cheekbone from the disaster Thursday afternoon." Havers is scenery.

Havers is carrying a jotter called Barbara's notebook. The file of Barbara's Observations is called "barbara". The text file of Barbara's notebook is the file of Barbara's Observations. The heading of Barbara's notebook is "Sun. AM".

The time of day is 9:11 AM.

94. Costa Rican Ornithology ★★★

The following relies on quite a number of features we haven't met yet: tables, rules for printing names, instructions for understanding the player's commands. It is offered simply as an example of how a fully implemented book might be handled in Inform.

paste.png "Costa Rican Ornithology"

A book is a kind of thing. Understand "book" as a book. A book has a table name called the contents.

Instead of consulting a book about a topic listed in the contents of the noun:
    say "[reply entry][paragraph break]".

Report consulting a book about:
    say "You flip through [the noun], but find no reference to [the topic understood]." instead.

With this "topic understood" phrase, we're telling Inform to print back the word or phrase that the player was attempting to look up. This overrides the more general default response, "You discover nothing of interest in the book."

We now have the essential elements to construct whatever books we like. Now let's have an example of a specific book:

The Guide to Central American Birds is a book carried by the player. The contents of the Guide is the Table of Listed Birds.

We will come back to the idea of tables and table names later, but for now the important thing is that we have instructed Inform to look up its answers to consulting the bird guide in this form:

Table of Listed Birds

topic

reply

"[red]" or "[red] bird/macaw"

"You flip through the Guide for a while and eventually discover a reference to the [scarlet macaw], which appears to correspond with what you see before you."

"quetzal/trogon" or "resplendent trogon"

"The entry on the quetzal is quite lyrical, describing its brilliant plumage, flashing and igniting in the sunshine, which is supposedly sufficient to lure birdwatchers from all over the world. Unfortunately, the quetzal is described as being bright emerald in color, with a pink fuzz on its head and a long soft tail 'like a feather boa'. None of these describes your visitor."

The topic column is a bit special: it matches the player's input, and is not meant to be printed out again. Topic columns will be discussed further in the chapter on Tables. (Note also that, however it may appear in the documentation, the topic column should not be spanning multiple lines in our source text.)

We may also compress long or complicated topics by creating bracketed abbreviations, and in fact it's useful to do so now, to explain the red token we just used:

Understand "red-orange" or "bird" or "red" or "orange" as the scarlet macaw. Understand "red-orange" or "red" or "orange" or "scarlet" as "[red]".

This technique is discussed further in the chapter on Understanding.

If we wanted more books, we could define those in the same way, giving each its own separate contents table to be used for consultation. But for the sake of the example we will keep it simple, and move on to the scenario itself:

The Veranda is a room. "From here you can see a considerable expanse of dense-growing jungle plants, and eventually the open water beyond."

The scarlet macaw is an animal in the veranda. "A vibrantly-colored [scarlet macaw] perches on the rail."

A thing can be known or unknown.

Before printing the name of the scarlet macaw while consulting:
    now the scarlet macaw is known.

Rule for printing the name of the unknown scarlet macaw: if the macaw is unknown, say "red-orange bird of unknown species".

Test me with "look up penguins in the guide / look up quetzal in guide / look up silver nuthatches in the guide / look / look up red bird in the book / look".

RB §9.7. Painting and Labeling Devices

Writing on something is only one way a player can change its visual appearance. IF authors have long been wary of paint brushes, because a sufficiently motivated player could go through a whole landscape like a graffiti artist with a railway bridge. We want to give the player the illusion of freedom of action, while avoiding a situation where unlimited numbers of different decorations might be needed - that would need a table of potentially unlimited size.

One approach is to limit the number of items which can be decorated. In Palette, only the canvas can be painted, and each image overlays the last. Early Childhood ★★★ increases the range to allow a whole kind ("block") to be painted, and also shows how the changing colours can be used to distinguish between otherwise identical objects.

Brown ★★★ finds a different way to limit the number of simultaneous decorations: almost anything can have a red sticky label attached, but there is only one red sticky label. (So to decorate a new item, the player must first un-decorate an old one.)

See also

Electricity and Magnetism for another form of stickiness

Examples

308. Palette

There are hundreds of traditional pigments, from lampblack to burnt sienna, so we will confine ourselves to just two:

paste.png "Palette"

The Atelier is a room. "The floridly untidy loft space used by a moderately unsuccessful artist (you, that is)." The canvas, palette and paint brush are here. Understand "painting" as the canvas.

Colour is a kind of value. The colours are white, red, blue and green.

The canvas has a colour. The canvas is white. The printed name of the canvas is "largely [colour] canvas".

Painting is an action applying to one thing and one colour. Check painting: if the noun is not the canvas, say "Centuries of tradition suggest that canvas is the natural home of paint." instead. Carry out painting: now the colour of the canvas is the colour understood. Report painting: say "You splash away at the now [canvas]."

Understand "paint [something] [a colour]" as painting.

Understand "calico" as white. Understand "cerulean" or "cerulean blue" as blue.

Test me with "examine canvas / paint canvas red / examine canvas / paint canvas cerulean / examine canvas".

35. Brown ★★★

paste.png "Brown"

The Shipping Room is a room. The red sticky label is a thing carried by the player. The description of the red sticky label is "It reads: AIRMAIL[if the label is part of something (called the parent)]. It is stuck to [the parent][end if]."

A black crate is in Shipping. The description is "A boring black crate." The brown crate is a thing in Shipping. The description is "An ordinary brown crate."

After examining something when the label is part of the noun:
    say "A bright red sticky label is attached to [the noun]!"

Here is the essential point: whenever we ATTACH LABEL TO something, it becomes part of that object.

Instead of tying the red sticky label to something:
    now the red sticky label is part of the second noun;
    say "You stick [the label] to [the second noun]."

And of course the label cannot be stuck to itself or to more than one thing at a time.

Before tying the label to something when the label is part of something:
    if the label is part of the second noun:
        say "[The label] is already stuck to [the second noun]." instead;
    otherwise:
        say "(first freeing the label)[line break]";
        silently try taking the label;
        if the label is part of something, stop the action.

Instead of tying the red sticky label to the label:
    say "That would ruin the label entirely."

Instead of taking the label when the label is part of something:
    now the player carries the label;
    say "You peel the label off again."

Much of the rest is just tidying to make sure that the player's commands are redirected into the right syntax.

Instead of tying something to the label:
    try tying the label to the noun.

Instead of putting the label on something:
    try tying the label to the second noun.

Instead of inserting the label into something:
    try tying the label to the second noun.

Understand the commands "stick" or "apply" as "tie".

We could have created a new "sticking" action, but to keep the example short we will use the built-in "tying" action instead, and respond to the command "stick" just as if it were "tie".

Understand "peel [something]" or "peel off [something]" as taking.

Test me with "i / put label on the black crate / look / x black / x label / get the label / apply label to brown crate / look / x brown / peel off label / stick label to label".

55. Early Childhood ★★★

This would be a one-star example if it were not for the repainting:

paste.png "Early Childhood 1"

A building block is a kind of thing. A red block, a blue block and a green block are kinds of building block.

The Nursery is a room. In the Nursery are six red blocks, four blue blocks and a green block.

Test me with "look / get red block".

But a kind cannot change during play, so this will not do. Instead, the colour will have to be a property of the block. So we might first try this:

paste.png "Early Childhood 2"

Colour is a kind of value. The colours are red, blue and green. A block is a kind of thing. A block has a colour. A block is usually blue.

The Nursery is a room. In the Nursery are six red blocks, four blue blocks and a green block.

Test me with "look / get red block".

Which is fine, so far as it goes, but the colour property is not at all visible to the player, who simply sees "eleven blocks". We thought of colour as being something outwardly apparent, but Inform does not know this. To achieve a better effect, we will need features from distant chapters. The first is an activity called "printing the name of":

paste.png "Early Childhood 3"

Colour is a kind of value. The colours are red, blue and green. A block is a kind of thing. A block has a colour. A block is usually blue. Before printing the name of a block: say "[colour] ". Before printing the plural name of a block: say "[colour] ".

The Nursery is a room. In the Nursery are six red blocks, four blue blocks and a green block.

Test me with "look / get red block".

This too, however, is unsatisfactory. The individual blocks are correctly described, but we are unable to distinguish them during play: we cannot type "take a green block", for instance. And because the blocks are indistinguishable in play, they are still massed together as "eleven blocks" in room descriptions. We need to go one step further:

paste.png "Early Childhood 4"

Colour is a kind of value. The colours are red, blue and green. A block is a kind of thing. A block has a colour. A block is usually blue. Before printing the name of a block: say "[colour] ". Before printing the plural name of a block: say "[colour] ". Understand the colour property as describing a block.

The Nursery is a room. In the Nursery are six red blocks, four blue blocks and a green block.

And now everything works nicely: the blocks are grouped by colour, and can be referred to by colour, and we can even change the colour of an individual block during play, using a bit of extra trickery from later:

Understand "paint [something] [colour]" as painting it. Painting it is an action applying to one thing and one colour. Check painting it: if the noun is not a block, say "Paints are only for blocks." instead. Carry out painting it: now the colour of the noun is the colour understood. Report painting it: say "The block is now [the colour of the noun]."

Test me with "get red block / get blue block / g / i / look / paint blue block red / i / look / paint me red".

RB §9.8. Simple Machines

The "device" kind provides for the simplest form of machine: one which is, at any given moment, switched on or switched off. Inform looks after this state, but leaves it to us to make the machine actually do something:

The air-conditioning unit is a device in the Florist's Shop. The air-conditioning is fixed in place and switched on.

Every turn when the location is the Florist's Shop:
    if the air-conditioning is switched off, say "You worry about the cut flowers in this jungle-hot air.";
    otherwise say "There is an low susurration from the air-conditioning unit."

One primary dictionary definition for a machine is "an apparatus using or applying mechanical power and having several parts", and we often use the "part of" relationship to build machinery. Control Center provides a neat way to display the component parts of a machine to the player who examines it.

One component almost always part of an electrical machine is the (literal) switch, lever or button to control whether it is switched on or off. In Model Shop ★★ just such an on/off button is automatically made part of every device.

While an electrical device has only two states, a mechanical machine might have many, and for these the best approach is to define a kind of value naming the possibilities: see Signs and Portents ★★★, where the states are the possible destinations pointed towards.

Perhaps stretching the definition of "machine", What Makes You Tick demonstrates a fishing pole which the player can put together from several pieces.

See also

Bags, Bottles, Boxes and Safes for a safe that can be dialed to different combinations

Examples

61. Control Center

It is straightforward to make a rule that anything with parts must mention all those parts during an EXAMINE command:

paste.png "Control Center"

After examining a thing when something is part of the noun:
    say "[The noun] includes [a list of things which are part of the noun]."

The Control Center is a room. "Here you are at the Control Center of the universe."

The Universe Management Computer is a fixed in place thing in the Control Center. "The Universe Management Computer sits directly before you, unguarded." The description of the Universe Management Computer is "The computer is so large that you would be unable to operate it all from one position. Alas, it does not come with a manual."

A chartreuse indicator light, an ennui meter, a golden knob settable to 15,000 positions, a toothpick dispenser, and a button labeled RESTART are part of the Universe Management Computer.

The command chair is an enterable supporter in the Control Center. It is pushable between rooms. "Because the computer is too large for you to reach all of the front panel from a standing position, there is a command chair on casters which allows you to push back and forth." The description of the command chair is "Quite ordinary, really, but for the heady rush of power that comes of sitting in it.". Some casters are part of the command chair.

Now whenever we look at any object with components, we will first see the description, then a list of parts which belong to it. The following refinement brings in elements of later chapters, but it may be worth noting: because we've written our rule as an "After examining...", anything that pre-empts the operation of the examine command will also prevent that rule from occurring. So for instance:

A hair-thick needle is part of the ennui meter.

Instead of examining the ennui meter: say "You can't be bothered."

...would not result in the needle being mentioned.

Test me with "x chair / x computer / x ennui meter"

427. What Makes You Tick

Suppose we want to let the player build a fishing pole out of three parts: a hook, a string, and a stick.

There are several things we must account for here. One is that our combination verb should be insensitive to ordering: it shouldn't matter whether the player types COMBINE STICK WITH STRING or COMBINE STRING WITH STICK.

Second, we need to make sure that our implementation handles intervening stages of assembly gracefully. The player should be able to combine string and hook first, or string and stick first, and be able to complete the assembly in either case.

Our implementation here uses a table of lists to determine which combinations of inputs should produce which result object. Because we sort our lists before comparing them, we guarantee that the player's ordering doesn't matter: COMBINE STICK WITH STRING will have the same effect as COMBINE STRING WITH STICK.

What's more, our implementation could be expanded to account for many other assemblages, if we wanted object-building to be a running theme of puzzles in our game.

paste.png "What Makes You Tick"

Understand "combine [something] with [something]" as combining it with. Combining it with is an action applying to two carried things. Understand the command "connect" as "combine".

Understand the command "attach" as something new. Understand "attach [something] to [something]" as combining it with.

The combining it with action has an object called the item built.

Setting action variables for combining something with something:
    let X be a list of objects;
    add the noun to X;
    add the second noun to X;
    sort X;
    repeat through the Table of Outcome Objects:
        let Y be the component list entry;
        sort Y;
        if X is Y:
            now the item built is the result entry.

Check combining it with:
    if the item built is nothing or the item built is not in limbo,
        say "You can't combine [the noun] and [the second noun] into anything useful." instead.

Carry out combining it with:
    move the item built to the holder of the noun;
    now the noun is nowhere;
    now the second noun is nowhere.

Report combining it with:
    say "You now have [an item built]."

Limbo is a container. Limbo contains a hookless fishing pole, a hooked line, and a complete fishing pole.

Streamside is a room. The player carries a stick, a wire hook, and a string.

Table of Outcome Objects

component list

result

{stick, string}

hookless fishing pole

{wire hook, string}

hooked line

{hooked line, stick}

complete fishing pole

{hookless fishing pole, wire hook}

complete fishing pole

Test me with "combine stick with string / i / combine pole with hook / i".

This kind of implementation makes sense if we don't intend the player to take the fishing pole apart again, or to refer to any of its component parts once it is built. For an alternate approach that does allow assembled objects to be taken apart again, see "Some Assembly Required".

57. Model Shop ★★

Suppose we're particularly mechanically-minded and would like a game in which all of our mechanical devices have buttons to turn them on and off.

paste.png "Model Shop"

An on/off button is a kind of thing.

Instead of pushing an on/off button which is part of a switched off device (called the machine):
    try switching on the machine.

Here we are making a rule about how our hypothetical buttons will interact with the machines to which they belong. Instead of pushing... is a rule that pertains to actions, and we will learn more about these in the chapter on actions. "...which is part of a switched off device" provides a specific circumstance - this is only to apply to buttons that are stuck to a machines that can be turned on or off. "(called the machine)" tells Inform that if it finds such a device, it should thereafter refer to it as "the machine." (The called syntax is explained further in the chapter on Change.)

A set of three more rules will complete our instructions about using buttons to control devices:

Instead of pushing an on/off button which is part of a switched on device (called the machine):
    try switching off the machine.

Instead of switching on an on/off button which is part of a device (called the machine):
    try switching on the machine.

Instead of switching off an on/off button which is part of a device (called the machine):
    try switching off the machine.

Then we hand out buttons with a free hand:

One on/off button is part of every device.

The Model Shop is a room. A model train is a fixed in place device in the Model Shop. A toy elephant is a device in the Model Shop.

Every turn when the model train is switched on:
    say "The model train circles your feet, blowing small puffs of steam."

Every turn when the toy elephant is switched on:
    say "The toy elephant waves its trunk at you."

Test me with "push model train's button / push elephant's button / g / switch off model train's button".

And now the game will have a model train's button and a toy elephant's button.

It may be that we want (as an added nuance) to add other names for these items. While we would want an assembly to create objects such as "Lucy's hand" and not "Lucy hand", it is entirely reasonable to want to talk about the model train button or the elephant button. We could define these additional names like so:

Understand "elephant button" or "button on elephant" as the elephant's button.

Understand "model train" or "model" or "train" as "[train]". Understand "[train] button" or "button on [train]" as the model train's button.

In the second case, we are defining [train] to mean any of the three phrases "train", "model", and "model train"; so "[train] button" will match "model train button" or "train button" or "model button" equally well. See the chapter on Understanding for more on how to create alternative phrasings for the player to use.

52. Signs and Portents ★★★

paste.png "Signs and Portents"

Seven Dials is a room. The description of Seven Dials is "There is a signpost, on which seven hands swivel and swing, freely as weathercocks. They make your present road now London, now Abingdon; now Weston-super-Mare, or now Hell."

Seven Dials contains a signpost. The signpost is scenery. Understand "sign" and "post" as the signpost.

Destination is a kind of value. The destinations are London, Abingdon, Luton, Weston-super-Mare, Runnymede, Hell, and Low Noon.

The signpost has a destination.

In order to interact with the signpost, we will need to make use of some action rules:

Instead of examining the signpost:
    say "[The signpost] currently puts you on the road to [italic type][the destination of the signpost][roman type], but it swiftly alters again.";
    now the destination of the signpost is the destination after the destination of the signpost.

Instead of turning the signpost:
    now the destination of the signpost is the destination after the destination of the signpost;
    say "With a hand's touch you turn the signpost to mark your way for [italic type][the destination of the signpost][roman type]."

Instead of going north in Seven Dials when the destination of the signpost is Hell:
    say "It is a path that goes gently ever down and down with no stumbling block or any distraction at either side; there are no bandits and no tolls.";
    end the story.

Instead of going north in Seven Dials when the destination of the signpost is Low Noon:
    say "A long road whose scenery does not change, nor anything on the horizon move but the sun. When at last you come to Noon, she hangs above your head like a hat.";
    end the story finally.

Test me with "x signpost / n / turn signpost / n / turn signpost / n / turn signpost / n / turn signpost / n".

Test more with "x signpost / n / turn signpost / n / turn signpost / n / turn signpost / n / turn signpost / turn signpost / n".

RB §9.9. Televisions and Radios

IF authors often provide clues or background information to the player by means of radio broadcasts, TV shows or video tapes because they can talk to the player without needing to listen back, or to react to what the player does. The simplest radio set, like the one in Aftershock ★★★, really only has one thing to say: which is serendipitously being broadcast just at the moment the player tunes in (regardless of when that is). The next simplest approach is to spool a broadcast on an endless loop taking several turns to play through, as in Radio Daze.

Televisions come in all shapes and sizes, and Aspect allows their shape ("aspect ratio") to be described by the player.

In Channel 1 ★★, we can also refer to the television by what it is currently showing: thus WATCH CHANNEL 4 will work if the set is indeed tuned to 4. In Channel 2 ★★★, numbered channel changing is taken further: we can now TUNE TV TO CHANNEL 3, as well. Channel 2 ★★★ is a reasonable base implementation of a television for many purposes.

Examples

66. Radio Daze

paste.png "Radio Daze" by Jon Ingold

The Living Room is a room. "A long couch, set up so you can see your wireless set. Not that you need to see it, of course."

The long couch is an enterable scenery supporter in the living room. Instead of entering the long couch when the radio was switched off, say "Better turn the radio on before you get comfortable." Report entering the couch: say "You settle yourself down to listen." instead. Instead of listening when the radio is switched on, stop the action.

The radio is a device in the living room. The radio is switched off. "[if switched on]The radio burbles on[otherwise]The radio is off[end if]." Check switching off the radio when the player is on the long couch: say "You can't reach the radio from here." instead.

Every turn when the radio is switched on:
    say "[one of]Two characters in the radio play have begun an argument[or]The argument continues[or]The play continues[stopping]: [one of]'Did not!'[or]'Did too!'[or]'Did I?'[or]'You did!'[or]'I couldn't have, Martha!'[or]'But you did, Tom!'[cycling]"

Test me with "sit on couch / turn on radio / sit on couch/ listen / g / g / g / g / g".

312. Aspect

Named properties are not the only kind that Inform is able to understand referring to an object. We can also use unit and number properties to distinguish things from one another, as here, where televisions have aspect ratios:

paste.png "Aspect"

An aspect ratio is a kind of value. 16:9 specifies an aspect ratio.

A television is a kind of device. A television has an aspect ratio. Understand the aspect ratio property as referring to a television. Understand "European standard" as 16:9.

The Office is a room.

The widescreen TV is a television in the Office. The fifties TV is a television in the Office. The widescreen TV is 16:9. The fifties TV is 4:3.

Test me with "examine european standard tv / x 16:9 tv / x 4:3 tv".

314. Channel 1 ★★

We might want to allow every television to be tuned to a channel (a number property) which the player could refer to, so that

WATCH CHANNEL 13
TURN OFF CHANNEL 4

would be directed to the appropriate television object, if any television is turned on and tuned to the correct station. We might now write:

paste.png "Channel"

A television is a kind of device. A television has a number called the channel. Understand the channel property as referring to a television. Understand "channel" as a television.

The Office is a room. The widescreen TV is a television in the Office. The fifties TV is a television in the Office.

Changing the channel of it to is an action applying to one thing and one number.

Understand "tune [something] to [number]" or "change channel of [something] to [number]" as changing the channel of it to.

Check changing the channel of something to:
    if the noun is not a television, say "[The noun] cannot be tuned to a channel." instead.

Carry out changing the channel of something to:
    now the channel of the noun is the number understood.

Report changing the channel of something to:
    say "You tune [the noun] to channel [number understood]."

Instead of examining a television:
    if the noun is switched off, say "[The noun] is currently turned off." instead;
    let the chosen channel be the channel of the noun;
    if the chosen channel is a current channel listed in the Table of Television Channels:
        choose row with current channel of the chosen channel in the Table of Television Channels;
        say "[output entry][paragraph break]";
    otherwise:
        say "Snow fills the screen of [the noun]."

Table of Television Channels

current channel

output

0

"The screen of [the noun] is completely black."

4

"A gloomy female news anchor describes the latest car bomb in Baghdad: 104 dead today, and no sign of change."

5

"A couple of contestants in spangled scarlet outfits are performing an energetic paso doble."

13

"On-screen, Ichiro is up to bat with one man on second and no outs."

Test me with "change channel of fifties tv to 4 / x channel 4 / switch on fifties / x channel 4 / switch on widescreen / tune fifties tv to 5 / x channel 5 / x fifties tv / x channel 4".

317. Channel 2 ★★★

Our previous implementation of televisions ("Channel 1") doesn't allow the player to type things like

TUNE FIFTIES TELEVISION TO CHANNEL 4

nor does it deal with player input like

TUNE TO CHANNEL 4 ON FIFTIES TELEVISION

or

TUNE TO CHANNEL 4

where no television is specified. When we are designing commands which involve two elements (here, a television and a channel number), it's usually a good idea to allow the player to specify those elements in either order, as we saw demonstrated briefly in "New commands for old grammar".

We might, therefore, want to add a few refinements: first by defining a "[channel]" token that will accept input of the forms "[number]" and "channel [number]", and second by creating some additional "Understand" lines that will accept variant versions of the player's input.

paste.png "Channel 2"

Section 1 - Televisions in General

A television is a kind of device.

A television has a number called the channel. Understand the channel property as referring to a television. Understand "channel" as a television.

Changing the channel of it to is an action applying to one thing and one number.

Understand "tune [television] to [channel]" or "change channel of [television] to [channel]" as changing the channel of it to.

Understand "tune [something] to [channel]" or "change channel of [something] to [channel]" as changing the channel of it to.

Understand "tune to [channel] on [television]" or "change to [channel] on [television]" as changing the channel of it to (with nouns reversed).

Understand "tune to [channel] on [something]" or "change to [channel] on [something]" as changing the channel of it to (with nouns reversed).

Understand "[number]" or "channel [number]" as "[channel]".

Check changing the channel of something to:
    if the noun is not a television, say "[The noun] cannot be tuned to a channel." instead.

Carry out changing the channel of something to:
    now the channel of the noun is the number understood.

Report changing the channel of something to:
    say "You tune [the noun] to channel [number understood]."

Instead of examining a television:
    if the noun is switched off, say "[The noun] is currently turned off." instead;
    let the chosen channel be the channel of the noun;
    if the chosen channel is a current channel listed in the Table of Television Channels:
        choose row with current channel of the chosen channel in the Table of Television Channels;
        say "[output entry][paragraph break]";
    otherwise:
        say "Snow fills the screen of [the noun]."

Table of Television Channels

current channel

output

0

"The screen of [the noun] is completely black."

Section 2 - The Scenario

The Office is a room.

The widescreen TV is a television in the Office. The fifties TV is a television in the Office.

And we add the scenario-specific content to our Table of Television Channels; in the case of channel 13, we provide for a changing sequence of events using text variations.

Table of Television Channels (continued)

current channel

output

4

"A gloomy female news anchor describes the latest car bomb in Baghdad: 104 dead today, and no sign of change."

5

"A couple of contestants in spangled scarlet outfits are performing an energetic paso doble."

13

"[one of]On-screen, Ichiro is up to bat with one man on second and no outs.[or]Ichiro has singled to first and the other man is on third.[or]The next batter is in the middle of flying out.[or]Everything looks rosy until the men in black pull off a double-play and retire the side.[or]The channel has cut to a commercial.[stopping]"

Test me with "test one / test two".

Test one with "change channel of fifties tv to 4 / x channel 4 / switch on fifties / x channel 4 / switch on widescreen / tune fifties tv to channel 5 / x channel 5 / x fifties tv / x channel 4".

Test two with "tune to channel 13 / widescreen / tune channel 13 to channel 5 / tune channel 5 to channel 3 / widescreen / x channel 3".

336. Aftershock ★★★

The built-in behavior of Inform is to print a line after a device is examined, saying whether the item is on or off. This is often inappropriate, and we could simply turn off that behavior in general by instructing Inform to ignore the "examine described devices rule" (see the chapter on rulebooks).

Perhaps, though, we would like continue to have a short passage about the action of any switched on device; we'd just like a little more control over what it says from time to time. And in that case, we might change the rule to give a new activity control over that portion of the description:

paste.png "Aftershock"

Section 1 - Showing actions

Showing action of something is an activity.

Rule for showing action of something (called item):
    if the item is switched on, say "[The item] is switched on.";
    otherwise say "[The item] is switched off."

Borrowing from the rulebooks chapter, we can replace the standard "examine described devices" rule with something that uses this activity.

The new described devices rule is listed instead of the examine devices rule in the carry out examining rules.

This is the new described devices rule:
    if the noun is a device:
        carry out the showing action activity with the noun;
        now examine text printed is true.

Thus far we have essentially replicated the original behavior, but we've made it possible to write specialized behavior for devices, and to invoke that behavior in other places:

Report switching on something:
    say "You flip a switch. ";
    carry out the showing action activity with the noun instead.

This might be useful for an electric lamp kind:

Section 2 - Electric Lamps

An electric lamp is a kind of device.

Rule for showing action of an electric lamp (called item):
    if the item is switched on, say "[The item] is lit[if the number of visible lit things is greater than 1], competing with [the list of visible lit things which are not the item][end if].";
    otherwise say "[The item] is dark."

Carry out switching on an electric lamp: now the noun is lit. Carry out switching off an electric lamp: now the noun is unlit.

Section 2 - The Scenario

The time of day is 3:47 AM. When play begins, now the right hand status line is "[time of day]".

The Downstairs Hallway is a dark room. "The only room in the house with no furniture and almost nothing on the walls. At times like this you always notice the crack in the plaster, originating near the light fixture and running almost all the way to the wall."

A plastic jug of filtered water is in the Downstairs Hallway. The description is "Five gallons, not that that will last you very long, hot as it has been lately."

The crack is scenery in the Hallway. The description is "No, the ceiling isn't going to fall on you today."

The light fixture is an electric lamp in the Hallway. It is switched on, lit, and scenery. The description is "A plain globe of frosted glass containing the light bulb. Nothing special, and you never think about it except when, as now, you are forced to spend hours in this room."

The flashlight is an electric lamp carried by the player. The description is "A shiny red flashlight." The portable radio is a device carried by the player. The description is "A small battery-operated radio which you received for free with your subscription to US News & World Report. It has served you well through many earthquakes past."

And with our activity, we can override the flashlight's electric lamp behavior with new behavior:

Rule for showing action of the flashlight:
    if the flashlight is switched on, say "A strong, narrow beam of light shines from the flashlight.";
    otherwise say "It is currently switched off."

...or give special actions for the radio:

Rule for showing action of the radio:
    if the radio is switched on, say "Through the static, you pick up pieces of discussion: a 6.7 on the Richter scale, epicenter... something about Topanga... but it crackles out again.";
    otherwise say "The radio is silent. You're saving the batteries."

Instead of listening in the presence of the switched on radio:
    carry out the showing action activity with the radio instead.

Test me with "examine light / switch light off / switch flashlight on / switch radio on / examine radio / examine flashlight".

RB §9.10. Telephones

Telephones are much harder to achieve than televisions and in some ways as difficult to make convincing as a human character is - though of course there are corners which can be cut: we could have the reception drop off, or the other party hang up in a misunderstanding, and so on.

A single telephone line is tricky enough to provide that one might just as well have a general solution providing a whole network. Four Cheeses ★★★ demonstrates a system where we can dial either people or numbers: CALL JANET ON TELEPHONE, or CALL 7103, for instance.

While Four Cheeses ★★★ provides only four-digit phone numbers, like internal company extensions, Alias ★★★ shows how to manage US-style seven digit numbers.

Finally, we might occasionally want the player to be able to address a microphone or telephone receiver directly when the identity of the person on the other end is unknown, in the form TELL MICROPHONE ABOUT CRIME. Ordinarily Inform will disallow this because we're not allowed to talk to inanimate objects, but the extension Inanimate Listeners provides more options.

See also

Saying Complicated Things for more approaches to conversation

Examples

226. Four Cheeses ★★★

paste.png "Four Cheeses"

Section 1 - Telephones and Connections

A telephone is a kind of thing. Understand "phone" as a telephone.

Understand "call [any telephone] on [something]" as calling it on. Understand "call [any telephone]" as calling it on. Understand the commands "dial" or "phone" or "telephone" as "call". Understand "call [any known person]" as calling it by name on.

Connection relates one thing to another (called the other party).

The verb to reach means the connection relation.

Calling it on is an action applying to one visible thing and one thing.

Check calling it on:
    if the second noun is not a telephone, say "[The second noun] is unlikely to be much use in that respect." instead;
    if the second noun is the noun, say "You get a busy signal." instead.

Carry out calling it on:
    if a person (called the listener) can see the noun, now the player reaches the listener.

Because we've said that connection is a reciprocal, one-to-one relationship, Inform will do the rest of the bookkeeping: if (for instance) we telephone someone else, the first connection will be broken automatically.

Report calling it on:
    say "'Hello?' says [the other party of the player]."

To avoid annoyance, we should also let the player use CALL #### as well as CALL #### ON TELEPHONE. A rule from the chapter on Activities comes in handy here:

Rule for supplying a missing second noun while calling something on:
    assign a phone.

To assign a phone:
    if the player can touch a telephone (called the current phone):
        say "(on [the current phone])[line break]";
        now the second noun is the current phone;
    otherwise:
        say "You don't have a phone handy."

Things might be a little more complicated if we had cell phones that could be moved around, but for right now the player can only touch a maximum of one phone at a time.

Suppose we further want to allow the player to call people up by name, but only if they've already been encountered or are familiar to the player for some reason.

A person can be known or unknown.

Understand "call [any known person]" as calling it by name on.

Understand "call [any known person] on [something]" as calling it by name on.

Rule for supplying a missing second noun while calling something by name on:
    assign a phone.

Calling it by name on is an action applying to one visible thing and one thing.

Check calling it by name on:
    if the noun is in the location, say "[The noun] is right here." instead.

Carry out calling it by name on:
    if the noun can touch a telephone (called the link), try calling the link on the second noun;
    otherwise say "You can't reach [the noun]." instead.

Before calling something on something when the player reaches someone:
    say "(first ending your conversation with [the other party of the player])[command clarification break]";
    end current conversation.

Understand "hang up [something]" as hanging up.

Hanging up is an action applying to one thing.

Check hanging up:
    if the noun is not a telephone, say "You can't hang up [the noun]." instead;
    if the player does not reach someone, say "You're not on the line with anyone." instead.

Carry out hanging up:
    now the player does not reach anyone.

Report hanging up:
    say "You put down [the noun], cutting the connection."

Before going somewhere when the player reaches someone:
    say "(first hanging up on [the other party of the player])[command clarification break]";
    end current conversation.

And finally we want to make sure that calling random other numbers produces a sensible result:

Understand "call [text]" as misdialling. Misdialling is an action applying to one topic. Carry out misdialling: say "The phone rings and rings but no one answers."

Understand "call 911" or "call 999" or "call police" or "call fire department" as a mistake ("After strict warnings, you've given up making prank calls to emergency services.").

Before misdialling when the player reaches someone:
    say "(first ending your conversation with [the other party of the player])[command clarification break]";
    end current conversation.

To end current conversation:
    let the current phone be a random telephone which can be touched by the player;
    silently try hanging up the current phone.

After deciding the scope of the player while the player reaches someone:
    place the other party of the player in scope, but not its contents.

A note about this scope addition: the player can refer to the other party whenever he has the other person on the phone. He can't, however, see or refer to anything that person might be holding or wearing, thanks to the "but not its contents" option.

Furthermore, the player can't actually do anything to that person that requires touching. That's because of the reaching inside rules, which govern whether the player can reach through intervening barriers such as rooms. (See the Advanced Actions chapter for more about changing reachability.) There are two things we might want to be careful about, though.

First, we should specifically disallow the player from looking at the person on the other end of the line. Since sight doesn't require touching, the reaching inside rules will not be consulted about a command such as EXAMINE BOSS or LOOK UNDER BOSS. We can, however, intervene in such cases using the visibility rules, which are consulted for any actions that "require light" (including EXAMINE and LOOK UNDER). Here again we borrow some options from the Advanced Actions chapter:

To decide whether acting through the line:
    if the noun is something and the location of the noun is not the location of the player:
        yes;
    if the second noun is something and the location of the second noun is not the location of the player:
        yes;
    no.

Visibility rule when acting through the line:
    there is insufficient light.

Rule for printing a refusal to act in the dark when acting through the line:
    say "You're not on a video phone, so you can only hear." instead.

Second, though the existing reaching inside rules are adequate to stop us from touching the person on the other end of the line, the response that's currently printed is a bit generic: it just says "You can't reach into [the room containing the person]." Let's add our own custom reply, instead:

A rule for reaching inside a room (called destination):
    if the other party of the player is enclosed by the destination:
        say "Though you're on the line with [the other party of the player], you can't physically reach to [the destination].";
        deny access.

Section 2 - Conversation over the Phone, In General

This portion supplies a simple method of conversation; but we could substitute some completely different conversation system if appropriate. The effect of the telephones is that we are allowed to talk to characters in distant locations under certain circumstances, after which the usual conversation rules apply.

Instead of listening to a telephone when the player reaches someone:
    say "You can hear [the other party of the player] breathing."

Before listening to someone when the player cannot touch the noun:
    say "[The noun] is waiting for you to carry on the conversation." instead.

A person has a table name called chatter.

Before telling someone about something:
    try asking the noun about it instead.

Before answering someone that something:
    say "Best to confine your conversation to questions and answers." instead.

Before asking someone about something:
    if the topic understood is a topic listed in the chatter of the noun, say "[reply entry][paragraph break]" instead;
    otherwise say "[The noun] does not reply." instead.

Section 3 - The Scenario

The Guard House is a room. "Here you spend all your nights. Bullet-proof windows offer a panoramic view of serene cliffs, palm trees, and a moonlit ocean. Occasionally someone is foolish enough to try a cliff ascent or even an attack by helicopter, but lately things have been pretty quiet.

The mansion is up the hill behind you, security lights ablaze."

The grey telephone is a telephone in the Guard House. Understand "6885" as the grey telephone. "Before you is a grey telephone. In black marker someone has written on it: MAIN OFFICE 2802."

Before going a direction in the Guard House, say "And leave your post? The boss would have you flayed. No kidding." instead.

In a game where the player could walk around, we would of course want to add a before rule so that he automatically hung up any phone he was using before leaving the room.

The Main Office is a room. The boss is a known woman in the Main Office. A telephone called the red telephone is in the Main Office. Understand "2802" as the red telephone.

The Guild is a room. The ninja is an unknown man in the Guild. A telephone called the black telephone is in the Guild. Understand "4431" as the black telephone.

Potter's Pizza is a room. The pizza delivery boy is a known man in Pizza. A telephone called the saucy telephone is in Pizza. Understand "8885" as the saucy telephone.

The chatter of the boss is the Table of Boss Conversation. The chatter of the delivery boy is the Table of Pizza Conversation. The chatter of the ninja is the Table of Ninja Conversation.

After calling the red telephone on something for the first time:
    say "'Yes?' asks the boss. Her voice is especially husky this evening. Maybe that night of passion isn't so far off after all."

Table of Boss Conversation

topic

reply

"love/passion/tonight/night" or "night of passion"

"'...Sorry, what?' she asks. 'I wasn't listening.' Oh. Maybe she'd go for some pizza, though."

"pizza"

"'I'd love some. No pepperoni, though,' she says, sounding dreamy. Yes, this is definitely time for a call to your old friend, the pizza boy."

"imminent ninja attack"

"'Don't worry about it,' says the boss crisply. 'I have everything under control.'"

Table of Pizza Conversation

topic

reply

"pizza"

"'Pepperoni special tonight!' he says proudly."

"pepperoni"

"'Pepperoni is included free on ALL our pizzas,' he says proudly."

"no pepperoni"

"'Well, I don't see why you'd want that,' replies the boy sniffily. 'It's free!'"

"jalapeno"

"'Sorry, we're out of jalapenos this evening. There was a run on them.'"

"sausage"

"'Sausage, sure, we can do you sausage.'"

"canadian bacon"

"'There's currently an embargo on Canadian pig products.'"

"cheese"

"'We use four kinds,' says the boy, then lowers his voice confidentially. 'Actually, two of them are the same. Nobody ever counts. The stringy one, the one that comes in dollops and the orangey one. You know.'"

"pineapple"

"'We could put pineapple on there, sure,' says the delivery boy, in a tone that lets you know his opinion of people who order fruit-based pizzas."

"pineapple and garlic"

"'What kind of crazy combination is that?' demands the delivery boy, finally losing all self-control."

"delivery"

"'Well, I don't know,' says the boy in a worried voice. 'Last time I came there were attack dogs. And ninjas.'"

"massive gratuity"

"'There's no use in a big tip you don't live to spend,' says the delivery boy quite firmly."

Table of Ninja Conversation

topic

reply

"imminent attack"

"'Yes, still on for tonight,' confirms the voice at the other end of the line."

"pizza delivery boy"

"The voice, in tones of velvet, indicates that it cannot guarantee the safety of any delivery persons whomsoever."

Test me with "call 2802 / examine boss / ask boss about night of passion / ask boss about pizza / listen to telephone / call delivery boy on telephone / ask boy about cheese / tell boy about no pepperoni / ask boy about delivery / tell boy about massive gratuity / attack boy".

...and it more or less writes itself from there.

253. Alias ★★★

Seven-digit telephone numbers are too long for Inform to handle when compiling to the Z-Machine, but they will work under Glulx. To have this example succeed, make sure that you have selected the Glulx option in your settings menu.

paste.png "Alias"

A telephone is a kind of thing. Understand "phone" or "telephone" as a telephone.

A phone number is a kind of value. 999-9999 specifies a phone number.

Now we borrow some techniques from the Understanding chapter to set up dialing actions:

Understand "dial [phone number] on [telephone]" as dialing it on. Understand "dial [phone number] on [something]" as dialing it on.

Understand the commands "phone" or "telephone" or "call" as "dial".

Understand "call [text]" or "phone [text]" or "dial [text]" or "telephone [text]" as a mistake ("That's not a number you know.").

Dialing it on is an action applying to one phone number and one thing.

Report dialing it on:
    say "You dial [the phone number understood]."

This much is enough to let us dial telephone numbers and have Inform report that we've done so; it doesn't actually provide a telephone system such that we could reach and converse with other characters (but see the other telephone examples in the recipe book for more on how one might do that).

We'll set up a little political espionage scenario from which our player can make calls:

The Senator's Junior Suite is a room. "The Senator appears, unfortunately, to have very precise habits: little in the room has been moved from its usual place; the trash can is empty; the bed has been remade[if the blue paper is unexamined]. There may in fact be nothing to find here[end if]."

The bed is an enterable scenery supporter in the Junior Suite.

The player is wearing a housekeeping uniform and a brunette wig. The player carries a telephone called a Nokia.

Borrowing again from the chapter on Understanding, we might arrange things so that the player knows and can call a few standard numbers with such syntax as CALL HOME:

Understand "home" as 555-9200.

And what if we'd like to have the player learn some phone numbers during the game?

A thing can be examined or unexamined. Carry out examining something: now the noun is examined.

Understand "Stephen" as 555-2513 when the blue paper is examined.

This will understand CALL STEPHEN once the paper is examined; before that, the player will just get the "That's not a number you know" response that Inform uses for all attempts to call unknown names.

We'd better plant this paper for the player to find:

The blue paper is in the drawer. The description of the blue paper is "It reads: 'Call Stephen - 555-2513'."

The drawer is part of the dresser. It is closed and openable. The dresser is in The Senator's Junior Suite. The lamp is on the dresser. The description of the dresser is "The single drawer is [if the drawer is open]open[otherwise]shut[end if]."

Test me with "dial 555-9999 / call home on the telephone / phone the president / call stephen / open drawer / read paper / call stephen / put phone in drawer / close drawer / call stephen".

RB §9.11. Clocks and Scientific Instruments

The simplest form of clock is a wrist watch. Here is a choice of analogue or digital:

The player wears a wrist watch. The description of the wrist watch is "It is [the time of day in words]."

The player wears a digital watch. The description of the digital watch is "It is [the time of day]."

Better clocks would allow us also to set the time, and to stop and start them: see Tom's Midnight Garden.

Scientific instruments provide sharper versions of our own senses. In the case of vision, they allow us to see closer up, or further away. It's a convention of IF that people can normally see only the current location, that is, they cannot see from one location into another. The boundary of the current room is like a horizon, even out of doors (though it's true that there are ways to disguise that with a continuous outdoor landscape). Ginger Beer ★★ provides a telescope able to see into other rooms.

Witnessed 2 provides a meter which measures how close a ghost is to the player.

See also

Continuous Spaces and The Outdoors for more on seeing into adjacent locations
Heat for infrared goggles

Examples

180. Witnessed 2

paste.png "Witnessed"

The player carries a device called a Trifield Natural EMF Meter. The description of the Meter is "This cost a pretty penny off the internet, but it's worth it: according to the website it has been programmed by PhD physicists to ignore manmade sources of fields and to respond only to paranormal EMF changes.

It also features an optional Tone Alarm, which can be turned on to indicate when readings spike. If the alarm is off, the meter just reads out the magnetic and electric field levels on a scale from 0-100 microteslas, or 0-1000 V/m.

Since both fields are important, you keep the meter set to SUM mode. The meter has its own optional backlighting, so that you can see the reading even if your flashlight is off. Currently it is reading at [meter setting]." A Tone Alarm is part of the Meter. It is a device. The description of the Tone Alarm is "The Tone Alarm will make a noise, if the EMF picks up a spike."

To decide what number is meter setting:
    if the meter is switched off, decide on 0;
    if a ghost is touchable, decide on 35;
    if a ghost is visible, decide on 12;
    decide on 0.

After switching on the meter:
    say "You turn on the meter. The needle steadies at [meter setting]."

Every turn: if the meter setting is greater than 10 and the Tone Alarm is switched on, say "[The Tone Alarm] shrieks."

Thirtieth Street Station is a room. "A huge, high, rectangular room with coffered ceilings, which looks grand but mostly makes you feel lonely and small. There are long benches in rows down the middle of the room, and an information desk with the train times, and a series of ticket windows, none of which matters very much at the moment."

The benches are an enterable supporter. They are scenery in the Station. The information desk is scenery in the Station. Some ticket windows are scenery in the Station. Instead of examining scenery in the Station: say "You're fairly sure that whatever is going on here has nothing to do with [the noun]." Understand "window" as ticket windows.

The mural is fixed in place in Thirtieth Street. "At the north side of the station is a particularly pointless and empty annex to the main room. It is dominated by a huge relief of sorts, and this is what you remember." Understand "metal" or "relief" or "huge" as the mural. The description of the mural is "It is both stylized and confusing, but you think it might be supposed to represent the various tasks and occupations of Philadelphia's population. The portions closer to the ground look as though they have recently been subjected to a light dusting of talcum powder. No unusual prints are evident."

The wind chimes are fixed in place in Thirtieth Street. "Carefully attached to the wall with a piece of duct tape and a hook is a light-weight set of wind chimes. Someone else has been here before you, it seems." The description is "Several of your friends use wind chimes as a sort of ghost alarm, since ghosts sometimes cause very localized movements of air when there is no natural breeze."

A ghost is a kind of person. The pale figure is a ghost.

At 9:03 AM: move the pale figure to the location; say "You shiver with some sort of presence."

Test me with "turn on alarm / turn on meter / z / z / z / x figure".

298. Tom's Midnight Garden

Time can also be understood as a token, and the time parsed will be recorded as "the time understood". So therefore, if we wish for clocks which may be set:

paste.png "Tom's Midnight Garden"

A clock is a kind of device. A clock has a time called the current time. A clock can be analog or digital. The current time of a clock is usually 9:01 AM. The description of a clock is "It shows the time to be [if analog]about [the current time to the nearest five minutes in words][otherwise][the current time][end if]."

Understand "set [clock] to [time]" as setting it by time. Setting it by time is an action applying to one thing and one time.

Instead of setting a clock to something:
    say "[The noun] can be set only to a time of day, such as 8:00 AM, or midnight."

Carry out setting a clock by time:
    now the current time of the noun is the time understood.

Report setting a clock by time:
    say "You set [the noun] to [time understood]."

Every turn:
    repeat with item running through switched on clocks:
        now the current time of the item is one minute after the current time of the item.

The Hall is a room. The grandfather clock is a fixed in place analog clock in the Hall. The travel clock is a switched on digital clock in the Hall. When play begins: now the right hand status line is "[time of day]".

Test me with "examine grandfather clock / set it to midnight / switch it on / wait / wait / wait / examine it / set travel clock to 4:12 / examine it".

365. Ginger Beer ★★

Suppose we want to have a pair of linked lenses so that the player can look into one of them and see things which occur in room containing the other lense.

We begin simply with a bit of environment for the player to wander around:

paste.png "Ginger Beer"

The Ginger Beer Factory is a room. "In the center of the room is an enormous pot filled with crushed ginger, which seems to be bubbling slightly on its own. The fumes are overwhelming."

The pot is scenery in the Ginger Beer Factory. The description of the pot is "Cast iron." In the pot is a bubbling brew.

Instead of smelling the Ginger Beer Factory: try smelling the brew.

Instead of smelling the brew, say "You blink back tears."

The Storeroom is south of the Ginger Beer Factory. "The walls here are lined with a prodigious number of small, rounded bottles, each with a screw top and a smiling pirate on the label."

The Clippings Room is west of the Ginger Beer Factory. "A clean room lined with steel tables, for preparing ingredients."

Some steel tables are a supporter in the Clippings Room. They are scenery. The description is "They are roughly the size and height of laboratory worksurfaces."

The quantity of dandelion is on the steel tables. The description is "Horrible common weed."

The wooden box is on the steel tables. It is openable and closed. The description is "A large wooden box with a lid, used for ingredient storage. There is a label on the lid."

The label is part of the box. The description is "BURDOCK: the root beaten with a little salt and laid on the place suddenly easeth the pain thereof, and helpeth those that are bit by a mad dog:... the seed being drunk in wine 40 days together doth wonderfully help the sciatica: the leaves bruised with the white of an egg and applied to any place burnt with fire, taketh out the fire, gives sudden ease and heals it up afterwards.... The root may be preserved with sugar for consumption, stone and the lax."

The quantity of burdock is in the box. The description is "It looks like a kind of thistle."

Some bottles are in the Storeroom. They are scenery. The description is "They are smaller than the average bottle, because more potent." Instead of taking the bottles, say "Take one away and the whole lineup will cascade to the floor."

Now for the lenses themselves:

A lense is a kind of thing.

The large end of the telescope is a lense in the Ginger Beer Factory. "There is a large glass lense propped against the wall, in which are reflected all the contents of the room." Understand "glass" or "lense" as the large end.

The small end of the telescope is a lense in the Storeroom. "There is a small glass lense sitting on the floor. Due to some curious effect of the optics, it appears to be giving a view of somewhere else entirely." Understand "glass" or "lense" as the small end. The description is "A gleaming lense about the size of a pound coin."

Here is the critical bit, which needs to be somewhat flexible, since the large end of the telescope could in theory be left anywhere in the game (and should still work).

After deciding the scope of the player while the small end is carried by the player:
    let there be the holder of the large end;
    place there in scope.

Before searching the small end when the small end is not carried by the player:
    say "(first picking up [the small end] and holding it to your eye)";
    silently try taking the small end.

Instead of searching the small end when the player is not carrying the small end:
    say "It's too hard to look through the small end from a distance."

Instead of searching the large end,
    say "You see only your own reflection."

We also want to make sure that the player who looks through the small lense does not see the large lense listed among the contents of the other location:

Definition: a thing is recognizable if it is not a lense.

Instead of searching the small end:
    let the far side be the holder of the large end of the telescope;
    say "You peer into the little lense and through it see, in [the far side], [the list of recognizable things in the far side]."

Test me with "examine lense / south / examine lense / look through lense / north / look through small lense".

And we're done.

RB §9.12. Cameras and Recording Devices

Recording what is going on, for later playing back or examination, is difficult because the range of situations is very complex. Exactly how much information should we store when we make a recording, and will this require problematically large tables? Will it be difficult even to do at all?

The usual approach is to record only basic details of events or situations. In If It Hadn't Been For... the tape recorder preserves only a few different sounds - footsteps, creaking, rustling - rather than capturing exactly the sound of every action taking place in earshot. In Claims Adjustment ★★, we can take up to 36 Polaroid-style photographs, but each is described only by saying what it is a photo of. Thus we can have a photograph of a vase, or even a photograph of a photograph of a vase (because that too is a thing), but not a photograph of a still life in which several items have been gathered together by the player. That would ordinarily require too much storage.

A similar trick, though involving impromptu sculpture rather than photography, can be found in Originals. (The artist magically "manifests" these models rather than sculpting the conventional way in order to avoid the nuisance of carrying around raw materials - wax maquettes and so forth - which would clutter up the example.)

Text, of course, can store arbitrary descriptions. Mirror, Mirror provides a perfect visual recorder: it remembers a room description exactly as the player saw it at the time.

Actor's Studio ★★ provides a video camera that records and time stamps all actions performed in its presence while it is set to record.

See also

Telephones for ways to speak to inanimate objects, which might be appropriate when, say, tape-recording a confession

Examples

273. If It Hadn't Been For...

We start out by giving ourselves a capacious recording device:

paste.png "If It Hadn't Been For..."

The digital recorder is a device. The description is "A noise-activated recorder, which time-stamps each recording segment. It has space for about 60 short recordings."

Every turn:
    if the digital recorder is switched on and the number of blank rows in the Table of Recorded Content is 0, now the recorder is switched off.

Table of Recorded Content

time stamp

sound

a time

some text

with 60 blank rows.

And most of what follows is attaching sounds to various events. (We could have made noises associated with all the actions, but for simplicity we stuck to a few.)

The thing to note here is that the recording happens as part of Carry out, not as part of Report, so sounds will be recorded even when they are the result of non-player action when the player is not even in the room.

Carry out opening something in the presence of the switched on recorder:
    record "A creaking noise, as of something being opened."

Carry out someone opening something when the switched on recorder can see the noun:
    record "A creaking noise, as of something being opened."

Carry out closing something in the presence of the switched on recorder:
    record "A creaking followed by a slam."

Carry out someone closing something in the presence of the switched on recorder:
    record "A creaking followed by a slam."

Carry out someone going to a room (called destination) in the presence of the switched on recorder:
    if the destination is the holder of the recorder, record "Footsteps, growing louder.";
    otherwise record "Footsteps, fading out."

Carry out going to a room (called destination) in the presence of the switched on recorder:
    if the destination is the holder of the recorder, record "Footsteps, growing louder.";
    otherwise record "Footsteps, fading out."

Carry out someone eating something in the presence of the switched on recorder:
    record "Loud uncouth chewing sounds."

Carry out eating something in the presence of the switched on recorder:
    record "Distant muffled chewing sounds."

To record (noise - some text):
    if the number of blank rows in the Table of Recorded Content is 0, rule succeeds;
    choose a blank row in the Table of Recorded Content;
    now time stamp entry is the time of day;
    now sound entry is noise.

Understand "play [something]" as listening.

Instead of listening to the recorder:
    if the number of filled rows in the Table of Recorded Content is 0, say "The recorder remains blank." instead;
    repeat through the Table of Recorded Content:
        say "[line break][time stamp entry]: [sound entry]";
    say paragraph break.

The Haunted House is a room. The squeaky cupboard is an openable enterable closed fixed in place container in the House. The ghost is a man in the cupboard. The Lawn is outside from the Haunted House.

Instead of opening the closed cupboard when the ghost is in the cupboard: say "The cupboard stubbornly refuses to open."

Every turn when the player is not in the House:
    if the ghost is in the cupboard:
        try the ghost exiting;
    otherwise if the cupboard is open:
        try the ghost closing the cupboard.

Before someone exiting when the person asked is in a closed container (called the trap):
    try the person asked opening the trap.

Before someone entering a closed container: try the person asked opening the noun.

Before going to the House when the House contains the ghost:
    try the ghost entering the cupboard;
    try the ghost closing the cupboard.

The player carries the recorder, chips, and a sandwich. The sandwich is edible. The chips are edible.

Carry out someone eating the chips in the presence of the switched on recorder: record "An incredible racket of a packet being opened." Carry out eating the chips in the presence of the switched on recorder: record "An incredible racket of a packet being opened."

Test me with "open cupboard / drop recorder / switch it on / eat chips / out / wait / wait / wait / in / switch recorder off / play recorder".

Now we're at liberty to record evidence of the ghost getting out of the cupboard and getting back in, while we ourselves stand about on the lawn.

368. Originals

We rely here on the understanding-by-relations rules we've already learned, but there is an additional trick: we want to make sure that if the player types "original" or "actual", this word will not be taken to refer to the thing modeled:

paste.png "Originals"

A model is a kind of thing. 100 models are in the model-repository.

Appearance relates one thing to various models. The verb to be shown by means the appearance relation.

Indication relates a model (called X) to a thing (called Y) when Y is shown by X and Y is suitable.

Understand "actual" or "original" as "[actual]". Understand "[actual]" as something when the item described is not a model.

Definition: a thing is suitable:
    if the player's command includes "[actual]", no;
    yes.

Understand "[something related by indication]" as a model.

After printing the name of a model (called target): say " [random thing shown by the target]"

Now our duplication command -- for the sake of simplicity, we'll suppose that in this scenario the player is duplicating objects by magic rather than creating them out of physical materials or supplies:

Understand "duplicate [something]" as duplicating. Duplicating is an action applying to one visible thing.

The duplicating action has an object called the selected model.

Setting action variables for duplicating:
    let N be a random model in the model-repository;
    now the selected model is N.

Check duplicating:
    if the selected model is nothing, say "You're out of power." instead.

Carry out duplicating:
    now the noun is shown by the selected model;
    move the selected model to the player.

Report duplicating:
    say "You concentrate and manifest [a selected model]."

Now, the challenge is that we want to print the word "actual" before printing the name of an object, but only during disambiguation questions and only when we are not printing the name of the object as part of a model-name! (If we are not careful about the latter point, we will get responses such as "Which do you mean, the model actual deer or the actual deer?" which of course defeats the whole purpose.

The way around this is to remember that activities stack: we're printing the name of the deer while printing the name of a model that involves the deer. So if we set a flag while printing the name of a model, we can control the way the deer's name prints during the transaction. (We could use our ...while clause to specify while not printing the name of a model, except that we're already using it for "while asking which do you mean", and these do not stack.) So:

The virtual-context is a truth state that varies. The virtual-context is false.

Before printing the name of a model:
    now virtual-context is true.

After printing the name of a model:
    now virtual-context is false.

Before printing the name of something (called target) while asking which do you mean:
    if the target is not a model and virtual-context is false:
        say "actual ".

Forest is a room. It contains a deer and a daisy. The deer is an animal.

Test me with "duplicate deer / x model deer / x deer model / drop deer / x deer / actual / x deer / model".

416. Mirror, Mirror

paste.png "Mirror, Mirror"

The Sorcerer's Workshop is a room. "The sorcerer's den is a dusty, whispering place. A grandfather clock with skeletal hands reads [the time of day in words]. The floorboards are stained where that porridge just wouldn't come out."

The Apprentice's Pantry is east of the Workshop. "This is where the aproned apprentice traditionally makes the camomile tea, cleans out the jackdaw cages and furtively examines purloined artefacts."

When play begins: erase the mirror.

The player carries a magic mirror. The magic mirror has a text called the mirror vision.

To erase the mirror: now mirror vision of the mirror is "The mirror is polished clean, and has no impression upon it."

To say current room description: try looking.
To expose the mirror:
    say "The mirror shines momentarily with a dazzling light.[paragraph break]";
    now mirror vision of the mirror is the substituted form of "The hazy image in the mirror preserves a past sight:[line break][current room description]All is distorted and yet living, as though the past and present are coterminous in the mirror."

Understand "hold up [something preferably held]" or "hold [something preferably held] up" as holding aloft. Holding aloft is an action applying to one carried thing. Report holding aloft: say "You hold [the noun] aloft."

Instead of rubbing the mirror: erase the mirror; try examining the mirror. Instead of holding aloft the mirror: expose the mirror.

The description of the mirror is "[mirror vision of the mirror]".

Test me with "look / examine mirror / hold up mirror / z / look / x mirror / rub mirror / east / hold mirror up / west / x mirror".

221. Actor's Studio ★★

Here we construct a video camera to track and play back actions:

paste.png "The Actor's Studio"

Section 1 - The Video Camera

The video camera is a thing carried by the player.

Table of Videotape

recorded action

time stamp

waiting

9:00 AM

with 25 blank rows.

Mode is a kind of value. The modes are idle, recording, and playing back. The video camera has a mode. The video camera is idle.

Understand "play back" as playing back. Instead of switching on the camera, try tuning the camera to recording. Instead of switching off the camera, try tuning the camera to idle.

The description of the video camera is "It is currently [mode]; its available settings are idle, recording, and playing back."

Understand "set [camera] to [a mode]" as tuning it to. Tuning it to is an action applying to one thing and one mode.

Instead of setting the camera to something:
    say "The available settings are idle, recording, and playing back."

Check tuning it to:
    if the noun is not the camera, say "Only the video camera can be set to [the mode understood]." instead.

Carry out tuning it to:
    now the mode of the noun is the mode understood.

Report tuning it to:
    say "You set [the noun] to [mode understood]."

After an actor doing something when the video camera is recording:
    if the current action is tuning the video camera to recording, make no decision;
    if the number of blank rows in the Table of Videotape is greater than zero:
        choose a blank row in the Table of Videotape;
        now the recorded action entry is the current action;
        now the time stamp entry is the time of day;
    otherwise:
        now the video camera is idle;
        say "The video camera runs out of recording memory and switches off.";
    continue the action.

Every turn when the video camera is playing back:
    say "On the camera screen, you see [run paragraph on]";
    let starting playback be false;
    repeat through the Table of Videotape:
        if the recorded action entry is not waiting:
            now starting playback is true;
            say "[line break] -- [if the actor part of the recorded action entry is the player]you [end if][the recorded action entry], time stamped at [time stamp entry]";
            blank out the whole row;
    if starting playback is false, say "only static.";
    otherwise say paragraph break.

Section 2 - The Scenario

The Actor's Studio is a room. Lucas is a man in the Actor's Studio. Persuasion rule: persuasion succeeds.

The Studio contains an edible thing called a croissant.

Test me with "set camera to recording / x lucas / lucas, take inventory / lucas, eat croissant / set camera to playing back / z".

Notice that both Lucas' implied taking action (picking up the croissant) and his eating action are recorded on the same move.

322. Claims Adjustment ★★

We start by creating a camera and a photograph object. As usual when we want to have a kind of object that can be dispensed in bulk, we start off with a bunch of identical instances of the object out of play (in this case, kept in an out-of-play container called "film roll"); we can then move them into play and give them characteristics when they're needed.

Each photograph can depict exactly one thing -- we're assuming that the player is not a landscape photographer here -- so we create a relation to indicate what is shown by each photograph. We'll then use that relation to determine how photographs are described, named, and parsed:

paste.png "Claims Adjustment"

A photograph is a kind of thing. 36 photographs are in the film roll.

Appearance relates one thing to various photographs. The verb to be shown by means the appearance relation.

The description of a photograph is usually "It shows [a random thing which is shown by the item described]."

Understand "of [something related by reversed appearance]" as a photograph.

This allows the player to refer to any photograph by its subject: useful if we have a large number of them.

Now we create an action to let the player use the camera and generate these photograph objects:

The player carries a cheap instant camera.

Understand "photograph [something] with [camera]" as photographing. Understand "photograph [something] with [something preferably held]" as photographing. Photographing is an action applying to one visible thing and one carried thing, requiring light.

The photographing action has an object called the selected film.

Setting action variables for photographing:
    let N be a random photograph in the film roll;
    now the selected film is N.

Check photographing:
    if the second noun is not the camera, say "You need a camera for that purpose." instead.

Check photographing:
    if the noun is the camera, say "Sadly impossible." instead.

Check photographing:
    if the selected film is nothing, say "You're out of film." instead.

Carry out photographing:
    now the noun is shown by the selected film;
    move the selected film to the player.

Report photographing:
    say "Your camera instantly spits out [a selected film]."

Now we use two activities from the Activities chapter to describe the photographs to the player more elegantly:

After printing the name of a photograph (called target):
    say " of [a random thing which is shown by the target]".

After printing the plural name of a photograph (called target):
    let N be the holder of the target;
    say " of [a list of things which are shown by photographs which are held by N]";
    if the number of things which are shown by photographs which are held by N is greater than one, say " (variously)".

And finally we provide a brief scenario to give the player something to take pictures of:

The Treasure Room is a room. "Despite the fancy name, this is no more than a closet -- albeit a closet with its own special circuit on the house alarm."

The Treasure Room contains a small Degas, a Ming vase, and a collection of South African krugerrands. The player is carrying insurance forms, a first-class stamp, and a security envelope.

The description of the forms is "Completely filled out in black ink in block letters: now all you need to do is attach photographic evidence of the objects you wish to insure."

Test me with "photograph degas / i / photograph degas / i / x photograph of degas / photograph me / x photograph of me / i / photograph vase / photograph camera / photograph collection / g / i / test more".

Test more with "x photograph of collection / x photograph of krugerrands / x photograph of collection of south african krugerrands / photograph photograph of degas / x photograph of photograph of degas".