kpsewhich now expects "-var-value" instead of "-var".
[ibg.git] / chapters / 06.rst
1 ==============================
2  William Tell: a tale is born
3 ==============================
4
5 .. highlight:: inform
6
7 .. epigraph::
8
9    | |CENTER| *K was King William, once governed the land;*
10    | |CENTER| *L was a lady, who had a white hand.*
11
12 .. only:: html
13
14    .. image:: /images/picK.png
15       :align: left
16
17 |K|\eeping up the momentum, this chapter (and the three which follow) works
18 steadily through the design of the "William Tell" game that we encountered
19 right at the start of this guide. Many of the principles are the same as
20 the ones we explained when designing Heidi and her forest, so we'll not
21 linger on what should be familiar ground.  "William Tell" is a slightly
22 longer and more complex game, so we'll move as swiftly as possible to
23 examine the features which are new.
24
25 Initial setup
26 =============
27
28 Our starting point is much the same as last time.  Here's a basic
29 ``Tell.inf``:
30
31 .. include:: /config/typethis.rst
32
33 ::
34
35    !% -SD
36    !===========================================================================
37    Constant Story "William Tell";
38    Constant Headline
39                "^A simple Inform example
40                 ^by Roger Firth and Sonja Kesserich.^";
41    Release 3; Serial "040804";     ! for keeping track of public releases
42
43    Constant MAX_SCORE = 3;
44
45    Include "Parser";
46    Include "VerbLib";
47
48    !===========================================================================
49    ! Object classes
50
51    !===========================================================================
52    ! The game objects
53
54    !===========================================================================
55    ! The player's possessions
56
57    !===========================================================================
58    ! Entry point routines
59
60    [ Initialise;
61        location = street;
62        lookmode = 2;           ! like the VERBOSE command
63        move bow to player;
64        move quiver to player; give quiver worn;
65        player.description =
66            "You wear the traditional clothing of a Swiss mountaineer.";
67        print_ret "^^
68            The place: Altdorf, in the Swiss canton of Uri. The year is 1307,
69            at which time Switzerland is under rule by the Emperor Albert of
70                Habsburg. His local governor -- the vogt -- is the bullying
71                Hermann Gessler, who has placed his hat atop a wooden pole in
72                the centre of the town square; everybody who passes through the
73                square must bow to this hated symbol of imperial might.
74                ^^
75                You have come from your cottage high in the mountains,
76                accompanied by your younger son, to purchase provisions. You are
77                a proud and independent man, a hunter and guide, renowned both
78                for your skill as an archer and, perhaps unwisely (for his soldiers
79                are everywhere), for failing to hide your dislike of the vogt.
80                ^^
81                It's market-day: the town is packed with people from the
82                surrounding villages and settlements.^";
83    ];
84
85    !===========================================================================
86    ! Standard and extended grammar
87
88    Include "Grammar";
89
90    !===========================================================================
91
92 You'll see that we've marked a couple of extra divisions in the file, to
93 help organise the stuff we'll add later, but the overall structure is
94 identical to our first game.  Let's quickly point out some extra bits and
95 pieces:
96
97 * If you look at a game's banner, you'll see two pieces of information:
98   "Release" and "Serial number".
99
100   .. code-block:: transcript
101
102      William Tell
103      A simple Inform example
104      by Roger Firth and Sonja Kesserich.
105      Release 3 / Serial number 040804 / Inform v6.30 Library 6/11 SD
106
107   These two fields are automatically written by the compiler, which sets by
108   default Release to 1 and the Serial Number to today's date.  However, we
109   can explicitly override this behaviour using ``Release`` and ``Serial``,
110   to keep track of different versions of our game.  Typically, we will
111   publish several updates of our games over time, each version fixing
112   problems which were found in the previous release.  If somebody else
113   reports a problem with a game, we'd like to know exactly which version
114   they were using; so, rather than take the default values, we set our own.
115   When it's time to release a new version, all we have to do is comment out
116   the previous lines and add another below them::
117
118      !Release 1; Serial "020128";      ! First beta-test release
119      !Release 2; Serial "020217";      ! Second beta-test release
120      Release 3; Serial "020315";       ! IF Library competition entry
121
122 * We'll be implementing a simple system of awarding points when the player
123   gets something right, so we define top marks::
124
125      Constant MAX_SCORE = 3;
126
127 * The ``Initialise`` routine that we wrote last time contained only one
128   statement, to set the player's initial :var:`location`.  We do that here
129   as well, but we also do some other stuff.
130
131 * The first thing is to assign 2 to the library variable ``lookmode``.
132   Inform's default mode for displaying room descriptions is BRIEF (a
133   description is displayed only when a room is visited for the first time)
134   and, by changing this variable's value, we set it to VERBOSE
135   (descriptions are displayed on *every* visit).  Doing this is largely a
136   matter of personal preference, and in any case it's nothing more than a
137   convenience; it just saves having to remember to type VERBOSE each time
138   that we test the game.
139
140 * At the start of the game, we want Wilhelm to be equipped with his bow and
141   quiver of arrows.  The recommended way of making this happen is to
142   perform the necessary object tree rearrangement with a couple of ``move``
143   statements in the ``Initialise`` routine::
144
145      move bow to player;
146      move quiver to player;
147
148   and indeed this is the clearest way to place objects in the player's
149   inventory at the beginning of any game.
150
151   .. note::
152
153      Wait! you say.  In the previous chapter, to make an object the child
154      of another object all we needed to do was to define the child object
155      with the internal identification of the parent object at the end of
156      the header::
157
158         Object bird "baby bird" forest
159
160      Why not do that with the player?  Because the object which represents
161      the player is defined by the library (rather than as part of our
162      game), and actually has an internal ID of :obj:`selfobj`;
163      :var:`player` is a variable whose value is that identifier.  Rather
164      than worry all about this, it's easier to use the ``move`` statements.
165
166   There's one other task associated with the quiver; it's an article of
167   clothing which Wilhelm is "wearing", a state denoted by the attribute
168   :attr:`worn`.  Normally the interpreter would apply this automatically,
169   while handling a command like WEAR QUIVER, but since we've moved the
170   quiver ourselves, we also need to set the quiver's :attr:`worn`
171   attribute.  The ``give`` statement does the job::
172
173      give quiver worn;
174
175   (To clear the attribute, by the way, you'd use the statement ``give
176   quiver ~worn`` -- read that as "give the quiver not-worn"; Inform often
177   uses ``~`` to mean "not".)
178
179 .. Generated by autoindex
180 .. index::
181    pair: description; library property
182
183 * If the player types EXAMINE ME, the interpreter displays the
184   :prop:`description` property of the :var:`player` object.  The default
185   value is "As good-looking as ever", a bit of a cliché in the world of
186   Inform games.  It's easy to change, though, once you realise that, since
187   the properties of an object are variables, you can assign new values to
188   them just as you'd assign new values to :var:`location` and ``lookmode``.
189   The only problem is getting the syntax right; you can't say just::
190
191      description = "You wear the traditional clothing of a Swiss mountaineer.";
192
193   because there are dozens of objects in the game, each with its own
194   :prop:`description` property; you need to be a little more explicit.
195   Here's what to type::
196
197      player.description =
198              "You wear the traditional clothing of a Swiss mountaineer.";
199
200 * Finally, the ``Initialise`` routine ends with a lengthy ``print_ret``
201   statement.  Since the interpreter calls ``Initialise`` right at the start
202   of the game, that's the point at which this material is displayed, so
203   that it acts as a scene-setting preamble before the game gets under way.
204   In fact, everything you want set or done at the very beginning of the
205   game, should go into the ``Initialise`` routine.
206
207 The game won't compile in this state, because it contains references to
208 objects which we haven't yet defined.  In any case, we don't intend to
209 build up the game in layers as we did last time, but rather to talk about
210 it in logically related chunks.  To see (and if you wish, to type) the
211 complete source, go to :doc:`/appendices/c`.
212
213 Object classes
214 ==============
215
216 Remember how we defined the rooms in "Heidi"?  Our first attempt started
217 like this::
218
219    Object  "In front of a cottage"
220      with  description
221                "You stand outside a cottage. The forest stretches east.",
222       has  light;
223
224    Object  "Deep in the forest"
225      with  description
226                "Through the dense foliage, you glimpse a building to the west.
227                 A track heads to the northeast.",
228       has  light;
229
230    ...
231
232 and we explained that just about *every* room needs that :attr:`light`
233 attribute, or else the player would be literally in the dark.  It's a bit
234 of a nuisance having to specify that same attribute each time; what would
235 be neater would be to say that *all* rooms are illuminated.  So we can
236 write this::
237
238    Class  Room
239      has  light;
240
241     Room  "In front of a cottage"
242     with  description
243                "You stand outside a cottage. The forest stretches east.",
244      has  ;
245
246     Room  "Deep in the forest"
247     with  description
248                "Through the dense foliage, you glimpse a building to the west.
249                 A track heads to the northeast.",
250      has  ;
251
252     ...
253
254 We've done four things:
255
256 #. We've said that some of the objects in our game are going to be defined
257    by the specialised word ``Room`` rather than the general-purpose word
258    ``Object``.  In effect, we've taught Inform a new word specially for
259    defining objects, which we can now use as though it had been part of the
260    language all along.
261
262 #. We've furthermore said that every object which we define using ``Room``
263    is automatically going to have the :attr:`light` attribute.
264
265 #. We've changed the way in which we define the four room objects, by
266    starting them with our specialised word ``Room``.  The remainder of the
267    definition for these objects -- the header information, the block of
268    properties, the block of attributes and the final semicolon -- remains
269    the same; except that:
270
271 #. We don't need to explicitly include the :attr:`light` attribute each
272    time; every ``Room`` object has it automatically.
273
274 A :term:`class` is a family of closely related objects, all of which behave
275 in the same way.  Any properties defined for the class, and any attributes
276 defined for the class, are automatically given to objects which you specify
277 as belonging to that class; this process of acquisition just by being a
278 member of a class is called :term:`inheritance`.  In our example, we've
279 defined a ``Room`` class with a :attr:`light` attribute, and then we've
280 specified four objects each of which is a member of that class, and each of
281 which gets given a :attr:`light` attribute as a result of that membership.
282
283 Why have we gone to this trouble?  Three main reasons:
284
285 * By moving the common bits of the definitions from the individual objects
286   to the class definition which they share, those object definitions
287   become shorter and simpler.  Even if we had a hundred rooms, we'd still
288   need to specify ``has light`` only once.
289
290 * By creating a specialised word to identify our class of objects, we make
291   our source file easier to read.  Rather than absolutely everything being
292   an anonymous ``Object``, we can now immediately recognise that some are
293   ``Room`` objects (and others belong to the different classes that we'll
294   create soon).
295
296 * By collecting the common definitions into one place, we make it much
297   easier to make widespread modifications in future.  If we need to make
298   some change to the definition of all our rooms, we just modify the
299   ``Room`` class, and all of the class members inherit the change.
300
301 For these reasons, the use of classes is an incredibly powerful technique,
302 easier than it may look, and very well worth mastering.  From now on, we'll
303 be defining object classes whenever it makes sense (which is generally when
304 two or more objects are meant to behave in exactly the same way).
305
306 You may be wondering: suppose I want to define a room which for some reason
307 *doesn't* have :attr:`light`; can I still use the ``Room`` class?  Sure you
308 can::
309
310    Room    cellar "Gloomy cellar"
311      with  description "Your torch shows only cobwebby brick walls.",
312      has   ~light;
313
314 This illustrates another nice feature of inheritance: the object definition
315 can override the class definition.  The class says ``has light``, but the
316 object itself says ``has ~light`` (read that as "has no light") and the
317 object wins.  The cellar is dark, and the player will need a torch to see
318 what's in it.
319
320 In fact, for any object both the block of properties and the block of
321 attributes are optional and can be omitted if there's nothing to be
322 specified.  Now that the :attr:`light` attribute is being provided
323 automatically and there aren't any other attributes to set, the word
324 ``has`` can be left out.  Here's the class again:
325
326 .. include:: /config/typethis.rst
327
328 ::
329
330    Class  Room
331      has  light;
332
333 and here is how we could have used it in "Heidi"::
334
335    Room    "In front of a cottage"
336      with  description
337                "You stand outside a cottage. The forest stretches east.";
338
339    Room    "Deep in the forest"
340      with  description
341                "Through the dense foliage, you glimpse a building to the west.
342                 A track heads to the northeast.";
343
344    ...
345
346 You'll notice that, if an object has no block of attributes, the semicolon
347 which terminates its definition simply moves to the end of its last
348 property.
349
350 .. _props-class:
351
352 A class for props
353 -----------------
354
355 We use the ``Room`` class in "William Tell", and a few other classes
356 besides.  Here's a ``Prop`` class (that's "Prop" in the sense of a
357 theatrical property rather than a supportive device), useful for scenic
358 items whose only role is to sit waiting in the background on the off-chance
359 that the player might think to EXAMINE them:
360
361 .. include:: /config/typethis.rst
362
363 ::
364
365    Class    Prop
366      with   before [;
367                Examine:
368                  return false;
369                default:
370                  print_ret "You don't need to worry about ", (the) self, ".";
371             ],
372       has   scenery;
373
374 All objects of this class inherit the :attr:`scenery` attribute, so they're
375 excluded from room descriptions.  Also, there's a :prop:`before` property;
376 one that's more complex than our previous efforts.  You'll remember that
377 the first :prop:`before` we met looked like this::
378
379    before [;
380       Listen:
381         print "It sounds scared and in need of assistance.^";
382         return true;
383    ],
384
385 .. Generated by autoindex
386 .. index::
387    pair: Examine; library action
388    pair: Listen; library action
389
390 The role of that original :prop:`before` was to intercept :act:`Listen`
391 actions, while leaving all others well alone.  The role of the
392 :prop:`before` in the ``Prop`` class is broader: to intercept (a)
393 :act:`Examine` actions, and (b) all the rest.  If the action is
394 :act:`Examine`, then the ``return false`` statement means that the action
395 carries on.  If the action is ``default`` -- none of those explicitly
396 listed, which in this instance means *every* action apart from
397 :act:`Examine` -- then the ``print_ret`` statement is executed, after which
398 the interpreter does nothing further.  So, a ``Prop`` object can be
399 EXAMINEd, but any other action addressed to it results in a "no need to
400 worry" message.
401
402 That message is also more involved than anything we've so far displayed.
403 The statement which produces it is::
404
405    print_ret "You don't need to worry about ", (the) self, ".";
406
407 which you should read as doing this:
408
409 #. display the string "You don't need to worry about ",
410
411 #. display a definite article (usually "the") followed by a space and the
412    external name of the object concerned,
413
414 #. display a period, and
415
416 #. display a newline and return true in the usual way for a ``print_ret``
417    statement.
418
419 The interesting things that this statement demonstrates are:
420
421 * The ``print`` and ``print_ret`` statements aren't restricted to
422   displaying a single piece of information: they can display a list of
423   items which are separated by commas.  The statement still ends with a
424   semicolon in the usual way.
425
426 * As well as displaying strings, you can also display the names of objects:
427   given the ``nest`` object from our first game, ``(the) nest`` would
428   display "the bird's nest", ``(The) nest`` would display "The bird's
429   nest", ``(a) nest`` would display "a bird's nest", ``(A) nest`` would
430   display "A bird's nest" and ``(name) nest`` would display just "bird's
431   nest".  This use of a word in parentheses, telling the interpreter how to
432   display the following object's internal ID, is called a :term:`print
433   rule`.
434
435 .. Generated by autoindex
436 .. index::
437    pair: self; library variable
438
439 * There's a library variable :var:`self` which always contains the internal
440   ID of the current object, and is really convenient when using a
441   ``Class``.  By using this variable in our ``print_ret`` statement, we
442   ensure that the message contains the name of the appropriate object.
443
444 Let's see an example of this in action; here's a ``Prop`` object from
445 "William Tell"::
446
447    Prop    "south gate" street
448      with  name 'south' 'southern' 'wooden' 'gate',
449            description "The large wooden gate in the town walls is wide open.",
450            ...
451
452 If players type EXAMINE GATE, they'll see "The large wooden gate..."; if
453 they type CLOSE GATE then the gate's :prop:`before` property will step in
454 and display "You don't need to worry about the south gate", neatly picking
455 up the name of the object from the :var:`self` variable.
456
457 The reason for doing all this, rather than just creating a simple scenery
458 object like Heidi's ``tree`` and ``cottage``, is to support EXAMINE for
459 increased realism, while clearly hinting to players that trying other verbs
460 would be a waste of time.
461
462 A class for furniture
463 ---------------------
464
465 .. Generated by autoindex
466 .. index::
467    single: NPC
468    pair: static; library attribute
469
470 The last class for now -- we'll talk about the ``Arrow`` and ``NPC``
471 classes in the next chapter -- is for furniture-like objects.  If you label
472 an object with the :attr:`static` attribute, an attempt to TAKE it results
473 in "That's fixed in place" -- acceptable in the case of Heidi's branch
474 object (which is indeed supposed to be part of the tree), less so for items
475 which are simply large and heavy.  This ``Furniture`` class might sometimes
476 be more appropriate:
477
478 .. include:: /config/typethis.rst
479
480 ::
481
482    Class    Furniture
483      with   before [;
484                Take,Pull,Push,PushDir:
485                  print_ret (The) self, " is too heavy for that.";
486             ],
487       has   static supporter;
488
489 Its structure is similar to that of our ``Prop`` class: some appropriate
490 attributes, and a :prop:`before` property to trap actions directed at it.
491 Again, we display a message which is "personalised" for the object
492 concerned by using a ``(The) self`` print rule.  This time we're
493 intercepting four actions; we *could* have written the property like this::
494
495    before [;
496        Take: print_ret (The) self, " is too heavy for that.";
497        Pull: print_ret (The) self, " is too heavy for that.";
498        Push: print_ret (The) self, " is too heavy for that.";
499        PushDir: print_ret (The) self, " is too heavy for that.";
500    ],
501
502 .. Generated by autoindex
503 .. index::
504    pair: PushDir; library action
505
506 but since we're giving exactly the same response each time, it's better to
507 put all of those actions into one list, separated by commas.
508 :act:`PushDir`, if you were wondering, is the action triggered by a command
509 like PUSH THE TABLE NORTH.
510
511 Incidentally, another bonus of defining classes like these is that you can
512 probably reuse them in your next game.
513
514 Now that most of our class definitions are in place, we can get on with
515 defining some real rooms and objects.  First, though, if you're typing in
516 the "William Tell" game as you read through the guide, you'd probably like
517 to check that what you've entered so far is correct;
518 :ref:`compile-as-you-go` explains how to compile the game in its current --
519 incomplete -- state.