Revert to original minimal Inform lexer.
[ibg.git] / chapters / 06.rst
1 ==============================
2  William Tell: a tale is born
3 ==============================
4
5 .. highlight:: inform
6
7 .. epigraph::
8
9    | *K was King William, once governed the land;*
10    | *L was a lady, who had a white hand.*
11
12 .. only:: html
13
14    .. image:: /images/picK.png
15       :align: left
16
17 .. raw:: latex
18
19    \dropcap{k}
20
21 eeping up the momentum, this chapter (and the three which follow) works
22 steadily through the design of the "William Tell" game that we encountered
23 right at the start of this guide. Many of the principles are the same as
24 the ones we explained when designing Heidi and her forest, so we'll not
25 linger on what should be familiar ground.  "William Tell" is a slightly
26 longer and more complex game, so we'll move as swiftly as possible to
27 examine the features which are new.
28
29 Initial setup
30 =============
31
32 Our starting point is much the same as last time.  Here's a basic
33 ``Tell.inf``::
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 ``location``.  We do that here as
129   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 ``selfobj``; ``player`` is a
163      variable whose value is that identifier.  Rather than worry all about
164      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   ``worn``.  Normally the interpreter would apply this automatically, while
169   handling a command like WEAR QUIVER, but since we've moved the quiver
170   ourselves, we also need to set the quiver's ``worn`` attribute.  The
171   ``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 * If the player types EXAMINE ME, the interpreter displays the
180   ``description`` property of the ``player`` object.  The default value is
181   "As good-looking as ever", a bit of a cliché in the world of Inform
182   games.  It's easy to change, though, once you realise that, since the
183   properties of an object are variables, you can assign new values to them
184   just as you'd assign new values to ``location`` and ``lookmode``.  The
185   only problem is getting the syntax right; you can't say just::
186
187      description = "You wear the traditional clothing of a Swiss mountaineer.";
188
189   because there are dozens of objects in the game, each with its own
190   ``description`` property; you need to be a little more explicit.  Here's
191   what to type::
192
193      player.description =
194              "You wear the traditional clothing of a Swiss mountaineer.";
195
196 * Finally, the ``Initialise`` routine ends with a lengthy ``print_ret``
197   statement.  Since the interpreter calls ``Initialise`` right at the start
198   of the game, that's the point at which this material is displayed, so
199   that it acts as a scene-setting preamble before the game gets under way.
200   In fact, everything you want set or done at the very beginning of the
201   game, should go into the ``Initialise`` routine.
202
203 The game won't compile in this state, because it contains references to
204 objects which we haven't yet defined.  In any case, we don't intend to
205 build up the game in layers as we did last time, but rather to talk about
206 it in logically related chunks.  To see (and if you wish, to type) the
207 complete source, go to "William Tell" story on page 219.
208
209 Object classes
210 ==============
211
212 Remember how we defined the rooms in "Heidi"?  Our first attempt started
213 like this::
214
215    Object  "In front of a cottage"
216      with  description
217                "You stand outside a cottage. The forest stretches east.",
218       has  light;
219
220    Object  "Deep in the forest"
221      with  description
222                "Through the dense foliage, you glimpse a building to the west.
223                 A track heads to the northeast.",
224       has  light;
225
226    ...
227
228 and we explained that just about *every* room needs that ``light``
229 attribute, or else the player would be literally in the dark.  It's a bit
230 of a nuisance having to specify that same attribute each time; what would
231 be neater would be to say that *all* rooms are illuminated.  So we can
232 write this::
233
234    Class  Room
235      has  light;
236
237     Room  "In front of a cottage"
238     with  description
239                "You stand outside a cottage. The forest stretches east.",
240      has  ;
241
242     Room  "Deep in the forest"
243     with  description
244                "Through the dense foliage, you glimpse a building to the west.
245                 A track heads to the northeast.",
246      has  ;
247
248     ...
249
250 We've done four things:
251
252 #. We've said that some of the objects in our game are going to be defined
253    by the specialised word ``Room`` rather than the general-purpose word
254    ``Object``.  In effect, we've taught Inform a new word specially for
255    defining objects, which we can now use as though it had been part of the
256    language all along.
257
258 #. We've furthermore said that every object which we define using ``Room``
259    is automatically going to have the ``light`` attribute.
260
261 #. We've changed the way in which we define the four room objects, by
262    starting them with our specialised word ``Room``.  The remainder of the
263    definition for these objects -- the header information, the block of
264    properties, the block of attributes and the final semicolon -- remains
265    the same; except that:
266
267 #. We don't need to explicitly include the ``light`` attribute each time;
268    every ``Room`` object has it automatically.
269
270 A **class** is a family of closely related objects, all of which behave in
271 the same way.  Any properties defined for the class, and any attributes
272 defined for the class, are automatically given to objects which you specify
273 as belonging to that class; this process of acquisition just by being a
274 member of a class is called **inheritance**.  In our example, we've defined
275 a ``Room`` class with a ``light`` attribute, and then we've specified four
276 objects each of which is a member of that class, and each of which gets
277 given a ``light`` attribute as a result of that membership.
278
279 Why have we gone to this trouble?  Three main reasons:
280
281 * By moving the common bits of the definitions from the individual objects
282   to the class definition which they share, those object definitions
283   become shorter and simpler.  Even if we had a hundred rooms, we'd still
284   need to specify ``has light`` only once.
285
286 * By creating a specialised word to identify our class of objects, we make
287   our source file easier to read.  Rather than absolutely everything being
288   an anonymous ``Object``, we can now immediately recognise that some are
289   ``Room`` objects (and others belong to the different classes that we'll
290   create soon).
291
292 * By collecting the common definitions into one place, we make it much
293   easier to make widespread modifications in future.  If we need to make
294   some change to the definition of all our rooms, we just modify the
295   ``Room`` class, and all of the class members inherit the change.
296
297 For these reasons, the use of classes is an incredibly powerful technique,
298 easier than it may look, and very well worth mastering.  From now on, we'll
299 be defining object classes whenever it makes sense (which is generally when
300 two or more objects are meant to behave in exactly the same way).
301
302 You may be wondering: suppose I want to define a room which for some reason
303 *doesn't* have ``light``; can I still use the ``Room`` class?  Sure you
304 can::
305
306    Room    cellar "Gloomy cellar"
307      with  description "Your torch shows only cobwebby brick walls.",
308      has   ~light;
309
310 This illustrates another nice feature of inheritance: the object definition
311 can override the class definition.  The class says ``has light``, but the
312 object itself says ``has ~light`` (read that as "has no light") and the
313 object wins.  The cellar is dark, and the player will need a torch to see
314 what's in it.
315
316 In fact, for any object both the block of properties and the block of
317 attributes are optional and can be omitted if there's nothing to be
318 specified.  Now that the ``light`` attribute is being provided
319 automatically and there aren't any other attributes to set, the word
320 ``has`` can be left out.  Here's the class again::
321
322    Class  Room
323      has  light;
324
325 and here is how we could have used it in "Heidi"::
326
327    Room    "In front of a cottage"
328      with  description
329                "You stand outside a cottage. The forest stretches east.";
330
331    Room    "Deep in the forest"
332      with  description
333                "Through the dense foliage, you glimpse a building to the west.
334                 A track heads to the northeast.";
335
336    ...
337
338 You'll notice that, if an object has no block of attributes, the semicolon
339 which terminates its definition simply moves to the end of its last
340 property.
341
342 .. rubric:: A class for props
343
344 We use the ``Room`` class in "William Tell", and a few other classes
345 besides.  Here's a ``Prop`` class (that's "Prop" in the sense of a
346 theatrical property rather than a supportive device), useful for scenic
347 items whose only role is to sit waiting in the background on the off-chance
348 that the player might think to EXAMINE them::
349
350    Class    Prop
351      with   before [;
352                Examine:
353                  return false;
354                default:
355                  print_ret "You don't need to worry about ", (the) self, ".";
356             ],
357       has   scenery;
358
359 All objects of this class inherit the ``scenery`` attribute, so they're
360 excluded from room descriptions.  Also, there's a ``before`` property; one
361 that's more complex than our previous efforts.  You'll remember that the
362 first ``before`` we met looked like this::
363
364    before [;
365       Listen:
366         print "It sounds scared and in need of assistance.^";
367         return true;
368    ],
369
370 The role of that original ``before`` was to intercept ``Listen`` actions,
371 while leaving all others well alone.  The role of the ``before`` in the
372 ``Prop`` class is broader: to intercept (a) ``Examine`` actions, and (b)
373 all the rest.  If the action is ``Examine``, then the ``return false``
374 statement means that the action carries on.  If the action is ``default``
375 -- none of those explicitly listed, which in this instance means *every*
376 action apart from ``Examine`` -- then the ``print_ret`` statement is
377 executed, after which the interpreter does nothing further.  So, a ``Prop``
378 object can be EXAMINEd, but any other action addressed to it results in a
379 "no need to worry" message.
380
381 That message is also more involved than anything we've so far displayed.
382 The statement which produces it is::
383
384    print_ret "You don't need to worry about ", (the) self, ".";
385
386 which you should read as doing this:
387
388 #. display the string "You don't need to worry about ",
389
390 #. display a definite article (usually "the") followed by a space and the
391    external name of the object concerned,
392
393 #. display a period, and
394
395 #. display a newline and return true in the usual way for a ``print_ret``
396    statement.
397
398 The interesting things that this statement demonstrates are:
399
400 * The ``print`` and ``print_ret`` statements aren't restricted to
401   displaying a single piece of information: they can display a list of
402   items which are separated by commas.  The statement still ends with a
403   semicolon in the usual way.
404
405 * As well as displaying strings, you can also display the names of objects:
406   given the ``nest`` object from our first game, ``(the) nest`` would
407   display "the bird's nest", ``(The) nest`` would display "The bird's
408   nest", ``(a) nest`` would display "a bird's nest", ``(A) nest`` would
409   display "A bird's nest" and ``(name) nest`` would display just "bird's
410   nest".  This use of a word in parentheses, telling the interpreter how to
411   display the following object's internal ID, is called a **print rule**.
412
413 * There's a library variable ``self`` which always contains the internal ID
414   of the current object, and is really convenient when using a ``Class``.
415   By using this variable in our ``print_ret`` statement, we ensure that the
416   message contains the name of the appropriate object.
417
418 Let's see an example of this in action; here's a ``Prop`` object from
419 "William Tell"::
420
421    Prop    "south gate" street
422      with  name 'south' 'southern' 'wooden' 'gate',
423            description "The large wooden gate in the town walls is wide open.",
424            ...
425
426 If players type EXAMINE GATE, they'll see "The large wooden gate..."; if
427 they type CLOSE GATE then the gate's ``before`` property will step in and
428 display "You don't need to worry about the south gate", neatly picking up
429 the name of the object from the ``self`` variable.
430
431 The reason for doing all this, rather than just creating a simple scenery
432 object like Heidi's ``tree`` and ``cottage``, is to support EXAMINE for
433 increased realism, while clearly hinting to players that trying other verbs
434 would be a waste of time.
435
436 .. rubric:: A class for furniture
437
438 The last class for now -- we'll talk about the ``Arrow`` and ``NPC``
439 classes in the next chapter -- is for furniture-like objects.  If you label
440 an object with the ``static`` attribute, an attempt to TAKE it results in
441 "That's fixed in place" -- acceptable in the case of Heidi's branch object
442 (which is indeed supposed to be part of the tree), less so for items which
443 are simply large and heavy.  This ``Furniture`` class might sometimes be
444 more appropriate::
445
446    Class    Furniture
447      with   before [;
448                Take,Pull,Push,PushDir:
449                  print_ret (The) self, " is too heavy for that.";
450             ],
451       has   static supporter;
452
453 Its structure is similar to that of our ``Prop`` class: some appropriate
454 attributes, and a ``before`` property to trap actions directed at it.
455 Again, we display a message which is "personalised" for the object
456 concerned by using a ``(The) self`` print rule.  This time we're
457 intercepting four actions; we *could* have written the property like this::
458
459    before [;
460        Take: print_ret (The) self, " is too heavy for that.";
461        Pull: print_ret (The) self, " is too heavy for that.";
462        Push: print_ret (The) self, " is too heavy for that.";
463        PushDir: print_ret (The) self, " is too heavy for that.";
464    ],
465
466 but since we're giving exactly the same response each time, it's better to
467 put all of those actions into one list, separated by commas.  ``PushDir``,
468 if you were wondering, is the action triggered by a command like PUSH THE
469 TABLE NORTH.
470
471 Incidentally, another bonus of defining classes like these is that you can
472 probably reuse them in your next game.
473
474 Now that most of our class definitions are in place, we can get on with
475 defining some real rooms and objects.  First, though, if you're typing in
476 the "William Tell" game as you read through the guide, you'd probably like
477 to check that what you've entered so far is correct; "Compile-as-you-go" on
478 page 233 explains how to compile the game in its current -- incomplete --
479 state.