RB §10.1. Gases

Inform normally assumes that everything is solid. It has no built-in support for gases or liquids, because they have so many different behaviours. For instance, is the important thing about gas that it diffuses, or that we breathe it, or that it mixes with other gases to react, or that it sometimes obscures vision? The answer depends on what we are trying to write, and for this reason Inform leaves it up to us.

Gases are easier to deal with than liquids, because they tend to be everywhere in their location at once (unlike a liquid which might form a pool on the floor) and because they diffuse and mix by themselves (rather than being carried around or brought into contact with each other by the player). On the other hand, unlike liquids, gases are compressible: they can be present at low or high pressures, that is, in low or high concentrations.

The simplest approach is the one in Only You... ★★★, where rooms are either filled with smoke or else smoke-free. Smoke gradually fills through the map, obscuring vision: no attempt is made to conserve the total quantity of smoke, as we assume that some fire is churning it out continuously to replace what diffuses away.

Lethal Concentration 1 ★★ and 2 simulate a gas diffusing through a three-dimensional maze of rooms, and becoming dangerous above certain concentrations. There is just one possible gas, and it is modelled by giving each room a number which represents the concentration (in parts per million). This enables us to conserve the total amount of gas, or to have it released or captured by sources and sinks of given capacity.

This could be extended by giving each room similar concentration levels for other gases, and providing for the diffusion rule to notice when different gases come into contact; or by giving a concentration (and also, for realism, a volume) to each closed container, applying rules for capturing and releasing gases as containers are opened and closed.

Examples

255. Lethal Concentration 1 ★★

paste.png "Lethal Concentration"

A concentration is a kind of value. 200.9ppm specifies concentration. 200.9 ppm specifies concentration.

A room has a concentration called current concentration. A room has a concentration called former concentration.

Probability inverse is a number that varies. [This is expressed as an inverse of the actual probability of diffusion from one room to another, to avoid error.] Probability inverse is 20. [That is, any given molecule of gas has a 5% chance of leaving by a given doorway at any given minute. Probability inverse should never drop below 10, the maximum number of exits from the room.]

Every turn:
    follow the diffusion rules.

The diffusion rules are a rulebook.

A diffusion rule (this is the gas movement rule):
    repeat with space running through rooms:
        let sum be 0.0 ppm;
        repeat with way running through directions:
            let second space be the room way from the space;
            if second space is a room:
                let difference be the former concentration of the second space minus the former concentration of the space;
                increase sum by the difference;
        let sum be sum divided by probability inverse;
        now current concentration of the space is the former concentration of the space plus the sum.

A technical note: it would be possible to write "repeat with space running through rooms... repeat with second space running through rooms adjacent to the space" instead, but in practice this loops through all the rooms * all the rooms again * all the directions (to determine adjacency). Phrasing the loop this way omits the second multiplier. For a map of 25 rooms, this means that the loop runs 25 times faster than it would otherwise, and of course for a larger map the effect would be even more dramatic.

A diffusion rule (this is the resetting concentration rule):
    repeat with space running through rooms:
        now the former concentration of the space is the current concentration of the space.

The last diffusion rule (this is the lethal dosage rule):
    if the current concentration of the location is greater than LC50:
        say "The concentration in the air overpowers you...";
        end the story;
    otherwise:
        if the current concentration of the location is greater than TLV-STEL:
            say "You feel extremely uncomfortable in this environment."

Instead of doing something when the current concentration of the location is greater than TLV-STEL:
    if going, continue the action;
    say "You can't work in this environment: your eyes and nose sting and it hurts to breathe."

And, for testing purposes, a square grid of rooms:

Room 1A is west of Room 1B. Room 1B is west of Room 1C. Room 1C is west of Room 1D. Room 1D is west of Room 1E.

Room 2A is south of room 1A and west of Room 2B. Room 2B is west of Room 2C and south of Room 1B. Room 2C is west of Room 2D and south of Room 1C. Room 2D is west of Room 2E and south of Room 1D. Room 2E is south of Room 1E.

Room 3A is south of room 2A and west of Room 3B. Room 3B is west of Room 3C and south of Room 2B. Room 3C is west of Room 3D and south of Room 2C. Room 3D is west of Room 3E and south of Room 2D. Room 3E is south of Room 2E.

Room 4A is south of room 3A and west of Room 4B. Room 4B is west of Room 4C and south of Room 3B. Room 4C is west of Room 4D and south of Room 3C. Room 4D is west of Room 4E and south of Room 3D. Room 4E is south of Room 3E.

Room 5A is south of room 4A and west of Room 5B. Room 5B is west of Room 5C and south of Room 4B. Room 5C is west of Room 5D and south of Room 4C. Room 5D is west of Room 5E and south of Room 4D. Room 5E is south of Room 4E.

The former concentration of room 3C is 800.0 ppm.

For variety of testing, here is another room set-up, this time with some corridors and walls within; uncommenting it, and commenting out the connected grid, will let us explore what would happen in alternative cases, to prove to ourselves that the model works consistently.

[Room 1A is west of Room 1B. Room 1B is west of Room 1C. Room 1C is west of Room 1D. Room 1D is west of Room 1E.

Room 2A is west of Room 2B. Room 2B is west of Room 2C. Room 2C is west of Room 2D. Room 2D is west of Room 2E. Room 2E is south of Room 1E.

Room 3A is south of room 2A and west of Room 3B. Room 3B is west of Room 3C. Room 3C is west of Room 3D. Room 3D is west of Room 3E.

Room 4A is west of Room 4B. Room 4B is west of Room 4C. Room 4C is west of Room 4D. Room 4D is west of Room 4E. Room 4E is south of Room 3E.

Room 5A is south of room 4A and west of Room 5B. Room 5B is west of Room 5C and south of Room 4B. Room 5C is west of Room 5D and south of Room 4C. Room 5D is west of Room 5E and south of Room 4D. Room 5E is south of Room 4E.]

For the sake at least of seeing what's going on in the example, let's also provide the player with the means to view the gas diffusion graphically:

The status grid is a device carried by the player. The status grid is switched on.

Every turn:
    try examining the grid.

Instead of examining the status grid:
    say "[fixed letter spacing][bar][line break]";
    say "|[state of room 1A]|[state of room 1B]|[state of room 1C]|[state of room 1D]|[state of room 1E]|[line break]";
    say "[bar][line break]";
    say "|[state of room 2A]|[state of room 2B]|[state of room 2C]|[state of room 2D]|[state of room 2E]|[line break]";
    say "[bar][line break]";
    say "|[state of room 3A]|[state of room 3B]|[state of room 3C]|[state of room 3D]|[state of room 3E]|[line break]";
    say "[bar][line break]";
    say "|[state of room 4A]|[state of room 4B]|[state of room 4C]|[state of room 4D]|[state of room 4E]|[line break]";
    say "[bar][line break]";
    say "|[state of room 5A]|[state of room 5B]|[state of room 5C]|[state of room 5D]|[state of room 5E]|[line break]";
    say "[bar][variable letter spacing][line break]".

To say bar:
    say "----------------------------------------------".

TLV is a concentration that varies. TLV is 30.0ppm. [Long-term exposure maximum, safe for 8 hours a day.]

TLV-STEL is a concentration that varies. TLV-STEL is 50.0ppm. [Short-term exposure maximum, safe for fifteen minutes max.]

TLV-C is a concentration that varies. TLV-C is 150.0ppm. [Absolute exposure ceiling.]

LC50 is a concentration that varies. LC50 is 300.0ppm. [Concentration at which 50 percent of test subjects die of exposure, usually expressed in terms of time and body weight; in our LC50 these are factored in for the player's weight for one minute.]

The values set for these would depend on the type of poisonous gas in question; we'd want to adjust appropriately.

To say state of (space - a room):
    if the space is the location, say bold type;
    if current concentration of space is less than 10.0ppm, say " ";
    if current concentration of space is less than 100.0ppm, say " ";
    say current concentration of space;
    say roman type.

Now, in theory we might also want to account for sources and sinks, items that either inject poisonous gas into the environment or remove it again. For simplicity, we will assume that these contributions can also be calculated in ppm and that the total number of inert and poisonous gas molecules in a room never changes (so if poison gas molecules are added, an equal number of inert molecules are removed). If room pressure were able to change, our model would have to be improved, so let us assume for now that that never happens. We want this sink/source business to calculate before any other portion of the diffusion rulebook, so set it as a first diffusion rule.

A gas source is a kind of thing. A gas source has a concentration called the contribution. The contribution of a gas source is usually 30.0ppm.

Room 2B contains a gas source called a spigot. The contribution of the spigot is 50.0ppm. Room 5A contains a gas source.

A gas sink is a kind of thing. A gas sink has a concentration called the contribution. The contribution of a gas sink is usually 30.0ppm.

Room 5E contains a gas sink called a fan. The contribution of the fan is 80.0ppm.

The first diffusion rule (this is the sources and sinks rule):
    follow the sources rule;
    follow the sinks rule.

This is the sinks rule:
    repeat with item running through gas sinks:
        let space be the location of the item;
        decrease the former concentration of the space by the contribution of the item;
        if the former concentration of the space is less than 0.0ppm, now the former concentration of the space is 0.0ppm.

This is the sources rule:
    repeat with second item running through gas sources:
        let space be the location of the second item;
        increase the former concentration of the space by the contribution of the second item;
        if the former concentration of the space is less than 0.0ppm, now the former concentration of the space is 0.0ppm.

Test me with "z / z / z / z / z / z / z / z".

74. Only You... ★★★

Suppose we want to have smoke that spreads from room to room, gradually filling the entire map with a clogging smoke. Having it spread every single turn would make for a pretty rapid diffusion, so we temper this by having it spread only on even-numbered turns, instead. Conveniently, Inform by default already knows about even and odd numbers, so we can write:

paste.png "Only You..."

Section 1 - The Procedure

Every turn when the turn count is even:
    if every room is smoky, make no decision;
    let previously smoky be whether or not the location is smoky;
    repeat with area running through smoky rooms:
        now every room which is adjacent to the area is smoky;
    if previously smoky is false and the location is smoky:
        say "[The location] is filling rapidly with smoke."

A room can be smoky or unsmoky.

Some air is a backdrop. Air is everywhere. Instead of doing something other than examining or smelling to air: say "It's just air." Understand "smoke" as the air when the location is smoky.

Instead of examining the air in a smoky room: say "A thick layer of smoke lies just under the ceiling."

Instead of smelling the air in a smoky room: say "Agh, acrid." Instead of smelling a smoky room: try smelling the air.

After looking in a smoky room: say "A thick layer of smoke has gathered under the ceiling."

Section 2 - The Scenario

The Guide Lodge is a room. "A very spacious room capable of containing several hundred girls while they eat, talk, or do crafts. It is constructed in a not-unappealing rustic style, with floor-to-ceiling windows overlooking the lake below, and a fieldstone hearth at the center." The Guide Lodge is smoky.

The Kitchen is north of the Guide Lodge. "Multiple eight-burner ranges, ovens, and a walk-in refrigerator: you know the sort of thing."

The Industrial Pantry is east of the Kitchen. "Awe-inspiring quantities of food line every shelf, from the three-gallon tub of mayonnaise to the 50-pound tub of rice. Perhaps the most astonishing item is a bag of marshmallows big enough to double as a futon."

The player is in the Pantry.

The Hallway is west of the Guide Lodge. The description of the Hallway is "A perpetually-crammed hallway which has to handle the overflow line for the toilets." A singed sign is fixed in place in the Hallway. The description of the sign is "Where the edge of the sign has not been burnt, the legible words are '...Can Prevent Forest Fires'."

The Toilets are north of the Hallway. "Always in full use, at least when the 12-to-15s are here."

The Coat Closet is south of the Hallway. "Muddy boots may not be worn inside the lodge; instead, about 250 pair are piled here, along with their owners' damp parkas and umbrellas."

The Craft Supply Room is west of the Hallway. "A holding-depot for jugs of white glue and popsicle sticks."

Test me with "x smoke / z / z / z / z / x smoke / look".

257. Lethal Concentration 2 ★★★

This is a slight variation on the previous gas diffusion example: the main difference is that gas preferentially moves towards lower rooms, and will gradually settle in the bottom floor. We do this by calculating the probability of movement separately for each pair of rooms.

paste.png "Lethal Concentration"

A concentration is a kind of value. 200.9ppm specifies concentration. 200.9 ppm specifies concentration.

A room has a concentration called current concentration. A room has a concentration called former concentration.

To decide what number is the probability inverse between (space - a room) and (second space - a room):
    let guess be 20;
    let way be the best route from space to second space;
    if way is up, let guess be 50;
    if way is down, let guess be 10;
    if the guess is less than 10, decide on 10;
    decide on guess.

If we wanted, we could introduce other concerns into the calculation here: open and closed doors, windows between rooms, rooms that are outdoors vs. those that are indoors, and so on. The possibilities are numerous, so we will stick with the simple principle that our poison gas sinks.

Every turn:
    follow the diffusion rules.

The diffusion rules are a rulebook.

A diffusion rule (this is the gas movement rule):
    repeat with space running through rooms:
        let sum be 0.0 ppm;
        repeat with way running through directions:
            let second space be the room way from the space;
            if second space is a room:
                let incoming be the former concentration of the second space divided by the probability inverse between second space and space;
                let outgoing be the former concentration of the space divided by the probability inverse between space and second space;
                let difference be incoming minus outgoing;
                increase sum by the difference;
        now current concentration of the space is the former concentration of the space plus the sum.

A diffusion rule (this is the resetting concentration rule):
    repeat with space running through rooms:
        now the former concentration of the space is the current concentration of the space.

The last diffusion rule (this is the lethal dosage rule):
    if the current concentration of the location is greater than LC50:
        say "The concentration in the air overpowers you...";
        end the story;
    otherwise:
        if the current concentration of the location is greater than TLV-STEL:
            say "You feel extremely uncomfortable in this environment."

Instead of doing something when the current concentration of the location is greater than TLV-STEL:
    if going, continue the action;
    say "You can't work in this environment: your eyes and nose sting and it hurts to breathe."

Room 1A is west of Room 1B. Room 1B is west of Room 1C. Room 1C is west of Room 1D. Room 1D is west of Room 1E.

Room 2A is west of Room 2B and below room 1A. Room 2B is west of Room 2C and below Room 1B. Room 2C is west of Room 2D and below Room 1C. Room 2D is west of Room 2E and below Room 1D. Room 2E is south of Room 1E and below Room 1E.

The former concentration of Room 1C is 800.0 ppm.

The status grid is a device carried by the player. The status grid is switched on.

And just for fun, this time we'll make the grid prettier, too; but this will work only on the Z-machine setting, not Glulx.

Every turn:
    try examining the grid.

    Instead of examining the status grid:
    say "[unicode box drawings light down and right][top bar][unicode box drawings light down and left][line break]";
    say "[unicode box drawings light vertical]";
    say "[state of room 1A][state of room 1B][state of room 1C][state of room 1D][state of room 1E] upstairs[line break]";
    say "[unicode box drawings light vertical and right][middle bar][unicode box drawings light vertical and left][line break]";
    say "[unicode box drawings light vertical]";
    say "[state of room 2A][state of room 2B][state of room 2C][state of room 2D][state of room 2E] downstairs[line break]";
    say "[unicode box drawings light up and right][bottom bar][unicode box drawings light up and left][variable letter spacing][line break]"

Include Unicode Character Names by Graham Nelson.

To say top bar:
    repeat with N running from 1 to 9:
        if the remainder after dividing N by 2 is 0, say "[unicode box drawings light down and horizontal]";
        otherwise say "[unicode box drawings light horizontal]".

To say middle bar:
    repeat with N running from 1 to 9:
        if the remainder after dividing N by 2 is 0, say "[unicode box drawings light vertical and horizontal]";
        otherwise say "[unicode box drawings light triple dash horizontal]".

To say bottom bar:
    repeat with N running from 1 to 9:
        if the remainder after dividing N by 2 is 0, say "[unicode box drawings light up and horizontal]";
        otherwise say "[unicode box drawings light horizontal]".

TLV is a concentration that varies. TLV is 30.0ppm. [Long-term exposure maximum, safe for 8 hours a day.]

TLV-STEL is a concentration that varies. TLV-STEL is 50.0ppm. [Short-term exposure maximum, safe for fifteen minutes max.]

TLV-C is a concentration that varies. TLV-C is 150.0ppm. [Absolute exposure ceiling.]

LC50 is a concentration that varies. LC50 is 300.0ppm. [Concentration at which 50 percent of test subjects die of exposure, usually expressed in terms of time and body weight; in our LC50 these are factored in for the player's weight for one minute.]

Include Basic Screen Effects by Emily Short.

To say state of (space - a room):
    if the current concentration of space is less than TLV, say blue letters;
    if the current concentration of space is TLV, say blue letters;
    if the current concentration of space is greater than TLV, say green letters;
    if the current concentration of space is greater than TLV-STEL, say yellow letters;
    if the current concentration of space is greater than TLV-C, say red letters;
    say "[unicode square with diagonal crosshatch fill]";
    say default letters;
    say "[unicode box drawings light vertical]".

Test me with "z / z / z / z / z / z / z / z".

RB §10.2. Liquids

Liquids are notoriously difficult to simulate well. A fully thorough approach consumes endless storage and can be very finicky to write and keep realistic. It is essential to decide what aspect of a liquid's behaviour is actually needed in a given story, and to simulate only that. For instance, if we only need a little chemistry, where a player can add (say) water to salt and make a solution, we do not want to fool around with calculating quantities or concentrations: what's important is that "some water" (amount unspecified) combines with "some salt" to produce "some salty water". We should no more calculate precisely here than we would work out where all the furniture is to the nearest inch. Good advice for handling liquids is to simulate the least amount of realism possible, but no less.

Sometimes all we want is a down-in-one drink: we needn't simulate the actual liquid, just the bottle it comes in, and all we need is to handle the "drinking" action. See Beverage Service, and also 3 AM ★★★, where carbonated drinks can be shaken - again simulating the vessel, not the liquid.

Some elementary biochemistry in Xylan ★★ is done simply by... well, the point is that two different liquids are represented by single things each, and a chemical reaction simply switches one for the other.

In Frizz ★★★, we allow any container to be filled with water (only) and we simulate what happens to any solid objects also inside: some waterproof, some not. Flotation provides a well (always full of water), with rules to determine whether things dropped into it should sink or float.

Next we move up to quantitative approaches, where we remember not just whether a liquid is present, but how much of it. In its simplest form, we could have a drinking vessel from which we draw in sips, so that it can be full, half-empty or empty: see Thirst.

The example with the best compromise between simulation quality and complexity is Lemonade ★★★. Here we provide a kind of container called a "fluid container", not just a single cup, and each such vessel has a given "fluid capacity". Each holds only a single liquid at a time (so no mixtures) and can be empty or full to any level (rounded off to the nearest 0.1 fl oz). We can fill one vessel from another (unless it would make a mixture). But liquids leaving these vessels must be consumed - drunk or poured away without trace: we cannot make pools on the floor, or carry liquids in our cupped hands. There is no object representing "lemonade": there are only fluid containers, but which can be called LEMONADE if that is what they now contain.

Savannah ★★★ is a light elaboration of Lemonade, showing how liquids might be poured on other objects, as for instance to extinguish a fire.

Noisy Cricket ★★★ extends Lemonade ★★★ to allow for mixing, though then the number of different possible mixtures is so large that complexity increases greatly. Lakeside Living ★★★ extends Lemonade ★★★ differently to add a "liquid source" kind, a form of fluid container which has infinite fluid capacity and is scenery - ideal for a lake, river or spring.

See also

Bags, Bottles, Boxes and Safes for stoppered bottles which could also be used for carrying liquids around in
Heat for keeping liquids warm in insulated containers

Examples

118. Thirst

paste.png "Thirst"

The player carries a waterskin. The waterskin can be full, partly drained, or empty. The waterskin is full. Understand "water" as the waterskin.

Instead of drinking the waterskin when the waterskin is empty:
    say "There is no water left."

Instead of drinking the waterskin: if the waterskin is partly drained, now the waterskin is empty; if the waterskin is full, now the waterskin is partly drained; say "You drink a long draught."

After printing the name of the waterskin: say " ([waterskin condition])"

Campsite is a room. "It is solid night now, and the stars have come out. Unfamiliar stars. On the other side of the valley -- a valley round-bottomed but shallow, like a soup bowl -- burn other campfires, most likely bandits. Their voices do not carry, but the smoke rises and obscures the starlight over that way."

A sleepsack is an enterable container in the Campsite. "Your sleepsack is laid out in a pocket of sandy soil and coarse grass."

The sandy soil, the stars, the distant campfires, and the coarse grass are scenery in the Campsite. Understand "smoke" as the campfires. Instead of listening in the presence of your campfire: say "All you hear are the reassuring snaps and cracks of the sticks in your fire." Understand "campfires" or "fires" as the distant campfires.

Your campfire is scenery in the Campsite. Instead of pushing, pulling, turning, tasting, or touching your campfire, say "You would burn yourself." Understand "fire" as your campfire. The description of your campfire is "A reassuring protection against wild animals and cold."

The description of the stars is "You invent constellations for them. The slingshot. The scroll. The heart (upside down)."

Instead of going nowhere when the player is in Campsite:
    say "Now is not the time for wandering, alone in the dark. Better to keep here[if your campfire is visible], by the fire[end if]."

Singing is an action applying to nothing. Understand "sing" as singing.

Instead of singing:
    say "You sing, deep and low, a song from home. It is a good night for singing and the song raises your spirits."

Test me with "i / drink water / i / drink water / i".

123. Beverage Service

Some kinds of game objects -- food, for instance -- can only sensibly be used once, and should then be destroyed. The EAT command already implements this, but suppose we also had a category of drinkable potions:

paste.png "Beverage Service"

A potion is a kind of thing. The sparkly blue potion is a potion carried by the player.

Level 3 is a room.

Instead of drinking a potion (called the drink):
    now the drink is nowhere;
    say "You quaff [the drink]. It goes down beautifully."

Test me with "drink sparkly / i".

403. Flotation

Here we want a rulebook to determine whether objects float or sink, so we create an object-based rulebook for the purpose. The more specific rules here, pertaining to corks and to inflated things, will be consulted first; then, as a default, the general flotation rule.

We also want a switch that can turn flotation off at will. The rule about the big switch will be observed before the others because the when... clause makes it more specific than the other rules in the flotation rulebook.

If we wanted, we could also put these rules into a rulebook in an explicit order, overriding Inform's automatic sorting by specificity.

paste.png "Flotation"

The Pumping House is a room.

A well is a fixed in place container in the Pumping House.

Instead of examining the well:
    say "[if something is in the well]On the surface of the water you can see [a list of things in the well][otherwise]There is nothing on the surface of the water, nor can you see into the depths[end if]."

The well bottom is a container.

The cork, the rubber ring and a lead ingot are in the Pumping House.

A big switch is a fixed in place device in the Pumping House. "A big switch labelled 'MAKE EVERYTHING SINK' is mounted on one wall[if switched on]. It crackles with electricity[otherwise]. It is currently switched off and silent[end if]."

A thing can be inflated or uninflated. A thing is usually uninflated. Before printing the name of an inflated thing: say "inflated ".

The rubber ring is inflated.

The flotation rules are an object-based rulebook.

A flotation rule for the cork: rule succeeds.
A flotation rule for an inflated thing: rule succeeds.
A flotation rule when the big switch is switched on: rule fails.

After inserting something into the well:
    follow the flotation rules for the noun;
    if the rule succeeded:
        say "[The noun] bobs on the surface.";
    otherwise:
        move the noun to the well bottom;
        say "[The noun] sinks out of sight."

A thing can be sinking, rising, or static. A thing is usually static.

Definition: a thing is wet:
    if it is in the well, yes;
    if it is in the well bottom, yes;
    no.

Every turn:
    now every thing is static;
    repeat with item running through wet things:
        follow the flotation rules for the item;
        if the rule failed and the item is in the well, now the item is sinking;
        if the rule succeeded and the item is in the well bottom, now the item is rising;
    now every rising thing is in the well;
    now every sinking thing is in the well bottom;
    if something is rising, say "[The list of rising things] rise[if the number of rising things is 1]s[end if] to the surface of the well.";
    if something is sinking, say "[The list of sinking things] sink[if the number of sinking things is 1]s[end if] out of sight."

And finally a few description rules to make things look prettier:

Rule for writing a paragraph about the well when the well contains something:
    say "The chief feature of the room is a concrete-sided well in which there float[if the number of things in the well is 1]s[end if] [a list of things in the well]."

Rule for writing a paragraph about the well:
    say "The chief feature of the room is a concrete-sided well full of water."

As we recall from the chapter on activities, "writing a paragraph about..." is an activity; activities are themselves structured as sets of object-based rulebooks. The activity "writing a paragraph about" uses three object-based rulebooks (before writing..., for writing..., after writing...). We could have made a flotation activity as well, but in general it is overkill to make an activity to make success/failure decisions. For that purpose an object-based rulebook is sufficient.

Test me with "get all / put cork in well / put ring in well / put ingot in well / x well / get cork / get ring / switch switch on / put cork in well / put ring in well / x well / switch switch off / switch switch on".

288. Xylan ★★

If we wanted to define a brand new verb that did affect a specific object, we might begin like this:

paste.png "Xylan"

Understand "hydrolyze [something]" as hydrolyzing. Hydrolyzing is an action applying to one thing.

Carry out hydrolyzing:
    say "[The noun] cannot be hydrolyzed."

Instead of hydrolyzing the xylan:
    move the xylose to the holder of the xylan;
    now the xylan is nowhere;
    say "At once the xylan becomes xylose."

Plant Cell Wall is a room.

There is a xylose sample. The xylan sample is a thing in Plant Cell Wall. The description of the xylan is "A polysaccharide. Totally useless. If only you had some xylose, instead!" The description of the xylose is "Awesome!"

Test me with "x xylan / hydrolyze xylan / x xylose".

Of course, how our players will ever solve this problem is another question (especially if their biology and chemistry are both rusty). When adding entirely new commands to a game, it is often a good idea to provide as many ways of phrasing the command as possible; to drop hints about the correct phrasing within the game's text; or even to tell the player about the expanded command list in some documentation or help at the beginning of the game. So for instance we might also add

Understand "break down [something] with water" or "break [something] down with water" as hydrolyzing.

And these lines will also provide syntax for our new command, without interfering with the previous syntax. It's also good to anticipate alternative (British or American) spellings. People's typing habits are hard to overcome, even if they know you are spelling the word the other way. It is probably best not to annoy them unduly. So:

Understand "hydrolyse [something]" as hydrolyzing.

Then some text in-game might offer a clue, subtle or (since this is an example) blunt:

Instead of examining the player, say "You're a drop of water, which means that you can break down certain chemicals!"

Understand "break down [something]" or "break [something] down" as hydrolyzing.

And finally, we could try adding instructions explicitly:

Understand "help" or "hint" or "hints" or "instructions" or "info" or "about" as asking for help. Asking for help is an action out of world. Carry out asking for help: say "The following commands are understood, in addition to the standard ones: EVAPORATE, FREEZE, HYDROLYZE, SUBLIME..."

Test more with "help / x me / break down xylan"

...though of course in fact these other commands won't be available until we define them, too.

This last approach, defining all the extra commands up front, is especially useful if these commands are very technical or unusual; if they are needed early in the game, before you've a chance to educate the player; or if they are not suggested by any in-game objects. A player who encounters a tool with an obvious use, such as a hairbrush, will likely think of trying to BRUSH things with it. It's harder to rely on his guessing actions that are both outside the range of usual commands and unrelated to any of the visible props, however.

192. 3 AM ★★★

paste.png "3 AM"

Understand "shake [something preferably held]" as shaking.

Shaking is an action applying to one carried thing.

Carry out shaking:
    say "Nothing results of your shaking [the noun]."

Instead of shaking a closed container when something is in the noun:
    say "Something rattles inside [the noun]."

Instead of shaking a closed transparent container when something is in the noun:
    say "Inside [the noun] there are banging noises produced by [the list of things contained by the noun]."

Instead of shaking an open container which contains something:
    say "[The list of things contained by the noun] might fly out."

The Wawa is a room. "A convenience store, if you like to call it that, vending the usual assortment of chips, donuts, soda, and beer. There is something of a line at the sandwich counter."

The box of enrobed cakes is in the Wawa. "A box of Tastykake Enrobed Cakes has fallen off its shelf." The description is "'Enrobed Cakes' is a fancy term for 'strange sponge-like baked good, covered in a thin shell of waxy chocolate'. They are addictive, but not in a way that lets you respect yourself in the morning." The box is a closed openable container. In the box is a cake.

Instead of opening the box, say "The Wawa clerks frown on the consumption of unpurchased foodstuffs."

The can of root beer is a closed openable container carried by the player. The can of root beer is either agitated or calm.

Because the can of root beer should have some reactions to having been shaken later in the game, we need to borrow a few ideas from the chapter on Time:

Instead of shaking the can of root beer:
    the can calms down in five turns from now;
    say "You give the can a good hard shake.";
    now the can is agitated.

Instead of listening to the can: say "It sounds [if agitated]fizzy[otherwise]calm[end if]!"

At the time when the can calms down:
    now the can is calm.

The sticky mess is fixed in place. "There is a sticky mess on the ground."

Instead of opening the agitated can of root beer:
    now the can of root beer is nowhere;
    now the sticky mess is in the location;
    say "You open the can and fizzing sweet soda goes absolutely everywhere."

Instead of opening the calm can of root beer when the can has been agitated:
    now the can of root beer is nowhere;
    say "The root beer is disappointingly flat. That's what you get for shaking it up!"

Test me with "get box / shake box / open box / shake box / listen to can / shake can / listen to can / wait / wait / wait / wait / wait / listen to can / open can".

193. Frizz ★★★

Suppose we have some items that get wet in contact with other damp things; in particular, if we touch anything wet while wearing a pair of gloves, the gloves too get damp. This requires that we be systematic about detecting all cases where contact occurs. So:

paste.png "Frizz"

A thing can be waterproof or porous. A container is usually waterproof. An animal is usually waterproof.

A thing can be sodden or dry.

A container can be waterfilled or empty.

Before printing the name of a sodden thing: say "sodden ". Understand the sodden property as describing a thing.

The player wears a pair of woolly gloves. Instead of wearing a sodden thing: say "You dubiously contemplate [the noun], and decide it's best to wear dry clothing."

Every turn:
    follow the liquid distribution rules.

The liquid distribution rules is a rulebook.

A liquid distribution rule:
    repeat with item running through containers:
        if the item is open and the item is empty and the item is in a waterfilled container:
            now the item is waterfilled;
            if the player can see the item, say "[The item] fills up with water, of course.".

A liquid distribution rule:
    repeat with item running through things in a waterfilled container:
        if the item is porous and the item is dry:
            if the player can see the item, say "[The item] soaks through.";
            now the item is sodden.

A liquid distribution rule:
    repeat with item running through sodden things in the airing cupboard:
        if the item is not The Last Man, now the item is dry.

The last liquid distribution rule:
    if the player carries a dry copy of The Last Man, end the story finally.

Instead of examining a waterfilled container:
    say "[The noun] is full of water[if the noun contains something visible]; it also contains [the list of things in the noun][end if]."

Instead of examining a container:
    say "Dry inside[if the noun contains something visible], and containing [a list of things in the noun]."

A book is a kind of thing. Instead of examining a sodden book, say "[The noun] is too soaked to read, thanks to someone's carelessness." Understand "book" as a book.

The copy of The Last Man is a book. The description of The Last Man is "Mary Shelley's very own original copy, loaned to you under the strictest of agreements[if the pond encloses the copy]. How it came to be in its present position is a long story, and not important at the moment: the critical thing is not to blame oneself - who could have anticipated the cricket bat, anyway? - but to fix it immediately, before anything worse occurs[end if]." The The Last Man is in the ziploc bag. The ziploc bag is waterproof and empty. It is openable, transparent, and closed.

The Back Garden is a room. The Back Garden contains a pond. The pond is a waterfilled container. In the pond is the ziploc bag. A carp is in the pond. The carp is an animal. Instead of taking the carp, say "You're not fast enough."

Rule for writing a paragraph about the pond:
    if the pond encloses the Last Man:
        say "It is a beautiful day just at the end of spring and beginning of summer. The sun shines, the trees blossom, the world conspires in Edenic cheerfulness. You can take in none of it. Your eye is on [the Last Man].";
    otherwise:
        say "The pond[if something is in the pond] (containing [the list of things in the pond])[end if] remains a figure of menace in an otherwise lushly verdant landscape."

Before printing the name of the Last Man when the Last Man is enclosed by the Pond: if the Last Man is dry, say "delicate, valuable ".

After printing the name of something (called the target) while writing a paragraph about something:
    if the Last Man is enclosed by the Pond:
        if the target is in something (called the parent), say " - which is in [the parent]".

The Kitchen is west of the Back Garden. "Not in any sense your province: Mrs Peaswell gets agitated if anyone besides herself so much as boils a kettle. In general it is best to sneak through, disturbing as little as possible and preserving the cosy domestic fiction that academics cannot cook.

The nearby stairwell leads up to the second floor."

The Stairwell is above the Kitchen. "Halfway up and halfway down." The airing cupboard is a container in the Stairwell. "An airing cupboard here contains the heating system, and is the ideal place for restoring wet items to a dry state." The airing cupboard is fixed in place.

Now: whenever the player definitely touches something, we want to follow certain rules about the transfer of liquid. These rules need to come after an action's check rules (to make sure the action really occurs) and before the carry out rules (so that nothing has moved or changed yet). So we'll borrow from the chapter on rulebooks to create a whole new stage to the action, occurring between the check and the carry out phases:

The post-check rules are a rulebook.

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

The post-check stage rule is listed before the carry out stage rule in the specific action-processing rules.

A post-check rule (this is the dry glove rule):
    if we get wet:
        if the player wears the gloves and the gloves are dry:
            now the gloves are sodden;
            say "(soaking your gloves in the process)";
    continue the action.

A post-check rule (this is the wet glove rule):
    if the player wears the sodden gloves:
        if the The Last Man must be touched and the Last Man is not sodden:
            say "(soaking the parched pages of The Last Man with the rude touch of your sodden gloves)";
            now the The Last Man is sodden;
        continue the action.

Before doing something when the player does not wear the gloves:
    if The Last Man must be touched:
        if The Last Man is dry, say "[The The Last Man] is too precious to endanger when you are not wearing gloves." instead;
        otherwise say "You hesitate instinctively, then recollect that you can hardly harm [The The Last Man] any more than it has already been harmed...".

To decide whether we get wet:
    if the noun is not a thing, no;
    if the noun dampens us, yes;
    if the second noun is not a thing, no;
    if the second noun dampens us, yes;
    no.

To decide whether (item - a thing) dampens us:
    if the item is not liquiferous, no;
    if item must be touched, yes;
    no.

To decide whether (item - a thing) must be touched:
    if the item is the noun and the action requires a touchable noun, yes;
    if the item is the second noun and the action requires a touchable second noun, yes;
    no.

Definition: a thing is liquiferous:
    if it is sodden, yes;
    if it is in a waterfilled container, yes;
    no.

Test me with "x book / x bag / get bag / take off gloves / w / u / put gloves in cupboard / z / open bag / touch book / push book / turn book / get gloves / wear gloves / get book".

Test disaster with "open bag".

Test mishandling with "get bag / open bag / get book".

266. Lemonade ★★★

Liquids, and all substances that can be mixed or broken off in partial amounts, pose a challenge to model in interactive fiction. The following example is a simple one, but adequate for many scenarios.

We start by assuming that all liquids in the game will always appear in containers. The player can pour liquids from one container to another, and the containers keep track of how full they are and describe themselves appropriately. The player can also refer to containers by content.

Mixture, however, is not allowed, nor is it possible to put liquids on other objects, pour them out on the ground, etc. These ideas would require a more complicated set-up.

paste.png "Lemonade"

A volume is a kind of value. 15.9 fl oz specifies a volume with parts ounces and tenths (optional, preamble optional).

A fluid container is a kind of container. A fluid container has a volume called a fluid capacity. A fluid container has a volume called current volume.

The fluid capacity of a fluid container is usually 12.0 fl oz. The current volume of a fluid container is usually 0.0 fl oz.

Liquid is a kind of value. The liquids are water, milk, lemonade, and iced tea. A fluid container has a liquid.

Instead of examining a fluid container:
    if the noun is empty,
        say "You catch just a hint of [the liquid of the noun] at the bottom.";
    otherwise
        say "[The noun] contains [current volume of the noun in rough terms] of [liquid of the noun]."

To say (amount - a volume) in rough terms:
    if the amount is less than 0.5 fl oz:
        say "a swallow or two";
    otherwise if tenths part of amount is greater than 3 and tenths part of amount is less than 7:
        let estimate be ounces part of amount;
        say "[estimate in words] or [estimate plus 1 in words] fluid ounces";
    otherwise:
        if tenths part of amount is greater than 6, increase amount by 1.0 fl oz;
        say "about [ounces part of amount in words] fluid ounce[s]".

Before printing the name of a fluid container (called the target) while not drinking:
    if the target is empty:
        say "empty ";
    otherwise:
        do nothing.

After printing the name of a fluid container (called the target) while not examining:
    unless the target is empty:
        say " of [liquid of the target]";
        omit contents in listing.

Instead of inserting something into a fluid container:
    say "[The second noun] has too narrow a mouth to accept anything but liquids."

Definition: a fluid container is empty if the current volume of it is 0.0 fl oz. Definition: a fluid container is full if the current volume of it is the fluid capacity of it.

Understand "drink from [fluid container]" as drinking.

Instead of drinking a fluid container:
    if the noun is empty:
        say "There is no more [liquid of the noun] within." instead;
    otherwise:
        decrease the current volume of the noun by 0.2 fl oz;
        if the current volume of the noun is less than 0.0 fl oz, now the current volume of the noun is 0.0 fl oz;
        say "You take a sip of [the liquid of the noun][if the noun is empty], leaving [the noun] empty[end if]."

We have allowed all liquids to be drunk, but it would be possible also to add checking, if we had a game where some liquids were beverages and others were, say, motor oil.

Understand the command "fill" as something new.

Understand "pour [fluid container] in/into/on/onto [fluid container]" as pouring it into. Understand "empty [fluid container] into [fluid container]" as pouring it into. Understand "fill [fluid container] with/from [fluid container]" as pouring it into (with nouns reversed).

Understand "pour [something] in/into/on/onto [something]" as pouring it into. Understand "empty [something] into [something]" as pouring it into. Understand "fill [something] with/from [something]" as pouring it into (with nouns reversed).

Pouring it into is an action applying to two things.

Check pouring it into:
    if the noun is not a fluid container, say "You can't pour [the noun]." instead;
    if the second noun is not a fluid container, say "You can't pour liquids into [the second noun]." instead;
    if the noun is the second noun, say "You can hardly pour [the noun] into itself." instead;
    if the liquid of the noun is not the liquid of the second noun:
        if the second noun is empty, now the liquid of the second noun is the liquid of the noun;
        otherwise say "Mixing [the liquid of the noun] with [the liquid of the second noun] would give unsavory results." instead;
    if the noun is empty, say "No more [liquid of the noun] remains in [the noun]." instead;
    if the second noun is full, say "[The second noun] cannot contain any more than it already holds." instead.

Carry out pouring it into:
    let available capacity be the fluid capacity of the second noun minus the current volume of the second noun;
    if the available capacity is greater than the current volume of the noun, now the available capacity is the current volume of the noun;
    increase the current volume of the second noun by available capacity;
    decrease the current volume of the noun by available capacity.

Report pouring it into:
    say "[if the noun is empty][The noun] is now empty;[otherwise][The noun] now contains [current volume of the noun in rough terms] of [liquid of the noun]; [end if]";
    say "[the second noun] contains [current volume of the second noun in rough terms] of [liquid of the second noun][if the second noun is full], and is now full[end if]."

This is probably a drier description than we would actually want in our story, but it does allow us to see that the mechanics of the system are working, so we'll stick with this for the example.

Now we need a trick from a later chapter, which allows something to be described in terms of a property it has. This way, the story will understand not only "pitcher" and "glass" but also "pitcher of lemonade" and "glass of milk" -- and, indeed, "glass of lemonade", if we empty the glass and refill it with another substance:

Understand the liquid property as describing a fluid container. Understand "of" as a fluid container.

And now the scenario itself:

The Porch is a room. The porch swing is an enterable supporter in the Porch. "An inviting swing hangs here at the end of the porch, allowing you to enjoy the summer with a cool beverage, and watch your neighbor Ted mowing his lawn with the very last manual powerless lawnmower on the block."

The glass is a fluid container carried by the player. The liquid of the glass is milk. The current volume of the glass is 0.8 fl oz.

The pitcher is a fluid container in the Porch. The fluid capacity of the pitcher is 32.0 fl oz. The current volume of the pitcher is 20.0 fl oz. The liquid of the pitcher is lemonade.

Ted's Lawn is outside from the Porch. Ted is a man in Ted's Lawn. "Ted has taken off his shirt, but still seems a bit oppressed by the sun." The description of Ted is "He looks hot. In all senses."

After deciding the scope of the player: place Ted in scope.

Instead of doing something to Ted when the player is in the Porch: say "You can't really interact with Ted from this distance, except in the sense of eyeing him surreptitiously."

Instead of giving an empty fluid container to Ted: say "Yes, taunt the poor man, why don't you?"

Instead of giving a fluid container to Ted when the liquid of the noun is milk: say "Ted looks ruefully at the milk. 'Thanks, but I'm lactose-intolerant,' he says."

The block giving rule is not listed in the check giving it to rules.

Every turn:
    if Ted is in the location:
        if Ted carries a fluid container (called refreshment):
            try Ted drinking the refreshment;
        otherwise if a random chance of 1 in 3 succeeds:
            say "Ted pushes the ineffective mower over some dandelions."

Instead of someone drinking a fluid container:
    if the noun is empty:
        try the person asked giving the noun to the player;
    otherwise:
        decrease the current volume of the noun by 2.0 fl oz;
        if the current volume of the noun is less than 0.0 fl oz, now the current volume of the noun is 0.0 fl oz;
        say "[The person asked] gulps down some [liquid of the noun]."

After someone giving something to the player:
    say "'Here,' says [the person asked], handing [the noun] back to you. 'Thanks, I owe you one.'";
    end the story finally.

Test me with "x milk / x lemonade / drink lemonade / drink milk / pour lemonade into glass / drink milk / x milk / drink milk / g / i / fill glass with lemonade / drink lemonade / drop glass / drink lemonade / pitcher".

Test Ted with "out / give milk to ted / drink milk / g / g / g / give glass to ted / in / fill glass with lemonade / out / give lemonade to ted / wait / z / z / z ".

267. Savannah ★★★

Here we build very slightly on the existing liquid implementation to add a puzzle where the player puts out a fire with a bucket of water. Most of the liquid implementation remains the same as before, but now we understand the names of containers according to the liquids they contain.

The new material, pertaining to extinguishing fires, is at the bottom in section 2.

paste.png "Savannah"

Section 1 - Essentials of Liquid

A volume is a kind of value. 15.9 fl oz specifies a volume with parts ounces and tenths (optional, preamble optional).

A fluid container is a kind of container. A fluid container has a volume called a fluid capacity. A fluid container has a volume called current volume.

The fluid capacity of a fluid container is usually 12.0 fl oz. The current volume of a fluid container is usually 0.0 fl oz.

Liquid is a kind of value. A fluid container has a liquid.

Instead of examining a fluid container:
    if the noun is empty,
        say "You catch just a hint of [the liquid of the noun] at the bottom.";
    otherwise
        say "[The noun] contains [current volume of the noun in rough terms] of [liquid of the noun]."

To say (amount - a volume) in rough terms:
    if the amount is less than 0.5 fl oz:
        say "a swallow or two";
    otherwise if tenths part of amount is greater than 3 and tenths part of amount is less than 7:
        let estimate be ounces part of amount;
        say "[estimate in words] or [estimate plus 1 in words] fluid ounces";
    otherwise:
        if tenths part of amount is greater than 6, increase amount by 1.0 fl oz;
        say "about [ounces part of amount in words] fluid ounce[s]".

Before printing the name of a fluid container (called the target) while not drinking:
    if the target is empty:
        say "empty ";
    otherwise:
        do nothing.

After printing the name of a fluid container (called the target) while not examining:
    unless the target is empty:
        say " of [liquid of the target]";
        omit contents in listing.

Instead of inserting something into a fluid container:
    say "[The second noun] has too narrow a mouth to accept anything but liquids."

Definition: a fluid container is empty if the current volume of it is 0.0 fl oz. Definition: a fluid container is full if the current volume of it is the fluid capacity of it.

Understand "drink from [fluid container]" as drinking.

Instead of drinking a fluid container:
    if the noun is empty:
        say "There is no more [liquid of the noun] within." instead;
    otherwise:
        decrease the current volume of the noun by 0.2 fl oz;
        if the current volume of the noun is less than 0.0 fl oz, now the current volume of the noun is 0.0 fl oz;
        say "You take a sip of [the liquid of the noun][if the noun is empty], leaving [the noun] empty[end if]."

Understand the command "fill" as something new.

Understand "pour [fluid container] in/into/on/onto [fluid container]" as pouring it into. Understand "empty [fluid container] into [fluid container]" as pouring it into. Understand "fill [fluid container] with/from [fluid container]" as pouring it into (with nouns reversed).

Understand "pour [something] in/into/on/onto [something]" as pouring it into. Understand "empty [something] into [something]" as pouring it into. Understand "fill [something] with/from [something]" as pouring it into (with nouns reversed).

Pouring it into is an action applying to two things.

Check pouring it into:
    if the noun is not a fluid container, say "You can't pour [the noun]." instead;
    if the second noun is not a fluid container, say "You can't pour liquids into [the second noun]." instead;
    if the noun is the second noun, say "You can hardly pour [the noun] into itself." instead;
    if the liquid of the noun is not the liquid of the second noun:
        if the second noun is empty, now the liquid of the second noun is the liquid of the noun;
        otherwise say "Mixing [the liquid of the noun] with [the liquid of the second noun] would give unsavory results." instead;
    if the noun is empty, say "No more [liquid of the noun] remains in [the noun]." instead;
    if the second noun is full, say "[The second noun] cannot contain any more than it already holds." instead.

Carry out pouring it into:
    let available capacity be the fluid capacity of the second noun minus the current volume of the second noun;
    if the available capacity is greater than the current volume of the noun, now the available capacity is the current volume of the noun;
    increase the current volume of the second noun by available capacity;
    decrease the current volume of the noun by available capacity.

Report pouring it into:
    say "[if the noun is empty][The noun] is now empty;[otherwise][The noun] now contains [current volume of the noun in rough terms] of [liquid of the noun]; [end if]";
    say "[the second noun] contains [current volume of the second noun in rough terms] of [liquid of the second noun][if the second noun is full], and is now full[end if]."

Understand the liquid property as describing a fluid container. Understand "of" as a fluid container.

Section 2 - Putting Out Fires

The Beach is a room. "The Atlantic stretches east to the horizon, though it is at low tide at the moment. It is dawn: time to pack up and go home."

We will skip implementing the Pacific ocean itself, though the example Lakeside Living shows how to incorporate large bodies of water into our liquid simulation.

The liquids are seawater. [We could include others, but for the moment...]

Instead of drinking a fluid container when the liquid of the noun is seawater:
    say "Blech!"

The bucket is a fluid container carried by the player. The liquid of the bucket is seawater. The current volume of the bucket is 64.0 fl oz.

The fire is a fixed in place thing in the beach. "A low fire crackles here, left over from an attempt at s'mores much earlier in the evening."

Instead of touching or rubbing or taking the fire, say "You're not such a glutton for punishment."

Instead of pouring something into the fire:
    now the fire is nowhere;
    now the current volume of the noun is 0.0 fl oz;
    say "[The second noun] goes out in a great hiss."

Test me with "drink seawater / pour seawater on fire / x bucket / i".

This is still a specific implementation: if we wanted to weave liquids together with a full-scale burning model (as in "In Fire or in Flood"), where pretty much any object in the game can be flaming (currently on fire) or damp (extinguished), we might generalize our rule to

Instead of pouring something into a flaming thing:
    now the second noun is damp;
    now the current volume of the noun is 0.0 fl oz;
    say "[The second noun] goes out in a great hiss."

Of course, the merging of fire and liquids also raises the possibility of gasoline and explosives, of heating and boiling liquids, etc.: as always, it's wise to incorporate a simulation that is only as detailed as the game's interactions really justify.

276. Noisy Cricket ★★★

Our previous experiments into liquid have not dealt with the possibility of mixing components, but that is because for most games, tracking the details of mixture is overkill.

But let's suppose that this time we do want to have mixed liquids; moreover, we want a way to describe the mixtures to the player inventively, so that if he hits specific combinations those combinations are recognized: calling the result a martini, say, rather than just "a mixture of vodka and vermouth".

The implementation that follows relies on a fairly simple idea from linear algebra. Any given liquid can be expressed as a vector in N-space, where N is the number of available ingredients and the length of the vector depends on how much of each ingredient is used; then we find the recipe that best describes the liquid by taking the dot product of our liquid vector with a bunch of sample vectors and selecting the one with the largest result.

If this does not make sense, don't worry: it's not necessary to understand the idea to use the code.

Any implementation involving a large number of place values is always a bit challenging in integer arithmetic. This examples assumes that no bodies of liquid will ever be very large, and that the proportions of ingredients in a mixture will not be vastly askew. (No 20-parts-to-1 proportions, for instance.) This probably works reasonably well for the cocktails that we make the basis of the example.

paste.png "Noisy Cricket"

Part 1 - Volumes and Mixtures

A volume is a kind of value. 15.9 fl oz specifies a volume with parts ounces and tenths (optional, preamble optional).

A fluid container is a kind of container. A fluid container has a volume called a fluid capacity. A fluid container has a volume called creme de menthe volume. A fluid container has a volume called vodka volume. A fluid container has a volume called cacao volume.

The fluid capacity of a fluid container is usually 12.0 fl oz. The creme de menthe volume of a fluid container is usually 0.0 fl oz. The vodka volume of a fluid container is usually 0.0 fl oz. The cacao volume of fluid container is usually 0.0 fl oz.

To decide what volume is the current volume of (item - a fluid container):
    let total be the creme de menthe volume of the item;
    increase total by the vodka volume of the item;
    increase total by the cacao volume of the item;
    decide on total.

Instead of examining a fluid container:
    if the noun is empty,
        say "You catch just a hint of [the nominal descriptor of the noun] at the bottom.";
    otherwise
        say "[The noun] contains [current volume of the noun in rough terms] of [adjectival descriptor of the noun] [nominal descriptor of the noun]."

Adjectival descriptor is a kind of value. The adjectival descriptors are strong, chocolatey, minty, perfect, and pure.

Nominal descriptor is a kind of value. The Nominal descriptors are creme de menthe, vodka, creme de cacao, grasshopper, chocolate vodka, mint vodka, chocolate martini, mintini, chocolate mint martini.

Our table of mixtures is expressed in parts: so if a recipe contains one part X and two parts Y, we would put "1" in the first column and "2" in the second column.

Table of Mixtures

rating

creme de menthe comp

vodka comp

cacao comp

adjectival descriptor

nominal descriptor

0.0 fl oz

1

0

0

minty

creme de menthe

0.0 fl oz

0

1

0

chocolatey

vodka

0.0 fl oz

0

0

1

chocolatey

creme de cacao

0.0 fl oz

1

2

0

chocolatey

mintini

0.0 fl oz

1

0

1

chocolatey

grasshopper

0.0 fl oz

0

2

1

chocolatey

chocolate martini

0.0 fl oz

0

3

1

chocolatey

chocolate vodka

0.0 fl oz

1

3

0

chocolatey

mint vodka

0.0 fl oz

1

2

1

chocolatey

chocolate mint martini

A fluid container has an adjectival descriptor. A fluid container has a nominal descriptor. Understand the adjectival descriptor property as describing a fluid container. Understand the nominal descriptor property as describing a fluid container.

To decide what number is (quantity - a number) squared:
    decide on quantity times quantity.

To score mixtures in (item - a fluid container):
    repeat through Table of Mixtures:
        let total line parts be creme de menthe comp entry squared;
        let total line parts be total line parts plus vodka comp entry squared;
        let total line parts be total line parts plus cacao comp entry squared;
        let creme de menthe score be creme de menthe comp entry times the creme de menthe volume of item;
        let vodka score be vodka comp entry times the vodka volume of item;
        let cacao score be cacao comp entry times the cacao volume of item;
        let total score be creme de menthe score plus vodka score;
        let total score be total score plus cacao score;
        let total score be total score times calibration for total line parts;
        now rating entry is total score;
        if total line parts is 1, now adjectival descriptor entry is pure;
        otherwise now adjectival descriptor entry is perfect;
        [and for creme de menthe...]
        now creme de menthe comp entry is creme de menthe comp entry plus 1;
        let total line parts be creme de menthe comp entry squared plus vodka comp entry squared;
        let total line parts be total line parts plus cacao comp entry squared;
        let creme de menthe score be creme de menthe comp entry times the creme de menthe volume of item;
        let vodka score be vodka comp entry times the vodka volume of item;
        let cacao score be cacao comp entry times the cacao volume of item;
        let total score be creme de menthe score plus vodka score;
        let total score be total score plus cacao score;
        let total score be total score times calibration for total line parts;
        if total score is greater than rating entry, now adjectival descriptor entry is minty;
        now creme de menthe comp entry is creme de menthe comp entry minus 1;
        [and for vodka...]
        now vodka comp entry is vodka comp entry plus 1;
        let total line parts be creme de menthe comp entry squared plus vodka comp entry squared;
        let total line parts be total line parts plus cacao comp entry squared;
        let creme de menthe score be creme de menthe comp entry times the creme de menthe volume of item;
        let vodka score be vodka comp entry times the vodka volume of item;
        let cacao score be cacao comp entry times the cacao volume of item;
        let total score be creme de menthe score plus vodka score;
        let total score be total score plus cacao score;
        let total score be total score times calibration for total line parts;
        if total score is greater than rating entry, now adjectival descriptor entry is strong;
        now vodka comp entry is vodka comp entry minus 1;
        [and for cacao...]
        now cacao comp entry is cacao comp entry plus 1;
        let total line parts be creme de menthe comp entry squared plus vodka comp entry squared;
        let total line parts be total line parts plus cacao comp entry squared;
        let creme de menthe score be creme de menthe comp entry times the creme de menthe volume of item;
        let vodka score be vodka comp entry times the vodka volume of item;
        let cacao score be cacao comp entry times the cacao volume of item;
        let total score be creme de menthe score plus vodka score;
        let total score be total score plus cacao score;
        let total score be total score times calibration for total line parts;
        if total score is greater than rating entry, now adjectival descriptor entry is chocolatey;
        now cacao comp entry is cacao comp entry minus 1.

To identify mixture in (item - a fluid container):
    score mixtures in item;
    sort Table of Mixtures in reverse rating order;
    choose row 1 in Table of Mixtures;
    now nominal descriptor of the item is nominal descriptor entry;
    let sample vodka be vodka comp entry; [Now keep track of all these]
    let sample creme de menthe be creme de menthe comp entry;
    let sample cacao be cacao comp entry;
    if rating entry divided by 100 is the current volume of the item:
        now adjectival descriptor of the item is pure;
    otherwise:
        now adjectival descriptor of the item is adjectival descriptor entry.

To decide what number is the raw quantity of (item volume - a volume):
    let raw be item volume divided by 0.5 fl oz;
    decide on raw.

To decide what number is calibration for (total - a number):
    if total is an initial listed in the table of Multipliers, decide on result entry;
    decide on 21.

Here we cheat on our arithmetic. The following chart just provides values corresponding roughly to 1/(sqrt (x)), but since Inform does not deal very gracefully with square roots or fractions, we will calculate this elsewhere and just supply the answers in the code:

Table of Multipliers

initial

result

1

100

2

71

3

57

4

50

5

44

6

41

7

38

8

35

9

33

10

31

11

30

12

29

13

28

14

27

15

26

16

25

17

24

18

24

19

23

20

22

When play begins:
    repeat with item running through fluid containers:
        identify mixture in item.

To say (amount - a volume) in rough terms:
    if the amount is less than 0.6 fl oz:
        say "half an ounce or less";
    otherwise if tenths part of amount is greater than 3 and tenths part of amount is less than 7:
        let estimate be ounces part of amount;
        say "[estimate in words] or [estimate plus 1 in words] fluid ounces";
    otherwise:
        if tenths part of amount is greater than 6, increase amount by 1.0 fl oz;
        say "about [ounces part of amount in words] fluid ounce[s]".

Before printing the name of a fluid container (called the target) while not drinking or pouring:
    if the target is empty:
        say "empty ";
    otherwise:
        do nothing.

After printing the name of a fluid container (called the target) while not examining or pouring:
    unless the target is empty:
        say " of [adjectival descriptor of the target] [nominal descriptor of the target]";
        omit contents in listing.

Instead of inserting something into a fluid container:
    say "[The second noun] has too narrow a mouth to accept anything but liquids."

Definition: a fluid container is empty if the current volume of it is 0.0 fl oz. Definition: a fluid container is full if the current volume of it is the fluid capacity of it.

Understand "drink from [fluid container]" as drinking.

Instead of drinking a fluid container:
    if the noun is empty:
        say "There is no more [nominal descriptor of the noun] within." instead;
    otherwise:
        let cacao loss be the consumed cacao of the noun out of sip volume;
        let creme de menthe loss be the consumed creme de menthe of the noun out of sip volume;
        let vodka loss be the consumed vodka of the noun out of sip volume;
        decrease the cacao volume of the noun by the cacao loss;
        decrease the creme de menthe volume of the noun by creme de menthe loss;
        decrease the vodka volume of the noun by vodka loss;
        say "You take a sip of [the nominal descriptor of the noun][if the noun is empty], leaving [the noun] empty[end if].".

Sip volume is a volume that varies. Sip volume is 0.5 fl oz.

To decide what volume is the consumed cacao of (item - a fluid container) out of (total consumption - a volume):
    let new volume be the cacao volume of the item times 100;
    let percentage be the new volume divided by the current volume of the item;
    let consumed volume be the percentage times total consumption;
    let consumed volume be consumed volume divided by 100;
    if consumed volume is greater than the cacao volume of the item, decide on the cacao volume of the item;
    decide on consumed volume.

To decide what volume is the consumed creme de menthe of (item - a fluid container) out of (total consumption - a volume):
    let new volume be the creme de menthe volume of the item times 100;
    let percentage be the new volume divided by the current volume of the item;
    let consumed volume be the percentage times total consumption;
    let consumed volume be consumed volume divided by 100;
    if consumed volume is greater than the creme de menthe volume of the item, decide on the creme de menthe volume of the item;
    decide on consumed volume.

To decide what volume is the consumed vodka of (item - a fluid container) out of (total consumption - a volume):
    let new volume be the vodka volume of the item times 100;
    let percentage be the new volume divided by the current volume of the item;
    let consumed volume be the percentage times total consumption;
    let consumed volume be consumed volume divided by 100;
    if consumed volume is greater than the vodka volume of the item, decide on the vodka volume of the item;
    decide on consumed volume.

Part 2 - Filling

Understand the command "fill" as something new.

Understand "fill [something] with/from [something]" as filling it with.

Filling it with is an action applying to two things. Carry out filling it with: try pouring the second noun into the noun instead.

Understand "pour [fluid container] in/into/on/onto [fluid container]" as pouring it into. Understand "empty [fluid container] into [fluid container]" as pouring it into.

Understand "pour [something] in/into/on/onto [something]" as pouring it into. Understand "empty [something] into [something]" as pouring it into.

Pouring it into is an action applying to two things.

Check pouring it into:
    if the noun is not a fluid container, say "You can't pour [the noun]." instead;
    if the second noun is not a fluid container, say "You can't pour liquids into [the second noun]." instead;
    if the noun is the second noun, say "You can hardly pour [the noun] into itself." instead;
    if the noun is empty, say "No more [nominal descriptor of the noun] remains in [the noun]." instead;
    if the second noun is full, say "[The second noun] cannot contain any more than it already holds." instead.

Carry out pouring it into:
    let available capacity be the fluid capacity of the second noun minus the current volume of the second noun;
    if the available capacity is greater than the current volume of the noun, now the available capacity is the current volume of the noun;
    let cacao loss be the consumed cacao of the noun out of available capacity;
    let creme de menthe loss be the consumed creme de menthe of the noun out of available capacity;
    let vodka loss be the consumed vodka of the noun out of available capacity;
    decrease the cacao volume of the noun by the cacao loss;
    decrease the creme de menthe volume of the noun by creme de menthe loss;
    decrease the vodka volume of the noun by vodka loss;
    increase the cacao volume of the second noun by the cacao loss;
    increase the creme de menthe volume of the second noun by creme de menthe loss;
    increase the vodka volume of the second noun by vodka loss.

Report pouring it into:
    identify mixture in noun;
    identify mixture in second noun;
    say "[if the noun is empty][The noun] is now empty; [otherwise][The noun] now contains [current volume of the noun in rough terms] of [nominal descriptor of the noun]; [end if]";
    say "[the second noun] contains [current volume of the second noun in rough terms] of [adjectival descriptor of the second noun] [nominal descriptor of the second noun][if the second noun is full], and is now full[end if]."

Understand "of" as a fluid container.

Part 3 - Scenario

When play begins: say "When you decided to try Mixology WS102 (*cross-listed with Women's Studies), you envisioned yourself writing essays about gender discrimination during the Prohibition, say, or reading essays on male vs. female metabolism of alcohol. But no: MxWS102 turns out to be about... mixing the perfect chocolate mint martini."

The College of Mixology is a room. The bar is a supporter in the college.

The cocktail glass is a fluid container carried by the player. The fluid capacity of the cocktail glass is 4.0 fl oz.

The flask is a fluid container carried by the player. The vodka volume of the flask is 4.0 fl oz.

The jigger is a fluid container carried by the player. The fluid capacity of the jigger is 1.0 fl oz.

The small measure is a fluid container carried by the player. The fluid capacity of the small measure is 0.5 fl oz.

The decanter is a fluid container on the bar. The fluid capacity of the decanter is 32.0 fl oz. The creme de menthe volume of the decanter is 20.0 fl oz.

The bottle is a fluid container carried by the player. The cacao volume of the bottle is 10.0 fl oz.

Test me with "i / pour flask in jigger / pour jigger in glass / pour bottle in jigger / pour jigger in glass / pour bottle in jigger / pour jigger in glass / pour decanter in jigger / pour jigger in glass / drink glass / g / g / x glass / pour flask in glass".

333. Lakeside Living ★★★

Much of what follows is identical to "Lemonade" earlier; the new material begins at Part 2.

paste.png "Lakeside Living"

A volume is a kind of value. 15.9 fl oz specifies a volume with parts ounces and tenths (optional, preamble optional).

A fluid container is a kind of container. A fluid container has a volume called a fluid capacity. A fluid container has a volume called current volume.

The fluid capacity of a fluid container is usually 12.0 fl oz. The current volume of a fluid container is usually 0.0 fl oz.

Liquid is a kind of value. The liquids are water, absinthe, and iced tea. A fluid container has a liquid.

Instead of examining a fluid container:
    if the noun is empty,
        say "You catch just a hint of [the liquid of the noun] at the bottom.";
    otherwise
        say "[The noun] contains [current volume of the noun in rough terms] of [liquid of the noun]."

To say (amount - a volume) in rough terms:
    if the amount is less than 0.5 fl oz:
        say "a swallow or two";
    otherwise if tenths part of amount is greater than 3 and tenths part of amount is less than 7:
        let estimate be ounces part of amount;
        say "[estimate in words] or [estimate plus 1 in words] fluid ounces";
    otherwise:
        if tenths part of amount is greater than 6, increase amount by 1.0 fl oz;
        say "about [ounces part of amount in words] fluid ounce[s]".

Before printing the name of a fluid container (called the target) while not drinking or pouring:
    if the target is empty:
        say "empty ";
    otherwise:
        do nothing.

After printing the name of a fluid container (called the target) while not examining or pouring:
    unless the target is empty:
        say " of [liquid of the target]";
        omit contents in listing.

Instead of inserting something into a fluid container:
    say "[The second noun] has too narrow a mouth to accept anything but liquids."

Definition: a fluid container is empty if the current volume of it is 0.0 fl oz. Definition: a fluid container is full if the current volume of it is the fluid capacity of it.

Understand "drink from [fluid container]" as drinking.

Instead of drinking a fluid container:
    if the noun is empty:
        say "There is no more [liquid of the noun] within." instead;
    otherwise:
        decrease the current volume of the noun by 0.2 fl oz;
        if the current volume of the noun is less than 0.0 fl oz, now the current volume of the noun is 0.0 fl oz;
        say "You take a sip of [the liquid of the noun][if the noun is empty], leaving [the noun] empty[end if]."

Part 2 - Filling

Understand the command "fill" as something new.

Here we want Inform to prefer full liquid sources to other containers when it chooses an end to a player's unfinished or ambiguous command. And so:

Understand "fill [fluid container] with/from [full liquid source]" as filling it with. Understand "fill [fluid container] with/from [fluid container]" as filling it with.

Both grammar lines point to the same ultimate outcome; the purpose of specifying both is to tell Inform to check thoroughly for full liquid sources before falling back on other fluid containers when making its decisions.

Understand "fill [something] with/from [something]" as filling it with.

Filling it with is an action applying to two things. Carry out filling it with: try pouring the second noun into the noun instead.

Understand "pour [fluid container] in/into/on/onto [fluid container]" as pouring it into. Understand "empty [fluid container] into [fluid container]" as pouring it into.

Understand "pour [something] in/into/on/onto [something]" as pouring it into. Understand "empty [something] into [something]" as pouring it into.

Pouring it into is an action applying to two things.

Check pouring it into:
    if the noun is not a fluid container, say "You can't pour [the noun]." instead;
    if the second noun is not a fluid container, say "You can't pour liquids into [the second noun]." instead;
    if the noun is the second noun, say "You can hardly pour [the noun] into itself." instead;
    if the liquid of the noun is not the liquid of the second noun:
        if the second noun is empty, now the liquid of the second noun is the liquid of the noun;
        otherwise say "Mixing [the liquid of the noun] with [the liquid of the second noun] would give unsavory results." instead;
    if the noun is empty, say "No more [liquid of the noun] remains in [the noun]." instead;
    if the second noun is full, say "[The second noun] cannot contain any more than it already holds." instead.

Carry out pouring it into:
    let available capacity be the fluid capacity of the second noun minus the current volume of the second noun;
    if the available capacity is greater than the current volume of the noun, now the available capacity is the current volume of the noun;
    increase the current volume of the second noun by available capacity;
    decrease the current volume of the noun by available capacity.

Report pouring it into:
    say "[if the noun is empty][The noun] is now empty;[otherwise][The noun] now contains [current volume of the noun in rough terms] of [liquid of the noun]; [end if]";
    say "[the second noun] contains [current volume of the second noun in rough terms] of [liquid of the second noun][if the second noun is full], and is now full[end if]."

Understand the liquid property as describing a fluid container. Understand "of" as a fluid container.

And now we add our liquid source kind, which will represent lakes, absinthe fountains, and any other infinite supplies of liquid we might need. Note that 3276.7 is the largest possible number of fluid ounces available to us.

A liquid source is a kind of fluid container. A liquid source has a liquid. A liquid source is usually scenery. The fluid capacity of a liquid source is usually 3276.7 fl oz. The current volume of a liquid source is usually 3276.7 fl oz. Instead of examining a liquid source: say "[The noun] is full of [liquid of the noun]."

Carry out pouring a liquid source into something: now the current volume of the noun is 3276.7 fl oz.

We want filling things from liquid sources to work the same way as usual, with the distinction that a) the liquid source never depletes in quantity (hence the carry-out rule resetting its fullness); and b) we should report the results a bit differently as well:

After pouring a liquid source into a fluid container:
    say "You fill [the second noun] up with [liquid of the noun] from [the noun]."

On the other hand, pouring liquids into a liquid source needs to work completely differently from pouring liquids into anything else. Let's say we're going to allow any liquid at all to be dumped into rivers and streams (environmental protections evidently are not very well-enforced in this scenario):

Instead of pouring a fluid container into a liquid source:
    if the noun is empty, say "[The noun] is already empty." instead;
    now the current volume of the noun is 0.0 fl oz;
    say "You dump out [the noun] into [the second noun]."

A couple of minor refinements:

Swimming is an action applying to nothing. Understand "swim" or "dive" as swimming.

Instead of swimming in the presence of a liquid source:
    say "You don't feel like a dip just now."

Before inserting something into a liquid source: say "[The noun] would get lost and never be seen again." instead.

Part 3 - Scenario

The Lakeside is a room. The Lakeside swing is an enterable supporter in the Lakeside. "Here you are by the lake, enjoying a summery view."

The glass is a fluid container carried by the player. The liquid of the glass is absinthe. The current volume of the glass is 0.8 fl oz.

The pitcher is a fluid container in the Lakeside. The fluid capacity of the pitcher is 32.0 fl oz. The current volume of the pitcher is 20.0 fl oz. The liquid of the pitcher is absinthe.

The lake is a liquid source. It is in the Lakeside.

The player wears a bathing outfit. The description of the bathing outfit is "Stylishly striped in blue and white, and daringly cut to reveal almost all of your calves, and quite a bit of upper arm, as well. You had a moral struggle, purchasing it; but mercifully the lakeshore is sufficiently secluded that no one can see you in this immodest apparel."

Instead of taking off the outfit: say "What odd ideas come into your head sometimes!"

Test me with "fill glass / empty absinthe into lake / fill glass / swim / drink lake / drink / x water / x lake".

RB §10.3. Dispensers and Supplies of Small Objects

A slightly tricky situation arises in IF when we want to offer the player a simulation of a near-infinite supply of something: a napkin dispenser from which he can keep taking more napkins, or an infinite selection of pebbles on a beach, or something of that nature.

One approach is simply to limit the number of items the player is allowed to pick up at a time, while maintaining the fiction that there are more of these items in existence than the player is allowed to interact with. Extra Supplies ★★ demonstrates this.

The task becomes harder if we do want to let the player have as many napkins as he wants. In some languages, it is possible to generate new objects on the fly after the story has begun (called "dynamic object creation"), and something like this is possible if we are compiling for Glulx. (See the Inform extensions site for examples.) Usually, though, it is less complicated and almost as effective simply to have a very large supply of existing objects, which are moved in and out of play as the player needs them. Pizza Prince demonstrates how to do this with slices of pizza.

See also

Ropes for an example involving divisible pieces of string, which relies on similar techniques

Examples

377. Pizza Prince

Suppose we want the player to have a pizza buffet from which he can take a number of slices. But we don't want to actually put the slices there in front of him, because "you can see 17 slices of pizza here" is not the descriptive effect we want, and because we want to pretend, at least, that the pizza supply is nearly infinite. In fact, we're going to replenish the supply by allowing eaten slices to return to the buffet table (safer in IF than in real life).

To do this, we create one object to stand in for the pizza supply, but whenever the player tries to take it, we give him a different "pizza slice" object instead. Thus:

paste.png "Pizza Prince"

The Pizza Prince is a room.

The buffet table is a supporter in Pizza Prince.

The pizza selection is a thing on the buffet table. Understand "slice" as the pizza selection. The description is "They are all cheese-only, and all luke-warm."

Rule for writing a paragraph about the buffet table:
    say "On [the buffet table] is [a pizza selection]. [description of the pizza selection][line break]".

Now we introduce our actual pizza slices, which are retained in a container out of play until they're needed:

A pizza slice is a kind of thing. 10 pizza slices are in Pizza Limbo. A pizza slice is always edible. [After a fashion, anyway.]

In this example we've set that supply to be artificially small, to make it easier to test what happens when the player reaches the limit; but we could provide many more slices to start with in Pizza Limbo, and the aim in practice would be to pick a number high enough (such as 50 or 100) that the average player will get bored of TAKE PIZZA long before he reaches the limit.

The main thing to be aware of is that objects consume memory in the game file, so creating a large number of pizza slices might bulk the game out. This is more of a concern if we're compiling for the Z-machine than if we're compiling for Glulx.

Whenever the player tries to take the selection, we want him to wind up holding an individual slice instead; but of course we need to check and make sure that he hasn't exhausted the pizza slice supply.

Instead of taking the pizza selection:
    let chosen slice be a random pizza slice in Pizza Limbo;
    if chosen slice is nothing: [That is, there were no slices remaining]
        say "[manager refusal]";
    otherwise:
        move the chosen slice to the player;
        say "Taken (gingerly)."

To say manager refusal:
    say "[one of]'Hey!' barks a hitherto-unseen manager from behind you. 'It's an 'all you can eat' buffet, not an 'all you can stuff down your pants' buffet.'[or]You are conscious of a disapproving huff from the manager, so you refrain.[stopping]"

That's fine for the case where the player is taking a new slice of pizza explicitly, but we need to handle it a little differently if the taking action is generated in response to EAT PIZZA. In that case, we need to take the slice and also change the identity of the noun, because after the implicit take action happens, the game will test whether the player is holding the noun before attempting to eat it. So we need to refocus its attention:

Rule for implicitly taking the pizza selection:
    let chosen slice be a random pizza slice in Pizza Limbo;
    if chosen slice is nothing: [That is, there were no slices remaining]
        say "[manager refusal]";
    otherwise:
        move the chosen slice to the player;
        say "(helping yourself from the selection)";
        now the noun is the chosen slice.

And finally, a bit of touch-up:

Rule for clarifying the parser's choice of the pizza selection while taking:
    say "(from the magnificent selection before you)[line break]"

For tidiness, we should probably also return the consumed pizza slices to Pizza Limbo so that they can be re-used later:

After eating a pizza slice:
    move the noun to Pizza Limbo;
    continue the action.

Test me with "i / get pizza / g / i / get pizza / drop pizza / look / get pizza / g / look / eat pizza / g / g / g / g / get pizza / g / g / g / g / g / g / g / g / g / g / g / g / i / eat pizza / take pizza / g".

124. Extra Supplies ★★

Suppose we have a supply closet in our game from which the player is allowed to take red pens. To keep modeling simple, we only allow him to have one in play at a time, and we test this by seeing whether the red pen is "off-stage" before moving it to his possession.

This approach might seem no different from having a single red pen sitting in the closet, but it may be preferable, for two reasons. First, it's not very plausible for a supply closet to contain nothing but a single red pen (well, assuming a well-regulated supplier, anyway); and second, it gives the player a way to get a new red pen should the original be destroyed in a tragic handwriting accident.

paste.png "Extra Supplies"

The Supply Closet is a room. A supply of red pens is in the Supply Closet. Understand "pen" as the supply of red pens when the red pen is not visible.

There is a red pen.

Instead of taking the supply of red pens:
    if the red pen is off-stage:
        move the red pen to the player;
        say "You help yourself to a fresh red pen.";
    otherwise:
        say "You're only allowed one pen at a time. The department secretary is very strict."

South of the Supply Closet is the Furnace Room. The incinerator is a thing in the Furnace Room. It is a container. "The incinerator is here, working full blast."

After inserting something into the incinerator:
    now the noun is nowhere;
    say "A fiery blast consumes [the noun]!"

Test me with "get pen / i / get pen / get supply / s / put pen in incinerator / n / get pen".

RB §10.4. Glass and Other Damage-Prone Substances

Just as Inform normally assumes everything is solid, it also assumes that these solid objects will not buckle, crack, break or deform under pressure, and cannot be fragmented. But breakability adds realism, and breakage need not be negative: sometimes we want the player to break her way in to something.

In IF the word DROP is more often used to mean "put down" or "leave behind" than "let go from a height": so it is perhaps unfair that in Ming Vase something fragile, when dropped, shatters (into nothing). In Spring Cleaning, fragile objects must be explicitly attacked by the player in order to break, and although they leave no tangible debris behind, their loss is at least remembered. Kyoto ★★ provides a general-purpose model for things being thrown at other things, with consequences including things moving (even between rooms) as well as breaking each other.

Debris from breakages is to be avoided if possible because it means keeping track of increasing numbers of objects. But we can increase realism by allowing something to have a visibly "broken" state, which it changes to when it breaks, rather than simply vanishing. Terracottissima ★★ provides for broken and unbroken flowerpots in this way.

Since "part of" allows us to have two objects joined together into what the player sees as one, it also gives us a natural seam which allows the whole to be broken back down into its component parts, and this is the neatest way of providing a breakage into pieces. Paddington ★★ demonstrates a cutting action which allows component parts to be cut away from their holders but will only make small surface gashes in any individual thing: so the player can cut something up, but only into the pieces we specifically choose to allow. Cutting also forces an opening into containers.

See also

Combat and Death for a robot that breaks into its component limbs when shot with a blaster
Goal-Seeking Characters for a character who eats donuts, leaving crumbs on the floor
Volume, Height, Weight for containers breaking under the weight of their contents
Ropes for cutting up string into up to 35 different pieces of different lengths - a limit the player is unlikely to find out about, but a limit all the same, and an expensive solution since we need 35 different things for the "debris" when string is "broken"

Examples

97. Ming Vase

In emulation of a certain annoying aspect of the original Adventure, in which there is a Ming vase that cannot safely be dropped:

paste.png "Ming Vase"

A thing can be strong or fragile. A thing is usually strong.

Instead of attacking or dropping a fragile thing:
    now the noun is nowhere;
    say "[The noun] breaks into thousands of pieces!"

The Cave is a room. The Ming vase is carried by the player. The vase is fragile.

We could also implement an additional refinement from Adventure, that a fragile thing is safe if dropped when there is a cushion nearby.

The pillow is a portable supporter. It is carried by the player.

Instead of dropping a fragile thing when the pillow is in the location: try putting the noun on the pillow instead.

After putting a fragile thing on the pillow:
    say "You set [the noun] down gently on the pillow."

Test me with "drop pillow / drop vase / get vase / get pillow / drop vase".

In this rule, the pillow is the second noun; if we had a general rule about setting fragile things on soft things, we could say "You set [the noun] down gently on [the second noun]." for the same effect.

If we wanted to be more refined, we would provide extra code so that breaking a container or a supporter would leave behind their contents. We will see how to do that later.

122. Spring Cleaning

Here we have a destruction action that allows the player to break any fragile items. Once destroyed, these things are removed from play, but we can still refer to them: they are now off-stage. This makes it easy for our sulking character to list the ones that have been destroyed:

paste.png "Spring Cleaning"

A thing can be tough or fragile. A thing is usually tough.

Instead of attacking something fragile:
    say "You smash [the noun] to smithereens!";
    now the noun is nowhere.

A knick-knack is a kind of thing which is fragile.

Every turn when a knick-knack is off-stage and Granny Blue can see the player:
    say "'Ohh,' whimpers Granny to herself softly. 'How I will miss [the list of off-stage knick-knacks]!'"

The Parlor is a room. Granny Blue is a woman in the Parlor. A china lamb, a porcelain milkmaid, a frolicking Dutch cow, and a crystal unicorn are knick-knacks in the Parlor.

Test me with "break lamb / break milkmaid / break cow / break unicorn".

195. Paddington ★★

Suppose we intend a game in which the player needs to cut things open on a regular basis. We'll want to check whether he has the proper tools handy, and deal graciously with commands such as CUT [something] when no tool is specified. So:

paste.png "Paddington"

A blade is a kind of thing.

Understand "cut [something] with [something]" as cutting it with.

Instead of cutting something:
    if a blade (called the edge) is held by the player,
        try cutting the noun with the edge;
    otherwise say "Your fingernails are not sharp enough."

Cutting it with is an action applying to two things.

Check cutting it with:
    if the noun is a person, say "That would hurt." instead;
    if the second noun is not a blade, say "[The second noun] has not got enough of a blade." instead.

Carry out cutting it with:
    increment the count of rips of the noun.

Report cutting it with:
    say "You slash [the noun] with [the second noun]."

We'll need a way to account for all these cuts and rips.

Definition: a thing is ripped if the count of rips of it > 0. A thing has a number called the count of rips. After examining something ripped, say "You see [the count of rips of the noun in words] rip[s] in [the noun][if something is in the noun], revealing [a list of things in the noun][end if]."

Moreover, because open containers normally list their contents when examined but we'd prefer Paddington's to be mentioned in the ripping paragraph:

The examine containers rule does nothing when examining the teddy bear.

So far, so good. But suppose that we'd like cutting also to make containers be permanently open and impossible to close again. We could write an "instead" rule, but that would mean that only our instead instructions would take effect, overriding the normal cutting it with rules entirely. Better would be to add a second carry out rule:

Carry out cutting a container with something:
    now the noun is open;
    now the noun is unopenable.

Now our rule will occur whenever a container is cut, but play will still go on to the reporting stage. And indeed we can add more of these, of varying degrees of specificity:

Carry out cutting something which is part of something with something:
    move the noun to the player.

Carry out cutting the quilt with something:
    now the description of the quilt is "Horribly tattered."

For that matter, we might want to add a report rule as well, to occur after the "You slash..." rule, so that every time the player cuts something open which has contents, the contents will be listed.

Report cutting it with:
    if the noun is open and the noun contains something,
        say "Visible within [is-are a list of things in the noun]."

This time we do not add the condition to the rule (i.e., Report cutting an open noun...) If we did, this report rule would be more specific than the general report rule, and would occur first.

The Safehouse is a room.

The teddy bear is a closed thing in the Safehouse. The description is "Fluffy[if the head is part of the bear], with an outsized head[otherwise], but headless[end if]." The head is a closed part of the teddy bear. In the bear is a large wad of stuffing. In the head are a small wad of stuffing and a packet of smuggled diamonds.

The quilt is in the Safehouse. The description is "An old but comforting quilt."

The player carries a blade called a switchblade.

Here is a final nicety to get rid of the "which is closed" statement on our closed unopenable teddy bear, using an "activity" rule:

After printing the name of a closed unopenable container:
    omit contents in listing.

Test me with "cut quilt with bear / cut quilt with switchblade / examine quilt / cut bear with switchblade / again / examine bear / cut head with switchblade / get diamonds / mourn loss of innocence".

315. Terracottissima ★★

This easiest way to do this uses the "printing the name of" activity, which will come up in the following chapter:

paste.png "Terracottissima"

A flowerpot is a kind of thing. Understand "pot" as a flowerpot.

A flowerpot can be unbroken or broken. After dropping an unbroken flowerpot: say "Crack!"; now the noun is broken. Understand the broken property as describing a flowerpot.

Before printing the name of a broken flowerpot, say "broken ". Before printing the name of an unbroken flowerpot: if a flowerpot is broken, say "unbroken ".

Before printing the plural name of a broken flowerpot, say "broken ". Before printing the plural name of an unbroken flowerpot: if a flowerpot is broken, say "unbroken ".

The Herb Garden is a room. In the Herb Garden are ten unbroken flowerpots.

Test me with "get three flowerpots / drop all / look".

404. Kyoto ★★

Suppose we want to expand the function of the existing THROW SOMETHING AT command so that a thrown object actually does make contact most of the time. A glance at the Actions index tells us that the Throwing it at rulebook currently looks like this:

Throwing something at something (past tense thrown it at)
    "drop [something held] at/against/on/onto [something]"

check

an actor throwing something at

implicitly remove thrown clothing rule

check

an actor throwing something at

futile to throw things at inanimate objects rule

check

an actor throwing something at

block throwing at rule

Some of those still look useful. We want to leave the "implicitly remove thrown clothing" rule, for instance -- no fair having the player throw a hat that's on his head. On the other hand, the "futile to throw things at inanimate objects rule" is going to have to go, because that would prevent us from ever being able to complete the throwing command. So let's get rid of that:

paste.png "Kyoto"

Part 1 - Throwing Rules

The futile to throw things at inanimate objects rule is not listed in the check throwing it at rules.

That "block throwing at" rule also looks sinister: any "block..." rule in the standard actions library is there to print a message telling the player he can't do what he's asked to do.

But it's not enough to ignore it, the way we did the "futile" rule. Since we are only expanding the command to affect inanimate objects, let's replace the "block throwing at" rule with a different one which will only prevent the player throwing things at people:

The block throwing at people rule is listed instead of the block throwing at rule in the check throwing it at rules.

This is the block throwing at people rule:
    if the second noun is a person, say "That might be construed as an attack." instead.

Now we've changed the command so that some action can sometimes be carried out here -- but we don't have any rules for what happens. It's time to create some rules for our model world.

A thing can be hard or soft. A thing can be fragile or strong. Shape is a kind of value. The shapes are round, flat, and linear. A thing has shape.

If we're actually going to allow throwing, we might want to add a couple of extra checks to the rulebook to make sure that this happens when it ought:

Check throwing it at (this is the block juggling rule):
    if the player is carrying the second noun, say "It would be difficult to throw at something you are yourself holding." instead.

Check throwing it at (this is the avoid throwing things into themselves rule):
    if the second noun is within the noun, say "That would be a nice magic trick." instead.

And then the rules for the action itself:

Carry out throwing it at (this is the check aerodynamics rule):
    if the noun is flat:
        move noun to location;
        say "[The noun], unwieldy, flutters to the ground.";
        rule succeeds.

That "rule succeeds" ends the action here, if the noun is flat. If not, Inform goes on to the next rule in the carry out throwing it at rulebook:

Carry out throwing it at (this is the contact rule):
    say "[The noun] hits [the second noun].[paragraph break]";
    if the second noun is fragile and the noun is hard:
        destroy the second noun.

Carry out throwing it at (this is the landing rule):
    let destination be the location;
    if the second noun is on a supporter (called endtable), let destination be the endtable;
    if the second noun is a supporter, let destination be the second noun;
    move the noun to the destination;
    if the noun is fragile and the second noun is hard:
        destroy the noun;
        rule succeeds;
    say "[The noun] lands [if the destination is the location]nearby[otherwise]on [the destination][end if]."

These rules are assuming some backup information, so let's provide that as well:

Reliance relates a thing (called X) to a thing (called Y) when X is part of Y or X is in Y or X is on Y. The verb to be relying on means the reliance relation.

To destroy (item - a thing):
    let home be the holder of the item;
    if the item is part of something (called the superstructure), let home be the holder of the superstructure;
    if the item is visible:
        say "[The item] breaks[if something is relying on the item], leaving [a list of things which are relying on the item] behind[end if].";
    if something is relying on the item,
        now all the things which are relying on the item are in the home;
    now the item is nowhere.

Now suppose we'd like to add some further cases for what happens if the player breaks a fragile door this way:

To destroy (item - a door):
    now the item is open;
    now the item is unopenable;
    say "[The item] smashes."

Rule for printing the name of an unopenable open door while not throwing something at something:
    say "open doorway".

Understand "door" or "doorway" as a door.

This works, except that objects will continue to "strike" open, unopenable doors, with the result that the player can smash the same door over and over. What we need is another rule, after the aerodynamics rule and before the contact rule, that tells Inform how to handle throwing things at open doors.

This is the flying through doorways rule:
    if the second noun is an open door:
        let the distant room be the other side of the second noun;
        move the noun to the distant room;
        say "[The noun] flies out of sight into [the distant room].";
        rule succeeds.

If the original rulebook is one we wrote ourselves, we could just add that rule in the proper spot in order. If we got it from an extension, though, we might need to put it in the right place explicitly:

The flying through doorways rule is listed before the contact rule in the carry out throwing it at rules.

The magic of rulebooks is that they allow authors to amend each other's work (or the Standard Rules) with a fair amount of freedom. A well-written extension will give individual names to its rules, to allow subsequent authors to modify the function of the extension without too much trouble.

Now for an actual scenario with which to test this:

Part 2 - The Study

The sliding paper screen is a door. It is north of the Moss Garden and south of the Study. The paper screen is fragile.

The player carries a netsuke and a shamisen. The description of the netsuke is "A weight for the cord on which you wear your purse or your medicine box. This particular one has the shape of a bullfrog, carved from green stone." The netsuke is round, hard, and strong. Understand "green" or "stone" or "bullfrog" as the netsuke.

The description of the shamisen is "An instrument you have only begun to learn to play." The shamisen is linear, soft, and fragile. A neck is part of the shamisen. The neck is linear, strong, and hard. A body is part of the shamisen. The body is round, fragile, and soft. A string is part of the shamisen. The string is linear, soft, and strong. The printed name of the body is "[if the body is not part of the shamisen]shamisen [end if]body". The printed name of the neck is "[if the neck is not part of the shamisen]shamisen [end if]neck". Understand "shamisen" as the body when the body is not part of the shamisen. Understand "shamisen" as the neck when the neck is not part of the shamisen.

The description of the Study is "A restful three-tatami room." The Study contains a calligraphy box and a hanging scroll. The initial appearance of the hanging scroll is "A handsome scroll depicts two women in kimonos crossing a bridge; Mount Fuji is in the background." The calligraphy box contains a brush. The box is openable and closed. The brush is hard, linear, and strong. The calligraphy box is round, soft, and strong. The hanging scroll is flat, soft, and strong.

The description of the Moss Garden is "Earlier today, you arranged three leaves on the moss in imitation of autumn. They must not be disturbed." The leaves are scenery in the Moss Garden. Instead of throwing something at the leaves: say "You spent too long over their placement."

Test me with "test one / test two".

Test one with "open screen / throw netsuke at screen / n / get netsuke / close screen / get scroll / throw scroll at screen / throw netsuke at scroll / get netsuke / throw netsuke at shamisen / drop netsuke".

Test two with "throw shamisen at netsuke / get all / throw netsuke at screen / get netsuke / throw netsuke at door / s / get netsuke".

RB §10.5. Volume, Height, Weight

What should fit into what? Inform has basically three sizes: small, person-sized, and room-sized. The difference between "small" and "person-sized" doesn't appear much, but it's the difference between an ordinary container and an enterable container; the fact that a person cannot get inside an ordinary container is one of the few size-related rules built into Inform. It will not object to, say, a fishing rod being put inside a matchbox.

Inform does have one built-in measure of the size of a container: its "carrying capacity". This is a maximum number of contents:

The carrying capacity of the rucksack is 3.

This of course allows three anvils, while forbidding four postage stamps. To do better, we need units of measurement, and Dimensions ★★ demonstrates setting these up. The Speed of Thought ★★, meanwhile, ventures into the area of unit conversion: having multiple types of unit and being able to express them to the player, or parse these in the player's input.

To be fully realistic in what will fit into what, we need sophisticated three-dimensional models of shapes, both of the items being carried and of the free space remaining inside containers. Depth elegantly simplifies this by approximating items as cuboids, with a given width, length and height: these multiply to give a volume. To fit in a container, a new item's volume must not exceed the volume remaining inside the container, and in addition its three dimensions must also fit in one of the possible arrangements at right angles to the sides. (So this system would indeed prevent a 1x1x100 fishing rod from being put inside a 5x2x1 matchbox, but would also prevent a 12x1x1 pencil from being put into a 10x10x1 box, because it would need to be turned diagonally to fit.)

Lead Cuts Paper ★★★ provides a different constraint: here we do not let light-weight containers hold heavy objects.

Weight comes in a different way into Swerve left? Swerve right? Or think about it and die?, which exploits up/down map connections to work out which way gravity would take a rolling marble.

See also

Liquids for containers with liquid capacity

Examples

233. Swerve left? Swerve right? Or think about it and die?

Suppose we have marbles that roll downhill across our map, in a life-size version of one of those marble-chute toys. We might now want to keep track of both compass relationships and which-room-slopes-into-which, so we make a new relation:

paste.png "Swerve left? Swerve right? Or think about it and die?"

Overlooking relates various rooms to various rooms.

The verb to overlook means the overlooking relation.

A thing can be spherical or lumpy. A marble is a kind of thing. A marble is always spherical. The player carries a marble called a red marble. The player carries a marble called an agate marble. The player carries a marble called a blue cloudy marble.

The Long Yellow Slide is north of the Funnel. The Long Yellow Slide overlooks the Blue Funnel. The Ski-jump is below the Blue Funnel. The Blue Funnel overlooks the Ski-jump. The Ski-jump overlooks the Landing Bowl. The Landing Bowl overlooks the Snake Run. The Landing Bowl is north of the Snake Run. The Snake Run overlooks the Goal. The Snake Run is north of the Goal.

Definition: a room is sloping if it overlooks a room.

And let's say we want the player to be allowed to slide, too, since that would be much more fun than just watching the marbles go:

Understand "sit" as sitting down. Sitting down is an action applying to nothing. Check sitting down: if the player is spherical, say "You are already seated." Carry out sitting down: now the player is spherical. Report sitting down: say "You sit, ready to slide wherever fate takes you."

Understand the command "stand" as something new.

Understand "stand" or "stand up" as standing up. Standing up is an action applying to nothing. Check standing up: if the player is lumpy, say "You are already standing." Carry out standing up: now the player is lumpy. Report standing up: say "You get to your feet."

Now a rule to control what happens to all our sliding and rolling objects:

Every turn:
    repeat with item running through spherical things which are in sloping rooms:
        let the current space be the holder of the item;
        let the final space be a random room which is overlooked by the current space;
        if the player can see the item and the item is a marble, say "[The item] rolls out of the room toward [the final space].[line break]";
        if the player is the item, say "You keep sliding...";
        move the item to the final space;
        if the player can see the item and the item is a marble, say "[The item] rolls into the room from [the current space].[line break]".

Since the Ski-jump overlooks the Landing Bowl, the marble will be able to fly through the air to its destination, even though there is no map connection to allow the player to cross. We might want to let the player make it across this barrier also, so:

Instead of jumping in a sloping room:
    say "You leap...";
    move the player to a random room overlooked by the location.

Because overlooking is various-to-various, we could include that element popular in marble chute toys, the splitter:

The Downhill Splitter is north of the Long Yellow Slide. "The green plastic chute runs downhill towards a Y-junction, forcing incoming marbles right or left."

The Downhill Splitter overlooks the Long Yellow Slide and the Purple Snaking Passage. The Purple Snaking Passage is southeast of the Downhill Splitter. The Purple Snaking Passage overlooks the Landing Bowl. The Purple Snaking Passage is above the Landing Bowl.

The player is in the Downhill Splitter.

Test me with "drop red / drop blue / sit / z / stand up / drop agate / sit / z / z / z / z / z".

268. Depth

In the following, we pretend that every item has a cuboidal shape. Every thing has a length, width and depth, while a "measured container" also has interior dimensions. (Thus a 10x10x10 container with 1cm-thick sides might have interior dimensions 9x9x9.)

paste.png "Depth"

A length is a kind of value. 10 cm specifies a length. An area is a kind of value. 10 sq cm specifies an area. A length times a length specifies an area. A volume is a kind of value. 10 cu cm specifies a volume. A length times an area specifies a volume.

A thing has a length called height. A thing has a length called width. A thing has a length called depth. The height of a thing is usually 10 cm. The width of a thing is usually 10 cm. The depth of a thing is usually 10 cm.

To decide what volume is the exterior volume of (item - a thing):
    let base area be the height of the item multiplied by the width of the item;
    let base volume be the base area multiplied by the depth of the item;
    decide on the base volume.

In order to see how these shapes might fit together spatially, we need to work out the three dimensions in order of size. (If we were only dealing with portable objects, we could simply insist that the length always be greater than the width which in turn must be greater than the depth, because we could always turn them over in our hands until this was so: but some of the things we deal with may be fixed in place.) A clever way to do this might be to put them in a table of three rows and sort it, but we will write the calculation out longhand:

To decide what length is the largest dimension of (item - a thing):
    let long side be the height of item;
    if the width of the item is greater than the long side, now the long side is the width of the item;
    if the depth of the item is greater than the long side, now the long side is the depth of the item;
    decide on the long side.

To decide what length is the middling dimension of (item - a thing):
    let longer side be the height of item;
    let shorter side be the width of item;
    if the width of the item is greater than the height of the item:
        let shorter side be the height of item;
        let longer side be the width of item;
    if the depth of the item is greater than the longer side, decide on the longer side;
    if the depth of the item is less than the shorter side, decide on the shorter side;
    decide on the depth of the item.

To decide what length is the shortest dimension of (item - a thing):
    let short side be the height of item;
    if the width of the item is less than the short side, now the short side is the width of the item;
    if the depth of the item is less than the short side, now the short side is the depth of the item;
    decide on the short side.

When testing this example, the author made use of the following: it's no longer needed, but may be useful to anyone else planning elaborations.

To test the dimensions of (item - a thing):
    say "[the item] - height [height of the item], width [width of the item], depth [depth of the item].";
    say "largest side [largest dimension of the item], middling [middling dimension of the item], smallest [shortest dimension of the item]."

We now introduce a new kind: a measured container, which not only has exterior dimensions - the height, width and depth which every thing now has - but also interior measurements. A convenient way to do calculations with the hollow interior is to regard it as if it were a solid shape in its own right, and we do this with the aid of something out of world, which the player never sees: the "imaginary cuboid", which is made into the shape of whatever measured container's interior is being thought about.

A measured container is a kind of container. A measured container has a length called interior height. A measured container has a length called interior width. A measured container has a length called interior depth.

There is an imaginary cuboid.

To imagine the interior of (receptacle - a measured container) as a cuboid:
    now the height of the imaginary cuboid is the interior height of the receptacle;
    now the width of the imaginary cuboid is the interior width of the receptacle;
    now the depth of the imaginary cuboid is the interior depth of the receptacle.

To decide what volume is the interior volume of (receptacle - a measured container):
    imagine the interior of the receptacle as a cuboid;
    decide on the exterior volume of the imaginary cuboid.

If we assume that we could always pack items into a measured container with perfect ease, never wasting any space, then the only volume constraint will be that the total volume of the contents must not exceed the volume of the inside of the container. So we need to calculate the available volume.

To decide what volume is the available volume of (receptacle - a measured container):
    let the remaining space be the interior volume of the receptacle;
    repeat with item running through things in the receptacle:
        decrease the remaining space by the exterior volume of the item;
    if the remaining space is less than 0 cu cm, decide on 0 cu cm;
    decide on the remaining space.

If we only constrained volume, a 140 cm-long fishing rod could fit into a 12 cm by 12 cm compact disc box. So we also insist the basic shape must fit, in some orientation perpendicular to one of the sides (i.e.: we can turn the item over in any of its three sides, but not turn it diagonally or wedge it in at a tilt). This requires the longest side of the item to be less than the longest side of the receptacle, and the middle-length side, and also the shortest side. The number of these conditions to fail gives us a clue as to how we can best describe the reason why the shape won't squeeze in.

Check inserting something (called the item) into a measured container (called the receptacle):
    if the exterior volume of the item is greater than the interior volume of the receptacle, say "[The item] will never fit inside [the receptacle]." instead;
    if the exterior volume of the item is greater than the available volume of the receptacle, say "[The item] will not fit into [the receptacle] with [the list of things in the receptacle]." instead;
    imagine the interior of the receptacle as a cuboid;
    if the largest dimension of the item is greater than the largest dimension of the imaginary cuboid, say "[The item] is too long to fit into [the receptacle]." instead;
    if the middling dimension of the item is greater than the middling dimension of the imaginary cuboid, say "[The item] is too wide to fit into [the receptacle]." instead;
    if the shortest dimension of the item is greater than the shortest dimension of the imaginary cuboid, say "[The item] is too bulky to fit into [the receptacle]." instead.

And finally a situation to try out these rules.

The Cubist Lab is a room. "A laboratory which, as the art critic Louis Vauxcelles said about Braque's paintings in 1908, is full of little cubes: everyday objects rendered as if cuboidal."

The box is a measured container. The interior height is 10 cm. The interior depth is 5 cm. The interior width is 6 cm. The player carries the box.

A pebble is a kind of thing. The height is usually 2 cm. The depth is usually 2 cm. The width is usually 2 cm. The player carries 25 pebbles.

A red rubber ball is carried by the player. The depth is 5 cm. The width is 5 cm. The height is 5 cm.
An arrow is carried by the player. The height is 40 cm. The width is 1 cm. The depth is 1 cm.
A crusty baguette is carried by the player. The height is 80 cm. The width is 4 cm. The depth is 5 cm.
A child's book is carried by the player. The height is 1 cm. The width is 9 cm. The depth is 9 cm.
A featureless white cube is carried by the player. The height is 6 cm. The width is 6 cm. The depth is 6 cm.

Test me with "put arrow in box / put book in box / put cube in box / put ball in box / put baguette in box / put pebbles in box".

Several warnings about this. First, the numbers can't go very high (if the Settings for the project set the story file format to the Z-machine): while the volume can in theory go to 32,767, in practice this equates to an object 32 cm on a side, which is not very large. One way to avoid this is to use the Glulx format, allowing for sizes in excess of 10 m on a side: or we could simply scale the dimensions to suit our purposes, using a decimeter (10 cm) as the basic unit of measurement, for instance.

Second, the system will require a height, width, and depth for every portable object in the game, which is a large commitment to data entry; it may become tiresome. So it is probably not worth bothering with this kind of simulation unless it is going to be genuinely significant.

258. Dimensions ★★

The following is not a very sophisticated approach, because it does not allow for weight to accumulate: if we put a gold ingot into a paper bag, then put the bag on the balance platform, only the bag's weight will register. But it will do for a first try.

paste.png "Dimensions"

A length is a kind of value. 10m specifies a length. An area is a kind of value. 10 sq m specifies an area. A length times a length specifies an area.

A weight is a kind of value. 10kg specifies a weight. Everything has a weight.

The verb to weigh means the weight property. A thing usually weighs 1kg.

Definition: A thing is light if its weight is 3kg or less.

Definition: A thing is heavy if its weight is 10kg or more.

The Weighbridge is a room.

A blackboard is in the Weighbridge. "A blackboard propped against one wall reads: '122/10 is [122 divided by 10] remainder [remainder after dividing 122 by 10]; 122kg/10kg is [122kg divided by 10kg] remainder [remainder after dividing 122kg by 10kg]; 122kg/10 is [122kg divided by 10] remainder [remainder after dividing 122kg by 10].'" The blackboard weighs 10kg.

A feather and a lead pig are in the Weighbridge. The lead pig weighs 45kg.

The balance platform is a supporter in the Weighbridge. "The balance platform is 10m by 8m, giving it an area of [10m multiplied by 8m], currently weighing [the list of things on the platform]. The scale alongside reads: [total weight of things on the platform]. [if two things are on the platform]Average weight is: [the total weight of things on the platform divided by the number of things on the platform]. Heaviest item is [the heaviest thing on the platform], at [weight of the heaviest thing on the platform]. Lightest item is [the lightest thing on the platform], at [weight of the lightest thing on the platform].[otherwise]It seems to be able to weigh several things at once."

Test me with "get feather / put it on platform / look / get pig / put it on platform / look".

269. The Speed of Thought ★★

Suppose that we have a number of objects in the game that are sized in some conventional unit (such as meters), but which we would like to describe in slightly less formal terms. To do this, we will start with measurements as defined in the built-in extension Metric Units, so we don't have to recreate all these.

We'll add our own set of "conceptual units" -- things we're familiar with in real life. As we'll see below, Inform will automatically choose a unit of the right order to express a given distance if we tell it to print a length "in conceptual units".

Note: the following will compile only if you have settings set for Glulx. (To change this, go to the Settings panel and click on the Glulx option.) The Glulx virtual machine is capable of handling larger numbers than the Z-machine.

paste.png "The Speed of Thought"

Section 1 - Procedure

Include Metric Units by Graham Nelson.

1 quarter (in conceptual units, in quarters, singular) or 2 quarters (in conceptual units, in quarters, plural) specifies a length equivalent to 24mm.
1 pencil (in conceptual units, in pencils, singular) or 2 pencils (in conceptual units, in pencils, plural) specifies a length equivalent to 18cm.
1 bathtub (in conceptual units, in bathtubs, singular) or 2 bathtubs (in conceptual units, in bathtubs, plural) specifies a length equivalent to 152cm.
1 Olympic swimming pool (in conceptual units, in Olympic swimming pools, singular) or 2 Olympic swimming pools (in conceptual units, in Olympic swimming pools, plural) specifies a length equivalent to 50 meters.
1 Empire state building (in conceptual units, in Empire State buildings, singular) or 2 Empire State buildings (in conceptual units, in Empire State buildings, plural) specifies a length equivalent to 443m.

1 credit card (in conceptual units, in credit cards, singular) or 2 credit cards (in conceptual units, in credit cards, plural) specifies an area equivalent to 46 sq cm.
1 letter sheet (in conceptual units, in letter sheets, singular) or 2 letter sheets (in conceptual units, in letter sheets, plural) specifies an area equivalent to 603 sq cm.
1 queen-sized mattress (in conceptual units, in queen-sized mattresses, singular) or 2 queen-sized mattresses (in conceptual units, in queen-sized mattresses, plural) specifies an area equivalent to 3 square meters.
1 football field (in conceptual units, in football fields, singular) or 2 football fields (in conceptual units, in football fields, plural) specifies an area equivalent to 5351 square meters.

Understand "report [something]" as reporting. Reporting is an action applying to one thing.

Check reporting:
    if the noun is not a fact:
        say "The public doesn't want to hear about [the noun]." instead.

Carry out reporting:
    now the noun is nowhere.

Report reporting:
    if the extent of the noun is greater than 0mm and the surface of the noun is greater than 0 sq cm:
        contextualize "'[The noun] has a length of [about] [extent of the noun in conceptual units] and an area of [about] [surface of the noun in conceptual units].'";
    otherwise if the extent of the noun is greater than 0mm:
        contextualize "'[The noun] has a length of [about] [extent of the noun in conceptual units].'";
    otherwise if the surface of the noun is greater than 0 sq cm:
        contextualize "'[The noun] has an area of [about] [surface of the noun in conceptual units].'";
    otherwise:
        say "'[The noun] is... pretty hard to imagine,' you say weakly. That's not going to go over well."

To say about:
    say "[one of]roughly[or]about[or]around[or]approximately[at random]";

To contextualize (chosen information - text):
    say "[one of]You turn to the camera and speak:[or][or]Turning to another camera angle, you add:[or][stopping] ";
    say "[chosen information] ";
    say "[one of][line break][or]Right now the station will be cutting over to a visual of that.[or][line break][or]Pity the kids in audiovisual who have to scare that image together in a hurry.[or]You smile brightly.[stopping]";

Section 2 - Scenario

The Science Journalism Desk is a room. "From here you, the Science Anchor, have the privilege of reporting the latest and most fascinating stories to an eager public."

After looking:
    try thinking.

Instead of thinking:
    say "Currently you have to report on the International Space Station. Your story could include [the list of facts carried by the player]."

Instead of taking inventory:
    say "It looks foolish to be fiddling with your possessions on camera."

Instead of dropping a fact:
    say "You decide to omit [the noun] from your lineup.";
    now the noun is nowhere.

A fact is a kind of thing. Every fact is carried by the player. A fact has a length called the extent. A fact has an area called the surface.

The experiment module is a fact. The extent is 1116cm.
The logistics module is a fact. The extent is 421cm.
The solar array is a fact. The surface is 375 sq m. The extent is 58m.
An individual solar cell is a fact. The surface is 8 sq cm.
The orbit height is a fact.

Report reporting the orbit height:
    contextualize "'The station orbits at heights between [about] [278km in conceptual units] and [460km in conceptual units] above the earth.'" instead.

Every turn:
    if the player carries no facts:
        say "And that's all! The channel cuts to weather.";
        end the story saying "Time for lunch".

Test me with "report experiment module / report logistics / report height / report array / report solar cell".

259. Lead Cuts Paper ★★★

The following shows the kind of "realism" rules which could be introduced using weights. Not entirely realistic: we do not bother to rupture containers out of the player's sight.

paste.png "Lead Cuts Paper"

A weight is a kind of value. 10kg specifies a weight. Everything has a weight. A thing usually has weight 1kg.

A container has a weight called breaking strain. The breaking strain of a container is usually 50kg. Definition: A container is bursting if the total weight of things in it is greater than its breaking strain.

A lead pig, a feather, a silver coin and a paper bag are in a room called the Metallurgy Workshop. The paper bag is a container with breaking strain 2kg. The lead pig has weight 50kg.

Every turn when a container (called the sack) held by someone visible (called the chump) is bursting:
    say "[The sack] splits and breaks under the weight! [if the player is the chump]You discard[otherwise][The chump] discards[end if] its ruined remains, looking miserably down at [the list of things in the sack] on the floor.";
    now all of the things in the sack are in the location;
    now the sack is nowhere.

Test me with "get bag / get feather / put feather in bag / get pig / put pig in bag / look".

RB §10.6. Ropes

Ropes, chains and similar long, thin, bendable items present three problems: they are like a liquid in that (unless unbreakable) they can be divided arbitrarily into smaller and smaller portions of themselves, they can be in two or more places at once (even in two or more rooms at once), and they can be tied down at either or both ends, allowing them to occupy an uneasy state in between being "portable" and "fixed in place". Even when all this is simulated, they allow us to pull on one end and so to exert force at the other - allowing action-at-a-distance which Inform's realism rules would ordinarily forbid. Ropes are hard. And it is very difficult to imagine everything a player might try when given a fully practical rope with which to solve puzzles.

Snip ★★★ solves the divisibility question, allowing string to be cut or retied into lengths of any size, with all the consequences for describing and understanding that this entails.

Otranto ★★★ provides a lengthy but straightforward approach to the other rope-related issues, subject to the simplifying assumptions that a rope is indivisible, has about the length of the distance between two adjacent rooms, and cannot be tied to another rope.

Examples

228. Otranto ★★★

The range of things one might want to do with a rope in a work of interactive fiction is fairly overwhelming. One might, in theory, swing from ropes; use them to tie containers shut; cut them up into smaller ropes; tie them together into longer ropes; employ them as fuses; bind other characters with them, or the player character.

Our rope implementation is, by these lights, reasonably simple, but it does account for the possibility of tying and untying both ends; using ropes to descend into lower rooms; pulling objects tied to the far end of the rope; and dragging objects from place to place.

paste.png "Otranto"

We start by coming up with a rope.

A rope is a kind of thing.

Definition: a thing is nonrope if it is not a rope. [The perfect idiocy of this statement notwithstanding, having a shortcut will come in very handy later]

Attachment relates things to each other in groups. The verb to be stuck to means the attachment relation.

Definition: a thing is tied if the number of things stuck to it is greater than 1.

Definition: a thing is free if it is not tied.

Definition: a rope is free if the number of nonrope things stuck to it is less than 2.

Definition: a thing is hindering if it is stuck to the noun and it is not within the location.

A thing can be round or unevenly shaped. A thing is usually round.

Definition: something is anchored if it is fixed in place or it is scenery or it is part of an anchored thing.

Definition: something is draggable if it is not had by the player and it is not the player and it is not anchored.

Now, we want a rope to be described in terms of the way it is tied, when it's described in a room description.

Rule for writing a paragraph about a rope (called the coil):
    if the coil is stuck to something which is in a room (called the next room) which is not the location:
        let the way be the best route from the location to the next room;
        if the way is up or the way is down:
            say "[The coil] runs [way] into [the next room].";
        otherwise:
            say "[The coil] snakes across the floor [way] towards [the next room].";
    otherwise:
        say "There is [a coil] here[if the coil is stuck to a visible nonrope thing], tied to [the list of nonrope visible things which are stuck to the coil][end if]."

To decide what room is the home of (item - a thing):
    if item is a door:
        let front cut be the number of moves from the location to the front side of the item;
        let back cut be the number of moves from the location to the back side of the item;
        if front cut is -1, let front cut be 999;
        if back cut is -1, let back cut be 999;
        if the location encloses the item, decide on the location;
        if front cut is greater than back cut, decide on the back side of the item;
        decide on the front side of the item;
    decide on the location of the item.

Rule for writing a paragraph about a nonrope thing (called the anchor) which is stuck to a rope (called the coil):
    if the coil is in an adjacent room:
        let the next room be the home of the coil;
        let the way be the best route from the location to the next room;
        if the way is up or the way is down:
            say "[The coil] runs [way] from [the anchor] into [the next room].";
        otherwise:
            say "From [the anchor] runs [a coil], heading off toward [the way].";
    otherwise:
        if the coil is stuck to something which is not visible,
            say "[The coil] is tied to [the anchor][if the coil is stuck to something in an adjacent room (called the next room)], and from there runs off towards [the next room][end if]."

We need a way to account for it when it's being carried, as well.

After printing the name of a rope (called the tied object) while taking inventory:
    if something nonrope is stuck to the tied object:
        say " (attached to [the list of nonrope things which are stuck to the tied object])";
    otherwise:
        say " (with both ends free)".

And, indeed, whenever the player examines a rope, we should see what's connected.

Instead of examining a rope (called the cord) when something is stuck to the cord:
    say "[The noun] is tied to [the list of secondary things which are stuck to the noun]."

Similarly, any time the player looks at something tied to a rope.

After examining the player when the player is stuck to something which is not the player:
    say "You're currently lashed to [the list of secondary things stuck to the noun]."

After examining something which is stuck to something secondary:
    say "[The noun] is currently attached to [the list of secondary things stuck to the noun]."

We also need to make sure that the rope can be interacted with properly even when it's partly in the next room.

After deciding the scope of the player:
    if something stuck to a rope (called the coil) is in the location, place the coil in scope.

A reaching inside rule:
    if the noun is a rope:
        let the anchor be a random visible thing stuck to the noun;
        if the anchor is touchable, allow access.

Now tying:

Before tying something to a rope:
    if the noun is stuck to the second noun, say "[The noun] and [the second noun] are already tied together." instead;
    if the second noun is not free, say "[The second noun] has no ends free." instead;
    if the noun is round, say "You can't realistically tie anything to [the noun]." instead.

Instead of tying a rope to something:
    try tying the second noun to the noun.

Instead of tying something to a rope:
    now the noun is stuck to the second noun;
    say "You loop [the second noun] around [the noun] and knot firmly."

Instead of tying something to a nonrope tied thing:
    let the coil be a random rope stuck to the second noun;
    try tying the noun to the coil.

Instead of tying a nonrope tied thing to something:
    let the coil be a random rope stuck to the noun;
    try tying the second noun to the coil.

Instead of tying a free nonrope thing to a free nonrope thing:
    if the player carries a free rope (called the coil):
        try tying the noun to the coil;
        if the noun is stuck to the coil and the coil is free:
            try tying the second noun to the coil;
    otherwise:
        say "You lack the requisite spare rope."

Understand "untie [something] from [something]" as untying it from. Understand "untie [something]" as untying it from.

Rule for supplying a missing second noun while untying something from:
    if the number of secondary things stuck to the noun is 0, say "[The noun] is already entirely free." instead;
    if the noun is a rope:
        if the number of touchable nonrope things which are stuck to the noun > 1:
            say "You'll have to say which thing you want to untie [the noun] from.";
            rule fails;
        otherwise:
            if the number of touchable nonrope things stuck to the noun is 0, say "You can't reach [the random nonrope thing stuck to the noun]." instead;
            let the tied object be a random touchable nonrope thing which is stuck to the noun;
            say "(from [the tied object])[line break]";
            now the second noun is the tied object;
    otherwise:
        if the noun is stuck to a rope (called the tied object):
            say "(from [the tied object])[line break]";
            now the second noun is the tied object.

Untying it from is an action applying to two things.

Before untying a rope from something: try untying the second noun from the noun instead.

Before untying something from a rope:
    if the second noun is not held:
        say "(first picking up [the second noun])[line break]";
        try taking the second noun.

Check untying it from:
    unless the noun is stuck to the second noun or the second noun is stuck to the noun,
        say "[The noun] and [the second noun] are already not tied together." instead.

Carry out untying it from:
    now the noun is not stuck to the second noun.

Report untying it from:
    say "Untied."

Another part of the fun of a rope is that you can drag things from another room:

After reading a command: now every thing is unmentioned.

Before pulling something anchored: say "[The noun] is firmly anchored." instead.

Instead of pulling something tied:
    if the noun is unmentioned:
        say "The impulse is transmitted to [the list of pullable things stuck to the noun].";
        repeat with item running through pullable things stuck to the noun:
            say "[item]: [run paragraph on]";
            try pulling the item;
        if the noun is a rope and the noun is not within the location:
            if the number of nonrope hindering things is 0, move the noun to the location;
    otherwise:
        continue the action.

Before pulling something which is not visible:
    if the noun is anchored:
        say "[The noun] resists, for whatever reason." instead;
    otherwise:
        let space be the holder of the noun;
        let way be the best route from the space to the location;
        if the way is a direction:
            move the noun to the location;
            say "[The noun] [if the way is up]rises[otherwise]slides[end if] into view." instead;
        otherwise:
            move the noun to the location;
            say "[The noun] slides into view." instead.

Definition: a thing is secondary if it is not the noun. Definition: a thing is pullable if it is not the noun and it is not the player.

A player who is tied to things should also have some restrictions on his ability to move.

Before going a direction (called the way) when the player has something (called the link) which is stuck to something anchored (called the anchor):
    let the next room be the home of the anchor;
    if the next room is not a room, continue the action;
    if the next room is the location:
        if the link is stuck to at least two anchored things,
            say "You can't go far while you're carrying [the link] tied to [the list of anchored things stuck to the link]." instead;
    otherwise:
        let the safe way be the best route from the location to the next room;
        if the safe way is the way:
            if the player is not stuck to the anchor, say "(coiling up your rope again as you go...)";
        otherwise:
            if the safe way is a direction,
                say "While you have [the link] you can't really head any direction but [best route from the location to the next room]." instead;
            otherwise say "You're tied up here." instead.

Before going a direction (called the way) when the player is stuck to something anchored (called the anchor):
    let the next room be the home of the anchor;
    if the next room is not a room, continue the action;
    if the next room is the location:
        if the player is stuck to at least two anchored things,
            say "You can't go far while you're tied to [the list of anchored things stuck to the player]." instead;
    otherwise:
        if the best route from the location to the next room is the way:
            say "(coiling up your rope again as you go...)";
        otherwise:
            say "Your attachments prevent you going any way but [best route from the location to the next room]." instead.

Sometimes, if the player is tied to a movable object, the moved object will move with him.

After going somewhere when the player has something (called the link) which is stuck to something draggable:
    if the player is not stuck to the link:
        say "You drag along behind you [the list of draggable things which are stuck to the link].";
        now every draggable thing which is stuck to the link is in the location;
    continue the action.

Report going somewhere when the player is stuck to something draggable:
    say "You drag along behind you [the list of draggable things which are stuck to the player].";
    now every draggable thing which is stuck to the player is in the location.

And now the actual game and puzzles.

Use full-length room descriptions.

The Fallow Field is a room. "The very land is gloomy, the earth plowed into untended rows that yield no fruit, shadowed by the castle to the north. A chasm, no doubt the product of some upheaval of the earth, opens before your feet.". An oak stump is fixed in place in the Field. "From an oak stump, a few hopeful shoots grow." A hempen rope is a rope in the field. It is stuck to the oak stump and the wooden chest. The stump is unevenly shaped.

The Chasm is below the Field. "Your person is most uncomfortably pressed on every side by the closeness of the walls; to which you may add as a further inconvenience, that the irregularity of the floor making it difficult to walk upright." An iron key is in the Chasm. "An iron key nestles in the cleft of earth, its age indicated by its implausibly great size."

The wooden chest is a unevenly shaped closed openable container in the Chasm. The description of the wooden chest is "A handsome, solid case not long committed to its dank enclosure, or it would long since have rotted." Rule for printing the name of the wooden chest when the chest is not handled: say "deadweight". Understand "dead" or "weight" or "deadweight" as the chest. Before pulling the wooden chest: now the chest is handled.

In the chest is a heavy dagger. The description of the dagger is "Set with red jewels and of a wicked aspect."

Before going down from the Field when the player is not stuck to something anchored:
    say "You don't quite dare simply leap into the darkness without some anchor." instead.

Before going down from the Field:
    let anchor be a random anchored thing which is stuck to the player;
    say "You lower yourself gingerly, hoping that [the anchor] holds your weight..."

Before going up from the Chasm:
    if the player cannot touch a rope which is stuck to an anchored thing which is in the Field, say "And how, precisely, do you mean to do that?" instead.

The Castle Hall is north of the Field. "All is desolate: the great hall has no roof, nor is there any glass in the windows. A staircase without banister ascends inside the wall to a musician's gallery without song."

The Musician's Gallery is above the Castle Hall. "Of its former cheery aspect only this remains to the Gallery: that chevrons of red and yellow are painted on the wall. But as these are streaked with rain and grime, the banister pulled away, the roof open to the sky, and the corners made a nesting place for birds, the consolation thereby afforded is but slight."

The pointed door is north of the Musician's Gallery and south of the Sinister Attic. It is a closed locked openable door. "A pointed door of particularly grim and uninviting aspect leads north." The pointed door is lockable and unevenly shaped. The description of the pointed door is "A door coming to a gothic point and fitted with iron fittings of great strength. The handle looks particularly well-attached." The iron key unlocks the pointed door.

A rule for reaching inside the Musician's Gallery:
    allow access.

A rule for reaching inside the Sinister Attic:
    allow access.

Instead of opening the pointed door for the first time:
    say "When you rattle at the door, there arises from beyond a terrible shrill noise as though something beyond exults in its imminent release."

After opening the trapped pointed door when the player can see the pointed door:
    say "Thousands of bats fly from the pointed door, attacking you!";
    end the story.

After opening the pointed door when the player cannot see the pointed door: now the pointed door is untrapped; continue the action.

The pointed door can be trapped or untrapped. The pointed door is trapped.

Before pulling the pointed door: try opening the pointed door instead.

The player is unevenly shaped.

After going to the sinister attic:
    say "You have arrived at the goal of your quest!";
    end the story finally.

Test me with "x rope / pull rope / get chest / untie rope from chest / tie rope to me / down / get key / up / untie rope from stump / north / up / unlock pointed door with key / open it / tie rope to door / down / pull rope / up / north".

Test death with "x rope / pull rope / get chest / untie rope from chest / tie rope to me / down / get key / up / untie rope from stump / north / up / unlock pointed door with key / open it / g"

261. Snip ★★★

paste.png "Snip!"

Length is a kind of value. 30 inch specifies a length. 20 in specifies a length. 50 inches specifies a length.

A string is a kind of thing. A string has a length. The length of a string is usually 36 inches.

Before printing the name of a string, say "[length] piece of ". Rule for printing the plural name of a string: say "[length] pieces of string".

Understand the command "cut" as something new. Understand "cut [length] from/off [something]" as trimming it by (with nouns reversed). Understand "cut [something] by [length]" as trimming it by. Understand the command "trim" as "cut".

Trimming it by is an action applying to one thing and one length.

Check trimming it by:
    if the length understood is 0 inches, say "You're approaching Zeno's string at this point." instead;
    if the length understood is greater than the length of the noun, say "[The noun] is only [length of the noun] long to start with." instead;
    if the length understood is the length of the noun, say "[The noun] is already exactly [length of the noun] long." instead.

Carry out trimming it by:
    now the length of the noun is the length of the noun minus the length understood;
    let the other half be a random string in the string repository;
    now the length of the other half is the length understood;
    move the other half to the player.

Report trimming it by:
    reset string lengths; [we will define this in a moment; it helps guarantee that our descriptions of the strings are correct when we write the output list]
    say "You now have [a list of strings carried by the player]."

Understand "cut [something] in half" as halving. Halving is an action applying to one thing.

Carry out halving:
    let half measure be the length of the noun divided by 2;
    now the length understood is half measure;
    try trimming the noun by half measure.

This fudges slightly, since an odd-length string will be divided into uneven halves. Keeping track of fractional inches would complicate matters, though, so let's assume for now that this doesn't matter.

The player carries a string.

The Scissors Room is a room.

The string repository contains 35 strings.

Since our initial string is 36 inches long and it is impossible for the player to divide it into pieces smaller than an inch each, we need a total of 36 items to represent all the string-bits: one that the player carries at the outset, and 35 others. We should bear in mind that it is usually a good idea to use the smallest number of spare objects we can get away with: writing a game that required 1000 strings in the string repository would place silly demands on the resources of the system, so it's best to avoid that sort of thing if possible.

Now with a bit of fiddling we can also teach Inform to recognize descriptors such as "the shortest string":

Ordinariness is a kind of value. The ordinarinesses are longest, medium, shortest. A string has an ordinariness. Understand the ordinariness property as referring to a string.

Definition: a string is small if its length is 2 in or less. Definition: a string is large if its length is 20 in or more.

Before reading a command:
    reset string lengths.

To reset string lengths:
    let upper measure be the length of the largest visible string;
    let lower measure be the length of the smallest visible string;
    repeat with item running through strings:
        now the ordinariness of the item is medium;
        if the length of the item is the upper measure, now the item is longest;
        if the length of the item is the lower measure, now the item is shortest.

After reading a command:
    if the player's command includes "shorter", replace the matched text with "shortest";
    if the player's command includes "longer", replace the matched text with "longest".

Instead of tying a string to a string:
    move the second noun to the string repository;
    now the length of the noun is the length of the noun plus the length of the second noun;
    decrease the length of the noun by 1 inch;
    say "You end up with [a noun], as some is taken up by the knot."

This is still a little incomplete because we cannot refer to strings by their lengths, as in "the 2 inch string" and so on. To do this, we borrow a line from the chapter on Understanding:

Understand the length property as referring to a string.

Test me with "trim string by 4 in / cut longer string in half / cut longest string in half / cut shortest string in half / g / g / tie longest string to shortest string / tie longest string to medium string / i / x 16 inch string / drop 8 inch string / i".

RB §10.7. Electricity and Magnetism

Electrons are so tiny, and move so fast, that we will never want to simulate them in ordinary IF. So we simply regard electricity and magnetism as behaviours which are either present or not present, and which have instantaneous effects.

In Witnessed 1 ★★★, batteries provide electricity to enable a "device" to work. Even if switched on, a device with no battery will be ineffective.

Larger voltages are exposed in Electrified, which makes certain items untouchable, and ensures that an experienced electrician will not even try.

Rules of Attraction provides for a magnet which attracts metallic items just strongly enough to stick together until pulled apart for any reason.

Examples

346. Rules of Attraction

Often we have some salient features of an object that we want to make sure the player notices whenever looking at the item in a room or in inventory. At other times, we may prefer to allow the name of the item to be printed bare. So for instance:

paste.png "Rules of Attraction"

A metal form is a kind of thing. A magnet is a kind of metal form.

Every turn:
    repeat with item running through nonmagnetic metal forms which are not part of something:
        if item is in a container which contains a magnet (called attractor):
            say "[The item] sticks to [the attractor].";
            now the item is part of the attractor.

The horseshoe magnet is a magnet carried by the player. The nail is a metal form carried by the player. The Barn is a room. In the Barn is a bucket. In the bucket is a metal form called the iron hook.

Definition: a thing is nonmagnetic if it is not a magnet.

Rule for printing room description details of a magnet (called attractor): if something is part of the attractor, say " (stuck to which [is-are the list of things which are part of the attractor])".

After printing the name of a magnet (called attractor) while taking inventory:
    if something is part of the attractor, say " (stuck to which [is-are the list of things which are part of the attractor])".

Before taking a touchable thing which is part of a magnet (called attractor):
    move the noun to the holder of the attractor.

Test me with "i / put horseshoe in bucket / look / get horseshoe / i / drop horseshoe / i / look / get all / put all in bucket / i / x magnet / get nail / i".

408. Electrified

Suppose we want to prevent the player from touching anything electrified -- not just as a response to TOUCH OBJECT, but at any time when the action would require contact with the object in question.

paste.png "Electrified"

A thing can be safe or electrified. A thing is usually safe.

The Open Field is a room. "At this end of the field is a wire fence separating farm country from the government testing grounds beyond." The wire fence is an electrified thing in Open Field. It is scenery. The description of the wire fence is "Built into the fence is [a list of things which are part of the fence]." The scary box is an electrified container. It is part of wire fence. In the scary box is an alluring prize.

The player carries a flashlight, a grappling hook, a very thick rubber glove, and a length of rope. The glove is wearable.

This is the electrocution-wisdom rule:
    if the player wears the very thick rubber glove, make no decision;
    if the action requires a touchable noun and the noun is electrified, say "You fear touching [the noun]." instead;
    if the action requires a touchable second noun and the second noun is electrified, say "You fear touching [the second noun]." instead.

The electrocution-wisdom rule is listed before the basic accessibility rule in the action-processing rules.

Before touching the scary box:
    say "You can't help noticing a bright red sticker on the surface of the box." [This rule will fire even if we are not wearing the glove, because Before rules occur before basic accessibility.]

Instead of opening the scary box:
    say "The scary box seems to be super-glued shut." [This one won't, because Instead rules occur after basic accessibility.]

Test me with "touch fence / touch box / open box / wear glove / open box".

139. Witnessed 1 ★★★

The following example makes fairly ample use of material that we haven't seen yet, but gives some idea of the flexibility of every turn rules. Suppose we want to have a number of electrical devices, all of which may be powered by a set of batteries. The batteries will all need to be discharged as they are used (regardless of what device they happen to be controlling at the moment). So:

paste.png "Witnessed"

A battery is a kind of thing. A battery has a number called charge. The charge of a battery is usually 15.

Every turn:
    repeat with hollow running through battery compartments:
        if the hollow is part of a switched on device (called the machine):
            if a battery (called cell) is in the hollow:
                decrement the charge of the cell;
                carry out the warning about failure activity with the machine;
                if the cell is discharged, carry out the putting out activity with the machine;
            otherwise:
                carry out the putting out activity with the machine.

Warning about failure of something is an activity.

Rule for warning about failure of a device (called the machine):
    if a random battery compartment which is part of the machine contains a battery (called the power source):
        if the charge of the power source is 2, say "[The machine] is obviously going to go out quite soon."

Putting out something is an activity.

Rule for putting out a device (called the machine):
        say "[The machine] loses power and switches off![line break]";
        silently try switching off the machine.

A battery compartment is a kind of container. A battery compartment is usually closed and openable. One battery compartment is part of every device. Instead of inserting something which is not a battery into a battery compartment, say "Only batteries should go in a battery compartment."

And to get rid of annoying messages like "Which would you like to close, the flashlight or the flashlight's battery compartment?" when only the compartment is closable, we might add some understanding instructions:

Understand "turn on [device]" as switching on.

Understand "turn off [device]" as switching off.

Understand "open [openable closed thing]" as opening.

Understand "close [openable open thing]" as closing.

Understand "put [something] in [container]" as inserting it into.

Instead of opening a device, try opening a random battery compartment which is part of the noun. Instead of closing a device, try closing a random battery compartment which is part of the noun. Instead of inserting a battery into a device, try inserting the noun into a random battery compartment which is part of the second noun.

Instead of switching on an empty device:
    say "Nothing happens, perhaps because there isn't a charged battery in [the noun]."

Instead of switching on a battery compartment which is part of a device (called the power user), try switching on the power user.

Definition: a device is empty:
    if a random battery compartment which is part of it contains a battery (called the power source):
        if the power source is discharged, yes;
        no;
    yes.

Definition: a battery is discharged if its charge < 1.

A light source is a kind of device. Carry out switching on a light source: now the noun is lit. Carry out switching off a light source: now the noun is unlit.

The flashlight is a light source. A D battery is a battery carried by the player.

The cassette recorder is a device. Every turn: if the cassette recorder is switched on, say "The cassette recorder hisses faintly."

Rule for warning about failure of the cassette recorder:
    if a random battery compartment which is part of the cassette recorder contains a battery (called the power source):
        if the charge of the power source is 2, say "The hiss from [the cassette recorder] begins to warble ominously."

The player wears a backpack. The backpack is openable. In the backpack is the flashlight and the cassette recorder.

The description of the cassette recorder is "Useful both for recording your notes and for capturing any odd ghostly sounds you may hear."

The description of the backpack is "An old familiar pack, which you know so well that you can find all its pockets and take things in and out of it in pitch darkness. To avoid it showing up oddly in photographs, it is entirely black, with no shiny or metallic attachments."

The description of the flashlight is "You bought a new one just for this occasion, because you were worried about bringing something too small or light. This is a heavy-duty flashlight with an adjustable-focus beam. The case is made of metal, rather than plastic, and there is a spare light-bulb inside as well. You've put a band of masking tape around the handle and written in your initials in red marker.

There is a piece of red cellophane attached to the business end of the flashlight to keep it from being overly bright."

The red cellophane is part of the flashlight.

Instead of doing something to the red cellophane: say "You need the cellophane on the flashlight so that using it does not completely destroy your night vision."

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."

And this last bit, borrowed from the chapter on Understanding, adds some special instructions to help Inform decide when the player is likely to be referring to a compartment and when he's likely to be referring to the device itself.

Does the player mean doing something other than searching to a battery compartment: it is unlikely. [We discourage Inform from choosing a compartment when the player uses just the name of a device or the word 'battery'.]

We also need to deal with commands like PUT BATTERY IN FLASHLIGHT, where Inform might construe BATTERY as the D battery, the flashlight's battery compartment, or the cassette recorder's battery compartment -- and might also construe FLASHLIGHT as either the flashlight's battery compartment or the flashlight itself.

Does the player mean inserting into a battery compartment:
    if the noun is nothing:
        it is very likely;
    otherwise:
        make no decision.

Does the player mean inserting a battery compartment into: it is very unlikely.

Does the player mean inserting something into a device: it is unlikely.

Does the player mean searching a battery compartment: it is very likely.

Test me with "test first / test second".

Test first with "i / open flashlight compartment / put battery in it / turn on flashlight / take d battery / open cassette compartment / turn on cassette / put battery in cassette compartment / turn on cassette / z / z / z / z".

Test second with "get d battery / put d battery in flashlight compartment / turn on flashlight / z / z / z / z / z / z / turn off flashlight / z / z / turn on flashlight / z".

RB §10.8. Fire

Fire exhibits some of the properties of a gas: it is only vaguely located and tends to spread out, though it passes by touch rather than on the air. It is hazardous to life, through direct contact, heat, and smoke. Better governed, it provides light and warmth. Worse governed, it consumes almost anything it comes into contact with. Here the problem with "debris" is not so much that we need potentially hundreds of new objects to represent broken items: instead, fire could sweep through a work of IF destroying so much that no play is possible any longer. Setting up a problem in which the player must defeat a fully-capable fire is difficult to balance.

As with liquids, it is best to simulate the least amount of fire that the design will allow. Bruneseau's Journey ★★ provides a single candle which can be lit, or blown out, but where fire can never transfer from the candle's end to anything else - or vice versa: the player's source of fire, with which to light the candle, is discreetly neglected.

In the more realistic Thirst 2, a campfire is lit using a tinderbox, so that fire does transfer from one thing (tinder) to another (the campfire): but it is always confined to just these two items, and can be used only for light and warmth.

The Cow Exonerated ★★ provides a class of matches that can light any flammable object, but assumes that burning objects requires only one turn; lighting one thing does not burn another.

In Fire or in Flood ★★★ provides a complete simulation of what we might call "wild-fire": combustion which spreads through arbitrary objects and rooms, destroying all in its path.

See also

Examining for a way to describe objects as charred once they have been partly burnt
Heat for one consequence of fire having touched something
Gases for an implementation of smoke without fire, if this can exist
Liquids for water being used to extinguish a simple fire
Lighting for other uses of candles and torches as light sources

Examples

117. Thirst 2

paste.png "Thirst"

The player carries a waterskin. The waterskin can be full, partly drained, or empty. The waterskin is full. Understand "water" as the waterskin.

Instead of drinking the waterskin when the waterskin is empty:
    say "There is no water left."

Instead of drinking the waterskin: if the waterskin is partly drained, now the waterskin is empty; if the waterskin is full, now the waterskin is partly drained; say "You drink a long draught."

After printing the name of the waterskin: say " ([waterskin condition])"

Campsite is a room. "It is solid night now, and the stars have come out. Unfamiliar stars. On the other side of the valley -- a valley round-bottomed but shallow, like a soup bowl -- burn other campfires, most likely bandits. Their voices do not carry, but the smoke rises and obscures the starlight over that way."

A sleepsack is an enterable container in the Campsite. "Your sleepsack is laid out in a pocket of sandy soil and coarse grass."

The sandy soil, the stars, the distant campfires, and the coarse grass are scenery in the Campsite. Understand "smoke" as the campfires. Instead of listening in the presence of your campfire: say "All you hear are the reassuring snaps and cracks of the sticks in your fire." Understand "campfires" or "fires" as the distant campfires.

Your campfire is scenery in the Campsite. Instead of pushing, pulling, turning, tasting, or touching your campfire, say "You would burn yourself." Understand "fire" as your campfire. The description of your campfire is "A reassuring protection against wild animals and cold."

The description of the stars is "You invent constellations for them. The slingshot. The scroll. The heart (upside down)."

Instead of going nowhere when the player is in Campsite:
    say "Now is not the time for wandering, alone in the dark. Better to keep here[if your campfire is visible], by the fire[end if]."

Singing is an action applying to nothing. Understand "sing" as singing.

Instead of singing:
    say "You sing, deep and low, a song from home. It is a good night for singing and the song raises your spirits."

The player carries a tinderbox. The tinderbox contains a flint, a steel, some tinder, and a patch of carbonized cloth. The description of the flint is "A flat grey stone with flaked edges." The description of the steel is "Curved so that you can hold it over the knuckles of your right hand and strike it against the flint. There is a knack to it. Those without the knack end up with bloody knuckles and no fire." The steel is wearable. The description of the tinder is "Dried grass and similar." The description of the cloth is "The little, precious, spark-preserving scraps without which the fire would never begin."

Instead of attacking the flint when the steel is not worn by the player:
    say "You must wear the steel over your knuckles, in order to hit the flint at the best angle."

Instead of attacking the flint when the steel is worn and the cloth is not in the location:
    say "Though you strike the flint sharply with the steel and throw sparks, they have nothing to catch on, since the patch of cloth does not lie beneath."

Instead of attacking the flint when the steel is worn and the cloth is in the location and the cloth is not unlit:
    say "The patch of cloth has already caught."

Instead of attacking the flint:
    now the cloth is glowing;
    say "You strike the flint against the steel and throw sparks onto the patch of cloth; they make tiny circles of orange there, which will only prosper if blown into flame."

Realistically, we ought to attach a randomization to this so that each step of the fire-starting has a good chance of failure. But because our player may not be as patient as someone who actually needs a fire started, we allow him to succeed the first time in every case.

Ignition is a kind of value. The ignitions are whole, fading, glowing, flaming. A thing has an ignition.

Blowing on is an action applying to one thing. Understand "breathe on [something]" or "blow on [something]" as blowing on.

Instead of blowing on the whole cloth:
    say "There is no point, since no sparks have caught there."

Instead of blowing on the fading cloth:
    now the cloth is flaming;
    say "You blow on the faint sparks on the cloth and turn them into the beginnings of flame."

Instead of burning the whole tinder:
    if the cloth is not flaming:
        say "The patch of cloth must catch flame before you can light anything with it.";
    otherwise:
        now the tinder is flaming;
        now the cloth is nowhere;
        say "You light the tinder with the patch of cloth, and have the elements of a fire."

Every turn:
    unless the cloth is flaming or the cloth is whole:
        now the ignition of the cloth is the ignition before the ignition of the cloth;
        say "Now the patch of cloth is [ignition of the cloth]."

Some kindling is in the campsite.

Instead of burning the whole kindling:
    if the tinder is not flaming:
        say "You need the tinder to be flaming, first.";
    otherwise:
        now the tinder is nowhere;
        now the kindling is nowhere;
        move the campfire to the location;
        say "You succeed in lighting yourself a proper campfire.";
        now the printed name of Campsite is "By The Campfire".

Test me with "i / drink water / i / drink water / i / wear steel / get flint / get cloth / drop cloth / get tinder / hit flint / blow on cloth / burn tinder / burn kindling / look".

150. Bruneseau's Journey ★★

"Sire," said the Minister of the Interior to Napoleon, "yesterday I saw the most intrepid man in your Empire." - "What man is that?" said the Emperor brusquely, "and what has he done?" - "He wants to do something, Sire." - "What is it?" - "To visit the sewers of Paris."

This man existed and his name was Bruneseau.

- Victor Hugo, Les Miserables

Let's say that our intrepid explorer has a candle that can be lit and blown out again, and should accordingly appear unlit, burning, or partly burnt:

paste.png "Bruneseau's Journey"

The Sewer Beneath St Denis is a room. "A narrow, stone-lined passageway, with only a little ledge to walk above the level of the refuse that flows down towards the Seine."

The candle is carried by the player. The description of the candle is "A candle, [if the candle has been lit]partially burnt[otherwise]still in pristine condition with untouched wick[end if]."

Instead of examining the lit candle, say "It burns with a pure heart."

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

Instead of burning the lit candle:
    say "The candle is already lit."

Check burning:
    if the noun is not the candle, say "[The noun] cannot profitably be set on fire."

Carry out burning the candle:
    now the candle is lit.

Report burning:
    if the candle had been lit, say "You relight the candle.";
    otherwise say "You light the candle for the first time.".

Understand "blow out [something]" as blowing out. Understand "blow [something] out" as blowing out. Blowing out is an action applying to one thing.

Carry out blowing out the candle:
    now the candle is unlit.

Report blowing out:
    if the noun is the candle and the candle was lit, say "You blow out [the noun].";
    otherwise say "You blow on [the noun], to little effect."

Test me with "x candle / light candle / x candle / blow out candle / x candle".

We must be careful: "if the noun was lit" would throw errors because past-tense rules can only be applied to specific items, not to variables that could be anything.

418. The Cow Exonerated ★★

Here we create a class of matches that can be used to burn other objects. Our objectives are as follow:

Burned objects other than matches should be removed from play instantly (just as edible objects are instantly eaten). We could give everything its own burning duration, but that complicates matters and allows for fire to spread from one object to another; for an example of how to do that, see the example "In Fire or in Flood".

Matches should be described to show whether they are burning or extinguished, and when the parser chooses one of several identical matches, it should make very clear which match it has selected.

The game must sensibly select and, if necessary, automatically light new matches to carry out a >BURN THING command.

The matches must burn for a set number of turns before going out, never to be used again.

And finally, the part for which the text will be useful: when several matches go out in the same turn, we want the game to print

Four matches go out.

rather than

A match goes out.
A match goes out.
A match goes out.
A match goes out.

This last function appears down in Section 3, if we wish to skip ahead and look at it.

paste.png "The Cow Exonerated"

Section 1 - Simple Burning

Understand the commands "light" and "burn" as something new.

Understand "burn [something] with [strikable-match]" as burning it with. Understand "burn [something] with [something preferably held]" as burning it with. Burning it with is an action applying to one thing and one carried thing.

Understand the command "light" as "burn".

A thing can be flammable or impervious. A thing is usually impervious.

Check burning something with something (this is the burn only with flaming matches rule):
    if the second noun is not a strikable-match, say "You can only light things with matches." instead;
    if the second noun is not flaming, say "[The second noun] needs to be burning first." instead.

Check burning something with something (this is the burn only flammable things rule):
    if the noun is impervious, say "[The noun] cannot be burned." instead.

Check burning something with something (this is the burn only things not held rule):
    say "[one of]It occurs to you to set down [the noun] before burning, just for safety's sake. [or]Again, you decide to put down [the noun] prior to burning. [or]You try setting down [the noun] as usual. [stopping][run paragraph on]";
    silently try the player dropping the noun;
    if the player encloses the noun, stop the action.

Carry out burning something with something (this is the simplistic burning rule):
    now the noun is nowhere.

Report burning something with something:
    say "You burn up [the noun]."

Rule for implicitly taking the second noun while burning something with something which is not a strikable-match:
    say "You can only light things with matches.";
    stop the action.

Section 2 - Matches

The word "matches" is used by Inform to compare snippets of text (see "Reading a command" in the Activities chapter). This can sometimes cause awkwardness if we also have a kind called "match", so for the occasion we will give our matches a more specialized name, never visible to the player:

A strikable-match is a kind of thing. The plural of strikable-match is s-matches.

A strikable-match has a number called duration. The duration of a strikable-match is usually 3.

Rule for printing the name of a strikable-match: say "match".
Rule for printing the plural name of a strikable-match: say "matches".

Understand "match" as a strikable-match. Understand "matches" as a strikable-match.

Flame-state is a kind of value. The flame-states are burnt, flaming, and new. Understand "burning" or "lit" as flaming. Understand "unused" as new.

A strikable-match has a flame-state. A strikable-match is usually new. Understand the flame-state property as describing a strikable-match.

Before printing the name of a strikable-match while asking which do you mean:
    say "[flame-state] ".

Before printing the name of a strikable-match while taking inventory:
    say "[flame-state] ".
Before printing the plural name of a strikable-match while taking inventory:
    say "[flame-state] ".

Before printing the name of a strikable-match while clarifying the parser's choice of something:
    if not taking inventory, say "[flame-state] ".

After printing the name of a strikable-match (called special-target) while clarifying the parser's choice of something:
    if the player carries the special-target:
        say " you're carrying";
    otherwise if the special-target is in the location:
        say " on the ground";
    otherwise:
        say " [if the holder of the special-target is a container]in[otherwise]on[end if] [the holder of the special-target]".

Understand "strike [something]" as attacking.

Understand "strike [strikable-match]" as striking. Striking is an action applying to one carried thing.

Understand "burn [strikable-match]" as striking.

Does the player mean striking a new strikable-match:
    it is very likely.

Does the player mean striking a burnt strikable-match:
    it is unlikely.

Check striking a strikable-match (this is the strike only new matches rule):
    if the noun is burnt, say "[The noun] has already burnt down and cannot be relit." instead;
    if the noun is flaming, say "[The noun] is already burning." instead.

Carry out striking a strikable-match (this is the standard striking rule):
    now the noun is flaming;
    now the noun is lit.

Report striking a strikable-match (this is the standard report striking rule):
    say "You light [the noun]."

Before burning something with a new strikable-match (this is the prior lighting rule):
    say "(first [if the player does not carry the second noun]taking and [end if]lighting [the second noun])[command clarification break]";
    silently try striking the second noun;
    if the second noun is not flaming, stop the action.

Rule for implicitly taking a strikable-match (called target) while striking:
    try silently taking the target.

Does the player mean burning something with a flaming strikable-match:
    it is very likely.

Does the player mean burning something with a new strikable-match:
    it is likely.

Does the player mean burning something with a burnt strikable-match:
    it is unlikely.

Instead of burning a burnt strikable-match with something:
    say "[The noun] is completely consumed and cannot be relit."

Section 3 - Putting the Matches Out

Every turn:
    let N be 0; [here we track how many matches are being put out during this turn, so that we don't have to mention each match individually if several go out during the same move]
    repeat with item running through flaming s-matches:
        decrement the duration of the item;
        if the duration of the item is 0:
            now the item is burnt;
            now the item is unlit;
            if the item is visible, increment N;
    if N is 1:
        say "[if the number of visible flaming s-matches is greater than 0]One of the matches [otherwise if the number of burnt visible s-matches is greater than 1]Your last burning match [otherwise]The match [end if]goes out.";
    otherwise if N is greater than 1:
        let enumeration be "[N in words]";
        if N is the number of visible s-matches:
            if N is two, say "Both";
            otherwise say "All [enumeration]";
        otherwise:
            say "[enumeration in title case]";
        say " matches go out[if a visible strikable-match is flaming], leaving [number of visible flaming s-matches in words] still lit[end if]."

Section 4 - Scenario

Old Chicago is a room.

The player carries a flammable thing called a log. Understand "wooden" and "wood" as the log.

The player carries two s-matches. The matchbox is an open openable container. It contains five s-matches. The player carries the matchbox.

When play begins:
    now every strikable-match carried by the player is flaming;
    now every strikable-match carried by the player is lit.

Test me with "i / burn match / i / i / burn log with match / burn matchbox with match / i".

401. In Fire or in Flood ★★★

paste.png "In Fire or in Flood"

Part I - Rules for combustion

Heat is a kind of value. The heats are whole, damp, and flaming. A thing has a heat. A thing is usually whole.

A thing has a number called endurance. The endurance of a thing is usually 5. A thing has a number called turns of burning. A thing can be flammable or flame-retardant.

Before printing the name of something flaming:
    say "flaming ".

Before burning something when the player is not carrying something flaming:
    if a flaming portable thing (called the lighter) is touchable:
        say "(with [the lighter], which you first take)[command clarification break]";
        try taking the lighter.

Instead of burning something when the player is not carrying something flaming:
    say "You would first need a fire source."

Instead of burning something flame-retardant:
    say "[The noun] is not the sort of thing that catches fire."

Instead of burning something flammable when the player is carrying something flaming (called the flame source):
    say "You light [the noun] with [the flame source].";
    now the heat of the noun is flaming.

Instead of burning something when the player is in the noun:
    say "That seems dangerous given that you yourself are in [the noun]."

Instead of burning something when the player is on the noun:
    say "That seems dangerous given that you yourself are on [the noun]."

Instead of examining something:
    say "Hm, the [printed name] appears to be [heat]."

Before taking a flaming thing:
    let turns remaining be the endurance of the noun minus the turns of burning of the noun;
    if turns remaining is less than two, say "There's no portion of [the noun] sufficiently cool for you to pick up." instead.

But that's only a small part of the battle. The thing about fire is that it keeps on doing fiery things even when the player is otherwise occupied: destroying items that are on fire, and spreading to other things nearby. So we need a set of rules for the fire's behavior.

Every turn when something is flaming:
    follow the fire rules.

The fire rules is a rulebook.

A fire rule (this is the can't hold flaming objects rule):
    repeat with item running through flaming things:
        if the item is held by the player:
            let turns remaining be the endurance of the item minus the turns of burning of the item;
            if turns remaining is less than two:
                say "[The item] becomes too hot to hold! ";
                try dropping the item;
                if the item is held by the player, say "This is certainly painful."

A fire rule (this is the flames spread rule):
    repeat with item running through flaming things:
        if the turns of burning of the item is one:
            spread the flames from the item.

A fire rule (this is the fire destroys things rule):
    now started printing is false;
    repeat with item running through flaming things:
        increment the turns of burning of the item;
        if the turns of burning of the item is greater than the endurance of the item, destroy the item;
    if started printing is true, say "[paragraph break]";
    now started printing is false.

Because we've labelled all the fire rules, we could swap their order, or turn some of them off, while allowing the others run as usual. For instance, if there were a pair of fireproof gloves in the game, we might want to turn off the "can't hold flaming objects rule" whenever the player is wearing them.

This sort of flexibility is especially useful in the context of extensions. Someone writing an extension about burning would have no way of anticipating the need for a Fireproof Gauntlet of Thog, but the author would nonetheless be able to implement one easily.

Definition: a thing is vulnerable if it is flammable and it is whole.

The contact between things is a critical factor when it comes to fire, so we might add a couple of conditional relations do determine what is touching what.

Reliance relates a thing (called X) to a thing (called Y) when X is part of Y or X is in Y or X is on Y. The verb to be relying on means the reliance relation.

Contact relates a thing (called X) to a thing (called Y) when X is relying on Y or Y is relying on X. The verb to be joined to means the contact relation.

Having these at our disposal makes it much tidier to write what happens next:

To spread the flames from (item - a thing):
    now started printing is false;
    if the item is joined to a flammable whole thing (called the sacrifice):
        if the sacrifice is visible:
            now started printing is true;
            say "Flames engulf [the list of flammable whole things which are joined to the item].";
        now all the flammable whole things joined to the item are flaming.

Started printing is a truth state that varies. Started printing is false.

To destroy (item - a thing):
    let home be the holder of the item;
    if the item is part of something (called the superstructure), let home be the holder of the superstructure;
    if the item is visible:
        now started printing is true;
        say "[The item] burns away[if something is relying on the item], leaving [a list of things which are relying on the item] behind[end if]. ";
    if something is relying on the item,
        now all the things which are relying on the item are in the home;
    now the item is nowhere;
    now the item is damp;
    now every flaming thing which is part of the item is damp.

To destroy (item - a door):
    let home be the holder of the item;
    if item is visible:
        now started printing is true;
        say "[The item] burns away[if something flame-retardant is part of the item], leaving [a list of flame-retardant parts of the item] behind[end if]. ";
    if home is a room, now all of the flame-retardant parts of the item are in the home;
    now the item is damp;
    now the item is open;
    now the item is unopenable.

Before printing the name of a damp door:
    say "burnt-out frame of ".

Instead of opening or closing a damp door:
    say "[The noun] can no longer be opened or closed in any meaningful sense."

Instead of doing something other than examining or dropping to a flaming thing when the turns of burning of the noun is greater than 1:
    say "Fire has too thoroughly engulfed [the noun] for that to be a good idea."

Instead of taking something when the noun is in a flaming thing (called the receptacle):
    say "You don't quite dare reach into [the receptacle]."

Instead of touching something which is within a flaming thing (called the receptacle):
    say "It seems a little risky since [the receptacle] is on fire."

Instead of turning something when the noun is contained in a flaming thing (called the receptacle):
    say "It seems a little risky since [the receptacle] is on fire."

Instead of pushing or pulling something when the noun is inside a flaming thing (called the receptacle):
    say "[The receptacle] deters you."

Before burning something which is in a container when the holder of the noun contains the player:
    say "This could make things toasty for you..."

And that completes the rules which cover burning: things can catch fire, fire will spread, and gradually consume the world in flames. All of that was general and could be used in any setting, but we now provide a small game to show it off.

Part II - Escape from the Library of the Dead

The Library of the Dead is a room. "This room -- little, dank, stone -- is filling with some miasma you do not quite dare breathe. It is imperative that you get out."

The desk is a flammable supporter in the Library. A drawer is part of the desk. The drawer is a flammable closed container. It is openable, lockable, and locked. The desk is scenery.

A box is in the Library. A metal hinge is part of the box. The hinge is flame-retardant. The box is open, flammable, and openable. The shroud of Laertes is a flammable thing in the box.

Instead of examining something when something is part of the noun:
    say "You note [the list of things which are part of the noun]."

The world's last manuscript of the Psychagogoi by Aeschylus is on the desk. The manuscript is flammable. The manuscript has endurance 1.

The torch is a flammable flaming thing carried by the player. It has endurance 60. The asbestos sack is a flame-retardant player's holdall in the drawer.

The trapdoor is up of the Library and east of the Plaza. The trapdoor is a door. It is flammable, closed, lockable, and locked. "A trapdoor in the ceiling is your only hope of escape[if flaming]. Fortunately, it is rapidly burning through[end if]." The trapdoor has endurance 15.

Instead of going through the closed trapdoor, say "[The trapdoor] is closed."

We can then add a special fire rule to handle the trapdoor, which will be called as part of the same sequence. Again, this would be most important if the fire rules were part of a standard extension, and the trapdoor fire rule the author's own addition.

A fire rule:
    if the trapdoor is flaming and a random chance of 1 in 3 succeeds:
        let the caught thing be a random flammable whole thing which can be touched by the trapdoor;
        if the caught thing is a thing:
            say "A spark from [the trapdoor] catches [the caught thing]!";
            now the caught thing is flaming.

Instead of going to the Plaza:
    say "Out at last!";
    end the story finally.

Test me with "get manuscript / get shroud / light desk / look / g / open drawer / look / g / g / g / get sack / put shroud in sack / put manuscript in sack / close sack / light trapdoor / look / g / g / g / g / g / g / g / g / g / g / g / g / g / g / up".

RB §10.9. Heat

Since we prefer not to simulate burnt skin, and it is unsporting to kill a player outright merely for touching a hot object, heat is mostly used as a reason why something cannot be picked up at a given moment. This very basic puzzle is demonstrated in Grilling.

With the naked eye, it is not always easy to detect what is too hot to touch - a point made in both Masochism Deli, where the only solution is to keep picking up potatoes until one doesn't burn, and in Hot Glass Looks Like Cold Glass ★★★, where infrared goggles turn the scales.

If a hot object is not to be touched, will it stay hot forever? It might well, if it is a steak on an electric grill, but not if it is a recently-baked apple pie sitting on a window-sill. Entropy simulates the gradual return of temperature to equilibrium.

See also

Electricity and Magnetism for items which shouldn't be touched because they are hot in a different way

Examples

84. Grilling

Descriptions of objects can be used in "Instead" rules: we can not only say "Instead of taking the steak", but also "Instead of taking something" or "Instead of taking something which is on the grill".

That last rule is useful if, for example, we want to prevent the player from interacting with anything on a specific supporter:

paste.png "Grilling"

The Patio is a room. The Patio contains a grill and an ice chest. The ice chest contains a cold beer. On the grill are a steak and a hot dog.

Mom is a woman in the Patio.

Instead of taking something which is on the grill:
    say "'Hey, you'll burn yourself,' says Mom."

Test me with "get steak / get all from grill / get all".

We could just as easily adapt this rule to affect a container: "Instead of taking something which is in the ice chest," for example.

Note also that in older versions of Inform, the pattern "get all from..." was treated differently from "get steak", and had to be accounted for separately. This is no longer the case; this instead of taking... rule will handle all the phrasings which the player might use to try to acquire this object.

182. Entropy

paste.png "Entropy"

Heat is a kind of value. The heats are frosty, cold, cool, room temperature, warm, hot, and scalding. Everything has a heat. The heat of a thing is usually room temperature.

Every turn:
    repeat with item running through things which are not in an insulated container:
        if the heat of the item is greater than room temperature, now the heat of the item is the heat before the heat of the item;
        if the heat of the item is less than room temperature, now the heat of the item is the heat after the heat of the item.

Definition: a container is insulated if it is closed and it is opaque.

The vacuum thermos is an opaque closed openable container carried by the player. In the vacuum thermos is a frosty thing called an ice cube.

Every turn:
    if the heat of the ice cube is greater than cold:
        if the ice cube is visible, say "The ice cube melts! 'HA ha,' says Maxwell, in a very unsporting, some might say demonic, way.";
        now the ice cube is nowhere.

Before printing the name of something: say "[heat] ".

Equilibrium is a room. "A perfectly smooth chamber sealed from the outside world. You can't at this moment work out where the exit is, though possibly that is just because the lighting is so very very even and diffuse. And doesn't come from anywhere that you can see, either."

Maxwell is a man in Equilibrium. "Maxwell perches awkwardly on a stool across from you[if Maxwell has something], holding [a list of things carried by Maxwell][end if]." He is carrying a box of Chinese food. The Chinese food is scalding. "A discarded [item described] lies on the floor." The description of Maxwell is "He has the faintly peevish look of one who has not been properly fed."

Every turn when Maxwell has the food:
    if the heat of the Chinese food is greater than warm, say "Maxwell takes a bite, and swears.";
    if the heat of the Chinese food is warm, say "Maxwell eats as fast as he can, enjoying the food while it's at just the right temperature.";
    if the heat of the Chinese food is less than warm:
        say "Maxwell sadly stabs at his leftovers with a chopstick, but does not try to eat any more.";
        move the food to the location.

Test me with "z / z / open thermos / close thermos / open thermos".

326. Masochism Deli

Here the player has several potatoes; we would like to make him more likely to drop the hot one, and more likely to pick up the cold one, all else being equal. At the same time, we want to phrase our rules so that they don't make the player try to take something he's already holding, or drop something he isn't.

So:

paste.png "Masochism Deli"

The Masochism Deli is a room. "Recent restructurings of corporate policy restrict the 'lunch hour' to exactly thirty-two minutes, which means that no one has time to go out. Instead, you and your coworkers eat here, in the company's very own themed lunch room."

The plural of potato is potatoes. A potato is a kind of thing. A potato is edible.

Temperature is a kind of value. The temperatures are hot and cold. A potato has a temperature. A potato is usually cold.

Understand the temperature property as describing a potato. Before printing the name of a potato (called subject): say "[temperature of subject] ". Before printing the plural name of a potato (called subject): say "[temperature of subject] ".

Does the player mean dropping a hot potato which is carried by the player: it is very likely.

Does the player mean taking a cold potato which is not carried by the player: it is very likely.

The player carries three potatoes.

After dropping a hot potato:
    say "The guy from Cube B sneers at your lack of potato-holding stamina."

When play begins: now a random potato is hot.

Test me with "inventory / drop potato / g / g / get potato / g / i / get potato".

331. Hot Glass Looks Like Cold Glass ★★★

Suppose we have a situation where the player is allowed to talk about the heat of an object only if he's properly equipped to detect it.

paste.png "Hot Glass Looks Like Cold Glass"

Use scoring.

Heat is a kind of value. The heats are hot, warm, room temperature, and cold. A thing has a heat.

Understand the heat property as referring to a thing when the player wears the infrared goggles.

The Test Kitchen is a room. "Your own personal lab, ready for scrupulously scientific recipe research. You hope. The previous three runs of this did not go well." The pair of infrared goggles is carried by the player. The description is "A pair of head-mounted IR goggles which look very foolish when worn." The goggles are wearable.

A glass dish is a kind of container. A glass dish is transparent. Three room temperature glass dishes are on the counter. Two hot glass dishes are on the counter. Two cold glass dishes are on the counter. The counter is scenery in the Test Kitchen.

Instead of doing something other than examining to a hot glass dish:
    say "Ow! Crikey! You swear, and Claudia makes a sympathetic hiss. 'You're going to have a mark from that for sure,' she comments.";
    decrease the score by 2.

Instead of doing something when a hot glass dish is the second noun:
    say "You brush [the second noun], and wince, but manage to conceal that from Claudia.";
    decrement the score.

Before printing the name of a glass dish when the player wears the goggles: say "[heat] "

Before printing the plural name of a glass dish when the player wears the goggles: say "[heat] "

So far, so good. Now, what if the player tries to GET HOT DISH when the goggles are off? "You can't see any such thing." doesn't seem like quite the right response: he can see such a thing. He just doesn't know which it is.

We could go on to write a mistake rule that would scold the player for trying "get [heat] [text]" when not wearing the goggles. The problem is that this would not cover any other phrasing of the command, nor would it account for all the many other things the player might try to do with an object specified by heat.

What we really want is to catch all instances of the player using the property name when not allowed to do so; and for this purpose we can borrow a trick from the chapter on Activities:

After reading a command:
    if the player wears the goggles, make no decision;
    if the player's command includes "[heat]":
        say "Without the IR goggles on, you cannot tell hot things from cold at sight.";
        rule succeeds.

Claudia is a woman in the Test Kitchen. "Your assistant Claudia stands by with [a list of things carried by Claudia]." The description of Claudia is "Infinitely patient and a very good stenographer. She is studiously avoiding giving you any sort of look that might be construed as mocking." Claudia carries a notepad, a brined chicken breast, a blowtorch, and a cup of heavy cream.

Instead of asking Claudia for something which is carried by Claudia:
    move the second noun to the player;
    say "'Check, [second noun],' repeats Claudia, in the tone of one who has seen too many medical dramas. She does hand it over, though."

Instead of asking Claudia for something:
    say "She clears her throat faintly and glances at [the second noun], as though to say that it's not hers to give."

Test me with "get all / drop all / look / wear goggles / look / ask claudia for cream / put cream in hot dish / put cream in cold dish / remove goggles / get hot dish".

RB §10.10. Magic (Breaking the Laws of Physics)

Every previous section of this chapter has been about adding further realism constraints to Inform, to give it a more advanced understanding of physics (and chemistry). But Inform has plenty of physical laws built into it already, even if they are more mundane: inanimate objects do not spontaneously move or change, one solid object cannot pass through another, there are opaque barriers through which light cannot pass, and so on. These rules stop many attempted actions. (GO EAST - "The oak door is closed." GET EMERALD - "You can't, since the glass display case is in the way.")

In the real world, physics is not negotiable. ("Gravity: it's not just a good idea, it's the law.") But in stories, magic can sometimes happen, and in these examples some of the rules built into Inform are waived in special circumstances, which in effect cancel certain physical laws. Very many other magical tricks could be achieved: if you want to make a given command work despite realism constraints, try typing ACTIONS - a testing command which reveals what is happening behind the scenes - and then typing the command you want. This should reveal which named rule is stopping it: you can then try suspending that rule, and seeing if the effect now works.

See also

Magic Words for ways to create new single-word spell commands

Examples

215. Magneto's Revenge

paste.png "Magneto's Revenge"

The School for Gifted Youngsters is a room. Kitty Pryde is a woman in the School for Gifted Youngsters. "Kitty Pryde waits for you to say why you summoned her out of class." The description is "You see nothing special about Kitty Pryde. But that is only because she has learned to conceal her mutant powers: in fact she has the alternative name Shadowcat, and the ability to phase through solid objects."

The glass box is a container in the School for Gifted Youngsters. It is closed, openable, and transparent. In the box is a quantity of poisonous gas. In the box is a thing called the message from Magneto.

Instead of examining the message when the player is not carrying the message:
    say "You'd need to be holding it before you could read it."

Instead of opening the glass box: say "You're deterred by the swirling bottle-green mist within."

Check someone taking the gas (this is the gaseous object rule): rule fails.

Unsuccessful attempt by someone taking the gas: say "The gas isn't something one can pick up in one's bare hands."

Every turn:
    if the player can touch the gas:
        say "The gas has reached your lungs!";
        end the story.

A rule for reaching inside something:
    if the person reaching is Kitty, allow access.

Persuasion rule for asking someone to try doing something: persuasion succeeds.

Test me with "get message / kitty, get message / open box / kitty, open box".

Now the player can get Kitty to take the message without releasing the poisonous gas:

Kitty Pride waits for you to tell her why you summoned her out of class.

You can also see a glass box (closed) (in which are some poisonous gas and a message from Magneto) here.

>kitty, get message
Kitty Pryde picks up a message from Magneto.

225. Interrogation

paste.png "Interrogation"

The X-Ray Vision Wand is carried by the player.

Instead of waving the X-Ray Vision Wand:
    say "Disappointingly, nothing happens."

Instead of waving the X-Ray Vision Wand when the player can see someone who is concealing something:
    say "The wand glows green. Immediately you see on the monitor [a list of things which are concealed by people who can be seen by the player]."

After printing the name of a thing (called target) which is carried by someone while waving the wand:
    say " (carried by [a random person who carries the target])"

The Interrogation Chamber is a room. "Despite its gothic name, this room is a rather civilized place for your work, with large plate-glass windows and a fitted carpet."

A thing can be secret or obvious. A thing is usually obvious.

Brian is in the Interrogation Chamber."Brian lounges against the wall." Brian carries a quantity of plastic explosive. The explosive is secret.

Janine is in the Interrogation Chamber. "Janine toys nervously with a laptop bag." Janine carries a chocolate biscuit, a laptop bag, and a microfilm. The microfilm is secret. The laptop bag is wearable. In the bag is a laptop computer.

Rule for deciding the concealed possessions of something: if the particular possession is secret, yes; otherwise no.

Instead of examining someone: say "[The noun] is openly carrying [a list of unconcealed things carried by the noun]."

Test me with "wave wand / examine janine / examine brian".

227. Transmutations

Suppose we want to have a machine in our game that can transmute one item into another, similar object with different properties: a bag of jelly beans into a bag of jewels, for instance. Thus each item will be associated with some number of equivalents -- the other objects it can turn into. This is a handy use for group relations:

paste.png "Transmutations"

Workshop is a room.

Transmutation relates things to each other in groups. The verb to become means the transmutation relation.

Definition: a thing is transmutable if it becomes more than one thing. [* It always becomes itself.]

A thing can be valuable. Something valuable called a bag of jewels is carried by the player. It becomes the bag of gunpowder and the bag of jelly beans.

A thing can be dangerous. The bag of gunpowder is a dangerous thing.

The bag of jelly beans is an edible thing.

The machine is fixed in place in the workshop.

The can't insert into what's not a container rule does nothing when inserting something into the machine.

Check inserting something which is not transmutable into the machine:
    instead say "You can't transmute that."

To decide which thing is new form of (obj - edible thing): decide on a random valuable thing which becomes obj.

To decide which thing is new form of (obj - dangerous thing): decide on a random edible thing which becomes obj.

To decide which thing is new form of (obj - valuable thing): decide on a random dangerous thing which becomes obj.

Carry out inserting something into the machine:
    now the noun is nowhere;
    now the player carries the new form of the noun.

Report inserting something edible into the machine:
    say "The machine clicks, whirrs, and spits out [a new form of the noun]. You're rich!";
    rule succeeds.

Report inserting something dangerous into the machine:
    say "The machine clicks, whirrs, and in a shower of flavor crystals, spits out [a new form of the noun].";
    rule succeeds.

Report inserting something valuable into the machine:
    say "The machine clicks, whirrs, and with a violent roar, spits out [a new form of the noun].";
    rule succeeds.

    Test me with "i / put jewels in machine / i / put gunpowder in machine / i / put beans in machine".

In this example we have only defined a single set of transmutable objects, but we could easily expand to include other groups.

(Thanks to Jesse McGrew for proposing this example.)

398. Access All Areas

If somebody tries to walk through a closed door, the "can't go through closed doors rule" usually stops them. This is a rule belonging to the "check going" rulebook. These names are fairly explanatory when written out, but hard to remember: fortunately we don't need to remember them, as the Index panel contains a full inventory of the check, carry out and report rules for every action, showing all of their names and the order in which they are checked. (We can also find out which rules are stopping an action by typing the testing command ACTIONS.)

Here we make the rule do nothing provided a condition holds:

paste.png "Access All Areas"

The extremely difficult door is north of the Standing Room and south of the Room of Walking Upside Down. It is a locked door.

The player is carrying the Pointy Hat of Liminal Transgression. The hat is wearable.

The can't go through closed doors rule does nothing when the Hat is worn.

Test me with "n / wear hat / n".

(The Pointy Hat may be useful in debugging a game, even if it never makes it into the final published work.)

RB §10.11. Mathematics

It is uncommon, but not absolutely unheard-of, to need to do detailed mathematical calculations in interactive fiction.

The Fibonacci Sequence demonstrates the calculation of a series of numbers; Sieve of Eratosthenes shows off how to calculate the prime numbers within a certain range.

Number Study demonstrates conditional relations between numbers.

Examples

240. Number Study

This is the same case given above, but expanded just slightly to demonstrate that the names of the relations can also be printed, if we like:

paste.png "Number Study"

Abstraction is a room.

Parity relates a number (called N) to a number (called M) when N minus M is even.

Joint magnitude relates a number (called N) to a number (called M) when N plus M is greater than 7.

To chart (R - a relation of numbers):
    repeat with N running from 1 to 5:
        repeat with M running from 1 to 5:
            if R relates N to M, say "[N] <=> [M] by [R][line break]";

When play begins:
    let L be { parity relation, joint magnitude relation };
    repeat with R running through L:
        chart R.

As this shows, we can even form lists of relations. The kind of L is "list of relations of numbers".

437. The Fibonacci Sequence

Fibonacci (a posthumous nickname) spread Arabic mathematical learning across Europe in the 13th century, and it's curious that his name lives on only for a single sequence.

paste.png "The Fibonacci Sequence"

Pisa is a room. Leonardo Fibonacci is a man in Pisa. "The modest Italian mathematician, Leonardo Fibonacci (1170-1250), beams at you."

Sequencing is an action applying to one number. Understand "sequence [number]" as sequencing.

Instead of sequencing, say "You make a feeble attempt, sketching in the sand, but it goes nowhere. Leonardo is sympathetic. 'Often goes wrong for me, too, actually. I didn't even invent the thing - the ancient Indians knew about it first.'"

Persuasion rule for asking Leonardo to try sequencing: persuasion succeeds.

Report Leonardo sequencing:
    let N be the number understood;
    say "Leonardo scratches his head and makes self-deprecating remarks, before coming up with [the first N terms of the Fibonacci sequence]."

An array need not be fixed in length, as the following example shows:

To decide what list of numbers is the first (F - a number) terms of the Fibonacci sequence:
    let the Fibonacci sequence be {1, 1};
    let N be 3;
    while N < F:
        let the last term be entry (N - 1) of the Fibonacci sequence;
        let the penultimate term be entry (N - 2) of the Fibonacci sequence;
        let the next term be the last term plus the penultimate term;
        add the next term to the Fibonacci sequence;
        increment N;
    decide on the Fibonacci sequence.

Test me with "sequence 20 / leonardo, sequence 20".

The result of "the first 20 terms of the Fibonacci sequence" is "1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584 and 4181". This is a sequence which has a knack of turning up in odd places - it was found in the 1970s to be related to the rings of florets in a sunflower, for instance - and here it is in a book about interactive fiction.

438. Sieve of Eratosthenes

In the words of Wikipedia: "Eratosthenes of Cyrene (Greek Eρατοσθένης; 276 BC-194 BC) was a Greek mathematician, poet, athlete, geographer and astronomer." In the words of Tom Lehrer: "It's people like that who make you realise how little you've achieved in life."

A prime number is a number greater than 1 which is not a multiple of anything, so we can find the primes by starting with all the numbers and sieving out all the multiples of 2, then all the multiples of 3, and so on. Here we make our sieve of the unacceptable numbers (the "composite" or non-prime ones) first, then form a list of all the numbers, then sieve out the composites: what are left must be the primes.

paste.png "Sieve of Eratosthenes"

Alexandria is a room. Eratosthenes is a man in Alexandria. "The haughty Greek mathematician, Eratosthenes, glowers at you."

Sieving is an action applying to one number. Understand "sieve [number]" as sieving.

Instead of sieving, say "You make a feeble attempt, sketching in the sand, but it goes nowhere. Eratosthenes smirks. 'I expect your friends call you gamma, then?'"

Persuasion rule for asking Eratosthenes to try sieving: persuasion succeeds.

Report Eratosthenes sieving:
    let N be the number understood;
    let the composites be a list of numbers;
    let I be 2;
    while I times I is at most N:
        if I is not listed in the composites:
            let J be I times 2;
            while J is at most N:
                add J to the composites, if absent;
                increase J by I;
        increment I;
    sort the composites;
    let the primes be a list of numbers;
    repeat with P running from 2 to N:
        add P to the primes;
    remove the composites from the primes;
    say "Eratosthenes sketches lines in the sand with the air of much practice. 'The primes up to [N] are [the primes]. The composites are [the composites].'"

Test me with "sieve 10 / eratosthenes, sieve 100".

While this could all be done more efficiently with an array, that's only because what we are sieving are numbers: sieving is a technique which can be used for non-numerical decisions, too.