summaryrefslogtreecommitdiff
path: root/apps/plugins/puzzles/src/devel.but
diff options
context:
space:
mode:
Diffstat (limited to 'apps/plugins/puzzles/src/devel.but')
-rw-r--r--apps/plugins/puzzles/src/devel.but6122
1 files changed, 0 insertions, 6122 deletions
diff --git a/apps/plugins/puzzles/src/devel.but b/apps/plugins/puzzles/src/devel.but
deleted file mode 100644
index c201a3e6c9..0000000000
--- a/apps/plugins/puzzles/src/devel.but
+++ /dev/null
@@ -1,6122 +0,0 @@
1\cfg{text-indent}{0}
2\cfg{text-width}{72}
3\cfg{text-title-align}{left}
4\cfg{text-chapter-align}{left}
5\cfg{text-chapter-numeric}{true}
6\cfg{text-chapter-suffix}{. }
7\cfg{text-chapter-underline}{-}
8\cfg{text-section-align}{0}{left}
9\cfg{text-section-numeric}{0}{true}
10\cfg{text-section-suffix}{0}{. }
11\cfg{text-section-underline}{0}{-}
12\cfg{text-section-align}{1}{left}
13\cfg{text-section-numeric}{1}{true}
14\cfg{text-section-suffix}{1}{. }
15\cfg{text-section-underline}{1}{-}
16\cfg{text-versionid}{0}
17
18\cfg{html-contents-filename}{index.html}
19\cfg{html-template-filename}{%k.html}
20\cfg{html-index-filename}{docindex.html}
21\cfg{html-leaf-level}{1}
22\cfg{html-contents-depth-0}{1}
23\cfg{html-contents-depth-1}{3}
24\cfg{html-leaf-contains-contents}{true}
25
26\define{dash} \u2013{-}
27
28\title Developer documentation for Simon Tatham's puzzle collection
29
30This is a guide to the internal structure of Simon Tatham's Portable
31Puzzle Collection (henceforth referred to simply as \q{Puzzles}),
32for use by anyone attempting to implement a new puzzle or port to a
33new platform.
34
35This guide is believed correct as of \cw{git} commit
36\cw{a2212e82aa2f4b9a4ee22783d6fed2761c213432}. Hopefully it will be
37updated along with the code in future, but if not, I've at least left
38this version number in here so you can figure out what's changed by
39tracking commit comments from there onwards.
40
41\C{intro} Introduction
42
43The Puzzles code base is divided into four parts: a set of
44interchangeable front ends, a set of interchangeable back ends, a
45universal \q{middle end} which acts as a buffer between the two, and
46a bunch of miscellaneous utility functions. In the following
47sections I give some general discussion of each of these parts.
48
49\H{intro-frontend} Front end
50
51The front end is the non-portable part of the code: it's the bit
52that you replace completely when you port to a different platform.
53So it's responsible for all system calls, all GUI interaction, and
54anything else platform-specific.
55
56The front end contains \cw{main()} or the local platform's
57equivalent. Top-level control over the application's execution flow
58belongs to the front end (it isn't, for example, a set of functions
59called by a universal \cw{main()} somewhere else).
60
61The front end has complete freedom to design the GUI for any given
62port of Puzzles. There is no centralised mechanism for maintaining the
63menu layout, for example. This has a cost in consistency (when I
64\e{do} want the same menu layout on more than one platform, I have to
65edit N pieces of code in parallel every time I make a change), but the
66advantage is that local GUI conventions can be conformed to and local
67constraints adapted to. For example, MacOS has strict human interface
68guidelines which specify a different menu layout from the one I've
69used on Windows and GTK; there's nothing stopping the MacOS front end
70from providing a menu layout consistent with those guidelines.
71
72Although the front end is mostly caller rather than the callee in
73its interactions with other parts of the code, it is required to
74implement a small API for other modules to call, mostly of drawing
75functions for games to use when drawing their graphics. The drawing
76API is documented in \k{drawing}; the other miscellaneous front end
77API functions are documented in \k{frontend-api}.
78
79\H{intro-backend} Back end
80
81A \q{back end}, in this collection, is synonymous with a \q{puzzle}.
82Each back end implements a different game.
83
84At the top level, a back end is simply a data structure, containing
85a few constants (flag words, preferred pixel size) and a large
86number of function pointers. Back ends are almost invariably callee
87rather than caller, which means there's a limitation on what a back
88end can do on its own initiative.
89
90The persistent state in a back end is divided into a number of data
91structures, which are used for different purposes and therefore
92likely to be switched around, changed without notice, and otherwise
93updated by the rest of the code. It is important when designing a
94back end to put the right pieces of data into the right structures,
95or standard midend-provided features (such as Undo) may fail to
96work.
97
98The functions and variables provided in the back end data structure
99are documented in \k{backend}.
100
101\H{intro-midend} Middle end
102
103Puzzles has a single and universal \q{middle end}. This code is
104common to all platforms and all games; it sits in between the front
105end and the back end and provides standard functionality everywhere.
106
107People adding new back ends or new front ends should generally not
108need to edit the middle end. On rare occasions there might be a
109change that can be made to the middle end to permit a new game to do
110something not currently anticipated by the middle end's present
111design; however, this is terribly easy to get wrong and should
112probably not be undertaken without consulting the primary maintainer
113(me). Patch submissions containing unannounced mid-end changes will
114be treated on their merits like any other patch; this is just a
115friendly warning that mid-end changes will need quite a lot of
116merits to make them acceptable.
117
118Functionality provided by the mid-end includes:
119
120\b Maintaining a list of game state structures and moving back and
121forth along that list to provide Undo and Redo.
122
123\b Handling timers (for move animations, flashes on completion, and
124in some cases actually timing the game).
125
126\b Handling the container format of game IDs: receiving them,
127picking them apart into parameters, description and/or random seed,
128and so on. The game back end need only handle the individual parts
129of a game ID (encoded parameters and encoded game description);
130everything else is handled centrally by the mid-end.
131
132\b Handling standard keystrokes and menu commands, such as \q{New
133Game}, \q{Restart Game} and \q{Quit}.
134
135\b Pre-processing mouse events so that the game back ends can rely
136on them arriving in a sensible order (no missing button-release
137events, no sudden changes of which button is currently pressed,
138etc).
139
140\b Handling the dialog boxes which ask the user for a game ID.
141
142\b Handling serialisation of entire games (for loading and saving a
143half-finished game to a disk file; for handling application shutdown
144and restart on platforms such as PalmOS where state is expected to be
145saved; for storing the previous game in order to undo and redo across
146a New Game event).
147
148Thus, there's a lot of work done once by the mid-end so that
149individual back ends don't have to worry about it. All the back end
150has to do is cooperate in ensuring the mid-end can do its work
151properly.
152
153The API of functions provided by the mid-end to be called by the
154front end is documented in \k{midend}.
155
156\H{intro-utils} Miscellaneous utilities
157
158In addition to these three major structural components, the Puzzles
159code also contains a variety of utility modules usable by all of the
160above components. There is a set of functions to provide
161platform-independent random number generation; functions to make
162memory allocation easier; functions which implement a balanced tree
163structure to be used as necessary in complex algorithms; and a few
164other miscellaneous functions. All of these are documented in
165\k{utils}.
166
167\H{intro-structure} Structure of this guide
168
169There are a number of function call interfaces within Puzzles, and
170this guide will discuss each one in a chapter of its own. After
171that, \k{writing} discusses how to design new games, with some
172general design thoughts and tips.
173
174\C{backend} Interface to the back end
175
176This chapter gives a detailed discussion of the interface that each
177back end must implement.
178
179At the top level, each back end source file exports a single global
180symbol, which is a \c{const struct game} containing a large number
181of function pointers and a small amount of constant data. This
182structure is called by different names depending on what kind of
183platform the puzzle set is being compiled on:
184
185\b On platforms such as Windows and GTK, which build a separate
186binary for each puzzle, the game structure in every back end has the
187same name, \cq{thegame}; the front end refers directly to this name,
188so that compiling the same front end module against a different back
189end module builds a different puzzle.
190
191\b On platforms such as MacOS X and PalmOS, which build all the
192puzzles into a single monolithic binary, the game structure in each
193back end must have a different name, and there's a helper module
194\c{list.c} which constructs a complete list of those game structures
195from a header file generated by CMake.
196
197On the latter type of platform, source files may assume that the
198preprocessor symbol \c{COMBINED} has been defined. Thus, the usual
199code to declare the game structure looks something like this:
200
201\c #ifdef COMBINED
202\c #define thegame net /* or whatever this game is called */
203\e iii iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
204\c #endif
205\c
206\c const struct game thegame = {
207\c /* lots of structure initialisation in here */
208\e iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
209\c };
210
211Game back ends must also internally define a number of data
212structures, for storing their various persistent state. This chapter
213will first discuss the nature and use of those structures, and then
214go on to give details of every element of the game structure.
215
216\H{backend-structs} Data structures
217
218Each game is required to define four separate data structures. This
219section discusses each one and suggests what sorts of things need to
220be put in it.
221
222\S{backend-game-params} \c{game_params}
223
224The \c{game_params} structure contains anything which affects the
225automatic generation of new puzzles. So if puzzle generation is
226parametrised in any way, those parameters need to be stored in
227\c{game_params}.
228
229Most puzzles currently in this collection are played on a grid of
230squares, meaning that the most obvious parameter is the grid size.
231Many puzzles have additional parameters; for example, Mines allows
232you to control the number of mines in the grid independently of its
233size, Net can be wrapping or non-wrapping, Solo has difficulty
234levels and symmetry settings, and so on.
235
236A simple rule for deciding whether a data item needs to go in
237\c{game_params} is: would the user expect to be able to control this
238data item from either the preset-game-types menu or the \q{Custom}
239game type configuration? If so, it's part of \c{game_params}.
240
241\c{game_params} structures are permitted to contain pointers to
242subsidiary data if they need to. The back end is required to provide
243functions to create and destroy \c{game_params}, and those functions
244can allocate and free additional memory if necessary. (It has not
245yet been necessary to do this in any puzzle so far, but the
246capability is there just in case.)
247
248\c{game_params} is also the only structure which the game's
249\cw{compute_size()} function may refer to; this means that any aspect
250of the game which affects the size of the window it needs to be drawn
251in (other than the magnification level) must be stored in
252\c{game_params}. In particular, this imposes the fundamental
253limitation that random game generation may not have a random effect on
254the window size: game generation algorithms are constrained to work by
255starting from the grid size rather than generating it as an emergent
256phenomenon. (Although this is a restriction in theory, it has not yet
257seemed to be a problem.)
258
259\S{backend-game-state} \c{game_state}
260
261While the user is actually playing a puzzle, the \c{game_state}
262structure stores all the data corresponding to the current state of
263play.
264
265The mid-end keeps \c{game_state}s in a list, and adds to the list
266every time the player makes a move; the Undo and Redo functions step
267back and forth through that list.
268
269Therefore, a good means of deciding whether a data item needs to go in
270\c{game_state} is: would a player expect that data item to be restored
271on undo? If so, put it in \c{game_state}, and this will automatically
272happen without you having to lift a finger. If not, then you might
273have found a data item that needs to go in \c{game_ui} instead.
274
275Two quite different examples of this:
276
277\b if the game provides an interface for making moves by moving a
278cursor around the grid with the keyboard and pressing some other key
279when you get to a square you want to change, then the location of that
280cursor belongs in \c{game_ui}, because the player will want to undo
281one \e{square change} at a time, not one \e{cursor movement} at a
282time.
283
284\b Mines tracks the number of times you opened a mine square and died.
285Every time you do that, you can only continue the game by pressing
286Undo. So the deaths counter belongs in \c{game_ui}, because otherwise,
287it would revert to 0 every time you undid your mistaken move.
288
289During play, \c{game_state}s are often passed around without an
290accompanying \c{game_params} structure. Therefore, any information
291in \c{game_params} which is important during play (such as the grid
292size) must be duplicated within the \c{game_state}. One simple
293method of doing this is to have the \c{game_state} structure
294\e{contain} a \c{game_params} structure as one of its members,
295although this isn't obligatory if you prefer to do it another way.
296
297\S{backend-game-drawstate} \c{game_drawstate}
298
299\c{game_drawstate} carries persistent state relating to the current
300graphical contents of the puzzle window. The same \c{game_drawstate}
301is passed to every call to the game redraw function, so that it can
302remember what it has already drawn and what needs redrawing.
303
304A typical use for a \c{game_drawstate} is to have an array mirroring
305the array of grid squares in the \c{game_state}, but describing what
306was drawn in the window on the most recent redraw. This is used to
307identify the squares that need redrawing next time, by deciding what
308the new value in that array should be, and comparing it to what was
309drawn last time. See \k{writing-howto-redraw} for more on this
310subject.
311
312\c{game_drawstate} is occasionally completely torn down and
313reconstructed by the mid-end, if the user somehow forces a full
314redraw. Therefore, no data should be stored in \c{game_drawstate}
315which is \e{not} related to the state of the puzzle window, because
316it might be unexpectedly destroyed.
317
318The back end provides functions to create and destroy
319\c{game_drawstate}, which means it can contain pointers to
320subsidiary allocated data if it needs to. A common thing to want to
321allocate in a \c{game_drawstate} is a \c{blitter}; see
322\k{drawing-blitter} for more on this subject.
323
324\S{backend-game-ui} \c{game_ui}
325
326\c{game_ui} contains whatever doesn't fit into the above three
327structures!
328
329A new \c{game_ui} is created when the user begins playing a new
330instance of a puzzle (i.e. during \q{New Game} or after entering a
331game ID etc). It persists until the user finishes playing that game
332and begins another one (or closes the window); in particular,
333\q{Restart Game} does \e{not} destroy the \c{game_ui}.
334
335There are various things that you might store in \c{game_ui}, which
336are conceptually different from each other, but I haven't yet found a
337need to split them out into smaller sub-structures for different
338purposes:
339
340\dt Transient UI state:
341
342\dd Storing a piece of UI state in \c{game_state} means that you can
343only update it by appending a move to the undo chain. Some UI state
344shouldn't really be treated this way. For example, if your puzzle has
345a keyboard-controlled cursor, you probably don't want every cursor
346movement to be an undoable action, because the history of where the
347cursor went just isn't interesting. More likely the cursor should just
348move freely, and the only undoable actions are the ones where you
349modify the element under the cursor. So you'd store the cursor
350position in \c{game_ui} rather than \c{game_state}. See
351\k{writing-keyboard-cursor} for more details.
352
353\lcont{ Another example of this is the state of an ongoing mouse drag.
354If there's an undoable action involved, it will probably occur when
355the drag is released. In between, you still need to store state that
356the redraw function will use to update the display \dash and that can
357live in \c{game_ui}. See \k{writing-howto-dragging} for more details
358of this. }
359
360\dt Persistent UI state:
361
362\dd An example of this is the counter of deaths in Mines or Inertia.
363This shouldn't be reverted by pressing Undo, for the opposite reason
364to the cursor position: the cursor position is too boring to store the
365history of, but the deaths counter is too \e{important}!
366
367\dt Information about recent changes to the game state:
368
369\dd This is used in Mines, for example, to indicate whether a
370requested \q{flash} should be a white flash for victory or a red flash
371for defeat; see \k{writing-flash-types}.
372
373\dt User preferences:
374
375\dd Any user preference about display or UI handled by
376\cw{get_prefs()} and \cw{set_prefs()} will need to live in
377\c{game_ui}, because that's the structure that those functions access.
378
379\H{backend-simple} Simple data in the back end
380
381In this section I begin to discuss each individual element in the
382back end structure. To begin with, here are some simple
383self-contained data elements.
384
385\S{backend-name} \c{name}
386
387\c const char *name;
388
389This is a simple ASCII string giving the name of the puzzle. This
390name will be used in window titles, in game selection menus on
391monolithic platforms, and anywhere else that the front end needs to
392know the name of a game.
393
394\S{backend-winhelp} \c{winhelp_topic} and \c{htmlhelp_topic}
395
396\c const char *winhelp_topic, *htmlhelp_topic;
397
398These members are used on Windows only, to provide online help.
399Although the Windows front end provides a separate binary for each
400puzzle, it has a single monolithic help file; so when a user selects
401\q{Help} from the menu, the program needs to open the help file and
402jump to the chapter describing that particular puzzle.
403
404This code base still supports the legacy \cw{.HLP} Windows Help format
405as well as the less old \cw{.CHM} HTML Help format. The two use
406different methods of identifying topics, so you have to specify both.
407
408Each chapter about a puzzle in \c{puzzles.but} is labelled with a
409\e{help topic} name for Windows Help, which typically appears just
410after the \cw{\\C} chapter title paragraph, similar to this:
411
412\c \C{net} \i{Net}
413\c
414\c \cfg{winhelp-topic}{games.net}
415
416But HTML Help is able to use the Halibut identifier for the chapter
417itself, i.e. the keyword that appears in braces immediatey after the
418\cw{\\C}.
419
420So the corresponding game back end encodes the \c{winhelp-topic}
421string (here \cq{games.net}) in the \c{winhelp_topic} element of the
422game structure, and puts the chapter identifier (here \cq{net}) in the
423\c{htmlhelp_topic} element. For example:
424
425\c const struct game thegame = {
426\c "Net", "games.net", "net",
427\c // ...
428\c };
429
430\H{backend-params} Handling game parameter sets
431
432In this section I present the various functions which handle the
433\c{game_params} structure.
434
435\S{backend-default-params} \cw{default_params()}
436
437\c game_params *(*default_params)(void);
438
439This function allocates a new \c{game_params} structure, fills it
440with the default values, and returns a pointer to it.
441
442\S{backend-fetch-preset} \cw{fetch_preset()}
443
444\c bool (*fetch_preset)(int i, char **name, game_params **params);
445
446This function is one of the two APIs a back end can provide to
447populate the \q{Type} menu, which provides a list of conveniently
448accessible preset parameters for most games.
449
450The function is called with \c{i} equal to the index of the preset
451required (numbering from zero). It returns \cw{false} if that preset
452does not exist (if \c{i} is less than zero or greater than the
453largest preset index). Otherwise, it sets \c{*params} to point at a
454newly allocated \c{game_params} structure containing the preset
455information, sets \c{*name} to point at a newly allocated C string
456containing the preset title (to go on the \q{Type} menu), and
457returns \cw{true}.
458
459If the game does not wish to support any presets at all, this
460function is permitted to return \cw{false} always.
461
462If the game wants to return presets in the form of a hierarchical menu
463instead of a flat list (and, indeed, even if it doesn't), then it may
464set this function pointer to \cw{NULL}, and instead fill in the
465alternative function pointer \cw{preset_menu}
466(\k{backend-preset-menu}).
467
468\S{backend-preset-menu} \cw{preset_menu()}
469
470\c struct preset_menu *(*preset_menu)(void);
471
472This function is the more flexible of the two APIs by which a back end
473can define a collection of preset game parameters.
474
475This function simply returns a complete menu hierarchy, in the form of
476a \c{struct preset_menu} (see \k{midend-get-presets}) and further
477submenus (if it wishes) dangling off it. There are utility functions
478described in \k{utils-presets} to make it easy for the back end to
479construct this menu.
480
481If the game has no need to return a hierarchy of menus, it may instead
482opt to implement the \cw{fetch_preset()} function (see
483\k{backend-fetch-preset}).
484
485The game need not fill in the \c{id} fields in the preset menu
486structures. The mid-end will do that after it receives the structure
487from the game, and before passing it on to the front end.
488
489\S{backend-encode-params} \cw{encode_params()}
490
491\c char *(*encode_params)(const game_params *params, bool full);
492
493The job of this function is to take a \c{game_params}, and encode it
494in a printable ASCII string form for use in game IDs. The return value must
495be a newly allocated C string, and \e{must} not contain a colon or a hash
496(since those characters are used to mark the end of the parameter
497section in a game ID).
498
499Ideally, it should also not contain any other potentially
500controversial punctuation; bear in mind when designing a string
501parameter format that it will probably be used on both Windows and
502Unix command lines under a variety of exciting shell quoting and
503metacharacter rules. Sticking entirely to alphanumerics is the
504safest thing; if you really need punctuation, you can probably get
505away with commas, periods or underscores without causing anybody any
506major inconvenience. If you venture far beyond that, you're likely
507to irritate \e{somebody}.
508
509(At the time of writing this, most existing games have purely
510alphanumeric string parameter formats. Usually these involve a
511letter denoting a parameter, followed optionally by a number giving
512the value of that parameter, with a few mandatory parts at the
513beginning such as numeric width and height separated by \cq{x}.)
514
515If the \c{full} parameter is \cw{true}, this function should encode
516absolutely everything in the \c{game_params}, such that a subsequent
517call to \cw{decode_params()} (\k{backend-decode-params}) will yield
518an identical structure. If \c{full} is \cw{false}, however, you
519should leave out anything which is not necessary to describe a
520\e{specific puzzle instance}, i.e. anything which only takes effect
521when a new puzzle is \e{generated}.
522
523For example, the Solo \c{game_params} includes a difficulty rating
524used when constructing new puzzles; but a Solo game ID need not
525explicitly include the difficulty, since to describe a puzzle once
526generated it's sufficient to give the grid dimensions and the location
527and contents of the clue squares. (Indeed, one might very easily type
528in a puzzle out of a newspaper without \e{knowing} what its difficulty
529level is in Solo's terminology.) Therefore, Solo's
530\cw{encode_params()} only encodes the difficulty level if \c{full} is
531set.
532
533\S{backend-decode-params} \cw{decode_params()}
534
535\c void (*decode_params)(game_params *params, char const *string);
536
537This function is the inverse of \cw{encode_params()}
538(\k{backend-encode-params}). It parses the supplied string and fills
539in the supplied \c{game_params} structure. Note that the structure
540will \e{already} have been allocated: this function is not expected
541to create a \e{new} \c{game_params}, but to modify an existing one.
542
543This function can receive a string which only encodes a subset of
544the parameters. The most obvious way in which this can happen is if
545the string was constructed by \cw{encode_params()} with its \c{full}
546parameter set to \cw{false}; however, it could also happen if the
547user typed in a parameter set manually and missed something out. Be
548prepared to deal with a wide range of possibilities.
549
550When dealing with a parameter which is not specified in the input
551string, what to do requires a judgment call on the part of the
552programmer. Sometimes it makes sense to adjust other parameters to
553bring them into line with the new ones. In Mines, for example, you
554would probably not want to keep the same mine count if the user
555dropped the grid size and didn't specify one, since you might easily
556end up with more mines than would actually fit in the grid! On the
557other hand, sometimes it makes sense to leave the parameter alone: a
558Solo player might reasonably expect to be able to configure size and
559difficulty independently of one another.
560
561This function currently has no direct means of returning an error if
562the string cannot be parsed at all. However, the returned
563\c{game_params} is almost always subsequently passed to
564\cw{validate_params()} (\k{backend-validate-params}), so if you
565really want to signal parse errors, you could always have a \c{char
566*} in your parameters structure which stored an error message, and
567have \cw{validate_params()} return it if it is non-\cw{NULL}.
568
569\S{backend-free-params} \cw{free_params()}
570
571\c void (*free_params)(game_params *params);
572
573This function frees a \c{game_params} structure, and any subsidiary
574allocations contained within it.
575
576\S{backend-dup-params} \cw{dup_params()}
577
578\c game_params *(*dup_params)(const game_params *params);
579
580This function allocates a new \c{game_params} structure and
581initialises it with an exact copy of the information in the one
582provided as input. It returns a pointer to the new duplicate.
583
584\S{backend-can-configure} \c{can_configure}
585
586\c bool can_configure;
587
588This data element is set to \cw{true} if the back end supports custom
589parameter configuration via a dialog box. If it is \cw{true}, then the
590functions \cw{configure()} and \cw{custom_params()} are expected to
591work. See \k{backend-configure} and \k{backend-custom-params} for more
592details.
593
594\S{backend-configure} \cw{configure()}
595
596\c config_item *(*configure)(const game_params *params);
597
598This function is called when the user requests a dialog box for
599custom parameter configuration. It returns a newly allocated array
600of \cw{config_item} structures, describing the GUI elements required
601in the dialog box. The array should have one more element than the
602number of controls, since it is terminated with a \cw{C_END} marker
603(see below). Each array element describes the control together with
604its initial value; the front end will modify the value fields and
605return the updated array to \cw{custom_params()} (see
606\k{backend-custom-params}).
607
608The \cw{config_item} structure contains the following elements used by
609this function:
610
611\c const char *name;
612\c int type;
613\c union { /* type-specific fields */ } u;
614\e iiiiiiiiiiiiiiiiiiiiiiiiii
615
616\c{name} is an ASCII string giving the textual label for a GUI
617control. It is \e{not} expected to be dynamically allocated.
618
619\c{type} contains one of a small number of \c{enum} values defining
620what type of control is being described. The usable member of the
621union field \c{u} depends on \c{type}. The valid type values are:
622
623\dt \c{C_STRING}
624
625\dd Describes a text input box. (This is also used for numeric
626input. The back end does not bother informing the front end that the
627box is numeric rather than textual; some front ends do have the
628capacity to take this into account, but I decided it wasn't worth
629the extra complexity in the interface.)
630
631\lcont{
632
633For controls of this type, \c{u.string} contains a single field
634
635\c char *sval;
636
637which stores a dynamically allocated string representing the contents
638of the input box.
639
640}
641
642\dt \c{C_BOOLEAN}
643
644\dd Describes a simple checkbox.
645
646\lcont{
647
648For controls of this type, \c{u.boolean} contains a single field
649
650\c bool bval;
651
652}
653
654\dt \c{C_CHOICES}
655
656\dd Describes a drop-down list presenting one of a small number of
657fixed choices.
658
659\lcont{
660
661For controls of this type, \c{u.choices} contains two fields:
662
663\c const char *choicenames;
664\c int selected;
665
666\c{choicenames} contains a list of strings describing the choices. The
667very first character of \c{sval} is used as a delimiter when
668processing the rest (so that the strings \cq{:zero:one:two},
669\cq{!zero!one!two} and \cq{xzeroxonextwo} all define a three-element
670list containing \cq{zero}, \cq{one} and \cq{two}).
671
672\c{selected} contains the index of the currently selected element,
673numbering from zero (so that in the above example, 0 would mean
674\cq{zero} and 2 would mean \cq{two}).
675
676Note that \c{u.choices.choicenames} is \e{not} dynamically allocated,
677unlike \c{u.string.sval}.
678
679}
680
681\dt \c{C_END}
682
683\dd Marks the end of the array of \c{config_item}s. There is no
684associated member of the union field \c{u} for this type.
685
686The array returned from this function is expected to have filled in
687the initial values of all the controls according to the input
688\c{game_params} structure.
689
690If the game's \c{can_configure} flag is set to \cw{false}, this
691function is never called and can be \cw{NULL}.
692
693\S{backend-custom-params} \cw{custom_params()}
694
695\c game_params *(*custom_params)(const config_item *cfg);
696
697This function is the counterpart to \cw{configure()}
698(\k{backend-configure}). It receives as input an array of
699\c{config_item}s which was originally created by \cw{configure()},
700but in which the control values have since been changed in
701accordance with user input. Its function is to read the new values
702out of the controls and return a newly allocated \c{game_params}
703structure representing the user's chosen parameter set.
704
705(The front end will have modified the controls' \e{values}, but
706there will still always be the same set of controls, in the same
707order, as provided by \cw{configure()}. It is not necessary to check
708the \c{name} and \c{type} fields, although you could use
709\cw{assert()} if you were feeling energetic.)
710
711This function is not expected to (and indeed \e{must not}) free the
712input \c{config_item} array. (If the parameters fail to validate,
713the dialog box will stay open.)
714
715If the game's \c{can_configure} flag is set to \cw{false}, this
716function is never called and can be \cw{NULL}.
717
718\S{backend-get-prefs} \cw{get_prefs()}
719
720\c config_item *(*get_prefs)(game_ui *ui);
721
722This function works very like \cw{configure()}, but instead of
723receiving a \c{game_params} and returning GUI elements describing the
724data in it, this function receives a \c{game_ui} and returns GUI
725elements describing any user preferences stored in that.
726
727This function should only deal with fields of \c{game_ui} that are
728user-settable preferences. In-game state like cursor position and
729mouse drags, or per-game state like death counters, are nothing to do
730with this function.
731
732If there are no user preferences, you can set both this function
733pointer and \c{set_prefs} to \cw{NULL}.
734
735If you implement these functions, you must also ensure that your
736game's \cw{new_ui()} function can be called with a null \c{game_state}
737pointer. (See \k{backend-new-ui}.)
738
739In every \c{config_item} returned from this function, you must set an
740additional field beyond the ones described in \k{backend-configure}:
741
742\c const char *kw;
743
744This should be an identifying keyword for the user preference in
745question, suitable for use in configuration files. That means it
746should remain stable, even if the user-facing wording in the \c{name}
747field is reworded for clarity. If it doesn't stay stable, old
748configuration files will not be read correctly.
749
750For \c{config_item}s of type \cw{C_CHOICES}, you must also set an
751extra field in \c{u.choices}:
752
753\c const char *choicekws;
754
755This has the same structure as the \c{choicenames} field (a list of
756values delimited by the first character in the whole string), and it
757provides an identifying keyword for each individual choice in the
758list, in the same order as the entries of \c{choicenames}.
759
760\S{backend-set-prefs} \cw{set_prefs()}
761
762\c void (*set_prefs)(game_ui *ui, const config_item *cfg);
763
764This function is the counterpart to \cw{set_prefs()}, as
765\cw{custom_params()} is to \cw{configure()}. It receives an array of
766\c{config_item}s which was originally created by \cw{get_prefs()},
767with the controls' values updated from user input, and it should
768transcribe the new settings into the provided \c{game_ui}.
769
770If there are no user preferences, you can set both this function
771pointer and \c{get_prefs} to \cw{NULL}.
772
773\S{backend-validate-params} \cw{validate_params()}
774
775\c const char *(*validate_params)(const game_params *params,
776\c bool full);
777
778This function takes a \c{game_params} structure as input, and checks
779that the parameters described in it fall within sensible limits. (At
780the very least, grid dimensions should almost certainly be strictly
781positive, for example.)
782
783Return value is \cw{NULL} if no problems were found, or
784alternatively a (non-dynamically-allocated) ASCII string describing
785the error in human-readable form.
786
787If the \c{full} parameter is set, full validation should be
788performed: any set of parameters which would not permit generation
789of a sensible puzzle should be faulted. If \c{full} is \e{not} set,
790the implication is that these parameters are not going to be used
791for \e{generating} a puzzle; so parameters which can't even sensibly
792\e{describe} a valid puzzle should still be faulted, but parameters
793which only affect puzzle generation should not be.
794
795(The \c{full} option makes a difference when parameter combinations
796are non-orthogonal. For example, Net has a boolean option
797controlling whether it enforces a unique solution; it turns out that
798it's impossible to generate a uniquely soluble puzzle with wrapping
799walls and width 2, so \cw{validate_params()} will complain if you
800ask for one. However, if the user had just been playing a unique
801wrapping puzzle of a more sensible width, and then pastes in a game
802ID acquired from somebody else which happens to describe a
803\e{non}-unique wrapping width-2 puzzle, then \cw{validate_params()}
804will be passed a \c{game_params} containing the width and wrapping
805settings from the new game ID and the uniqueness setting from the
806old one. This would be faulted, if it weren't for the fact that
807\c{full} is not set during this call, so Net ignores the
808inconsistency. The resulting \c{game_params} is never subsequently
809used to generate a puzzle; this is a promise made by the mid-end
810when it asks for a non-full validation.)
811
812\H{backend-descs} Handling game descriptions
813
814In this section I present the functions that deal with a textual
815description of a puzzle, i.e. the part that comes after the colon in
816a descriptive-format game ID.
817
818\S{backend-new-desc} \cw{new_desc()}
819
820\c char *(*new_desc)(const game_params *params, random_state *rs,
821\c char **aux, bool interactive);
822
823This function is where all the really hard work gets done. This is
824the function whose job is to randomly generate a new puzzle,
825ensuring solubility and uniqueness as appropriate.
826
827As input it is given a \c{game_params} structure and a random state
828(see \k{utils-random} for the random number API). It must invent a
829puzzle instance, encode it in printable ASCII string form, and
830return a dynamically allocated C string containing that encoding.
831
832Additionally, it may return a second dynamically allocated string in
833\c{*aux}. (If it doesn't want to, then it can leave that parameter
834completely alone; it isn't required to set it to \cw{NULL}, although
835doing so is harmless.) That string, if present, will be passed to
836\cw{solve()} (\k{backend-solve}) later on; so if the puzzle is
837generated in such a way that a solution is known, then information
838about that solution can be saved in \c{*aux} for \cw{solve()} to
839use.
840
841The \c{interactive} parameter should be ignored by almost all
842puzzles. Its purpose is to distinguish between generating a puzzle
843within a GUI context for immediate play, and generating a puzzle in
844a command-line context for saving to be played later. The only
845puzzle that currently uses this distinction (and, I fervently hope,
846the only one which will \e{ever} need to use it) is Mines, which
847chooses a random first-click location when generating puzzles
848non-interactively, but which waits for the user to place the first
849click when interactive. If you think you have come up with another
850puzzle which needs to make use of this parameter, please think for
851at least ten minutes about whether there is \e{any} alternative!
852
853Note that game description strings are not required to contain an
854encoding of parameters such as grid size; a game description is
855never separated from the \c{game_params} it was generated with, so
856any information contained in that structure need not be encoded
857again in the game description.
858
859\S{backend-validate-desc} \cw{validate_desc()}
860
861\c const char *(*validate_desc)(const game_params *params,
862\c const char *desc);
863
864This function is given a game description, and its job is to
865validate that it describes a puzzle which makes sense.
866
867To some extent it's up to the user exactly how far they take the
868phrase \q{makes sense}; there are no particularly strict rules about
869how hard the user is permitted to shoot themself in the foot when
870typing in a bogus game description by hand. (For example, Rectangles
871will not verify that the sum of all the numbers in the grid equals
872the grid's area. So a user could enter a puzzle which was provably
873not soluble, and the program wouldn't complain; there just wouldn't
874happen to be any sequence of moves which solved it.)
875
876The one non-negotiable criterion is that any game description which
877makes it through \cw{validate_desc()} \e{must not} subsequently
878cause a crash or an assertion failure when fed to \cw{new_game()}
879and thence to the rest of the back end.
880
881The return value is \cw{NULL} on success, or a
882non-dynamically-allocated C string containing an error message.
883
884\S{backend-new-game} \cw{new_game()}
885
886\c game_state *(*new_game)(midend *me, const game_params *params,
887\c const char *desc);
888
889This function takes a game description as input, together with its
890accompanying \c{game_params}, and constructs a \c{game_state}
891describing the initial state of the puzzle. It returns a newly
892allocated \c{game_state} structure.
893
894Almost all puzzles should ignore the \c{me} parameter. It is
895required by Mines, which needs it for later passing to
896\cw{midend_supersede_game_desc()} (see \k{backend-supersede}) once
897the user has placed the first click. I fervently hope that no other
898puzzle will be awkward enough to require it, so everybody else
899should ignore it. As with the \c{interactive} parameter in
900\cw{new_desc()} (\k{backend-new-desc}), if you think you have a
901reason to need this parameter, please try very hard to think of an
902alternative approach!
903
904\H{backend-states} Handling game states
905
906This section describes the functions which create and destroy
907\c{game_state} structures.
908
909(Well, except \cw{new_game()}, which is in \k{backend-new-game}
910instead of under here; but it deals with game descriptions \e{and}
911game states and it had to go in one section or the other.)
912
913\S{backend-dup-game} \cw{dup_game()}
914
915\c game_state *(*dup_game)(const game_state *state);
916
917This function allocates a new \c{game_state} structure and
918initialises it with an exact copy of the information in the one
919provided as input. It returns a pointer to the new duplicate.
920
921\S{backend-free-game} \cw{free_game()}
922
923\c void (*free_game)(game_state *state);
924
925This function frees a \c{game_state} structure, and any subsidiary
926allocations contained within it.
927
928\H{backend-ui} Handling \c{game_ui}
929
930\S{backend-new-ui} \cw{new_ui()}
931
932\c game_ui *(*new_ui)(const game_state *state);
933
934This function allocates and returns a new \c{game_ui} structure for
935playing a particular puzzle.
936
937Usually, this function is passed a pointer to the initial
938\c{game_state}, in case it needs to refer to that when setting up the
939initial values for the new game.
940
941However, if the puzzle defines \c{get_prefs()} and \c{set_prefs()}
942functions, then this function may also be called with
943\cw{state==NULL}. In this situation it must still allocate a
944\c{game_ui} which can be used by \c{get_prefs()} and \c{set_prefs()},
945although it need not be usable for actually playing a game.
946
947\S{backend-free-ui} \cw{free_ui()}
948
949\c void (*free_ui)(game_ui *ui);
950
951This function frees a \c{game_ui} structure, and any subsidiary
952allocations contained within it.
953
954\S{backend-encode-ui} \cw{encode_ui()}
955
956\c char *(*encode_ui)(const game_ui *ui);
957
958This function encodes any \e{important} data in a \c{game_ui}
959structure in printable ASCII string form. It is only called when
960saving a half-finished game to a file.
961
962It should be used sparingly. Almost all data in a \c{game_ui} is not
963important enough to save. The location of the keyboard-controlled
964cursor, for example, can be reset to a default position on reloading
965the game without impacting the user experience. If the user should
966somehow manage to save a game while a mouse drag was in progress,
967then discarding that mouse drag would be an outright \e{feature}.
968
969A typical thing that \e{would} be worth encoding in this function is
970the Mines death counter: it's in the \c{game_ui} rather than the
971\c{game_state} because it's too important to allow the user to
972revert it by using Undo, and therefore it's also too important to
973allow the user to revert it by saving and reloading. (Of course, the
974user could edit the save file by hand... But if the user is \e{that}
975determined to cheat, they could just as easily modify the game's
976source.)
977
978The \cw{encode_ui()} function is optional. If a back-end doesn't need
979this function it can just set the pointer to \cw{NULL}.
980
981\S{backend-decode-ui} \cw{decode_ui()}
982
983\c void (*decode_ui)(game_ui *ui, const char *encoding,
984\c const game_state *state);
985
986This function parses a string previously output by \cw{encode_ui()},
987and writes the decoded data back into the freshly-created \c{game_ui}
988structure provided. If the string is invalid, the function should do
989the best it can, which might just mean not changing the \c{game_ui}
990structure at all. This might happen if a save file is corrupted, or
991simply from a newer version that encodes more \c{game_ui} data. The
992current \c{game_state} is provided in case the function needs to
993refer to it for validation.
994
995Like \cw{encode_ui()}, \cw{decode_ui()} is optional. If a back-end
996doesn't need this function it can just set the pointer to \cw{NULL}.
997
998\S{backend-changed-state} \cw{changed_state()}
999
1000\c void (*changed_state)(game_ui *ui, const game_state *oldstate,
1001\c const game_state *newstate);
1002
1003This function is called by the mid-end whenever the current game
1004state changes, for any reason. Those reasons include:
1005
1006\b a fresh move being made by \cw{interpret_move()} and
1007\cw{execute_move()}
1008
1009\b a solve operation being performed by \cw{solve()} and
1010\cw{execute_move()}
1011
1012\b the user moving back and forth along the undo list by means of
1013the Undo and Redo operations
1014
1015\b the user selecting Restart to go back to the initial game state.
1016
1017The job of \cw{changed_state()} is to update the \c{game_ui} for
1018consistency with the new game state, if any update is necessary. For
1019example, Same Game stores data about the currently selected tile
1020group in its \c{game_ui}, and this data is intrinsically related to
1021the game state it was derived from. So it's very likely to become
1022invalid when the game state changes; thus, Same Game's
1023\cw{changed_state()} function clears the current selection whenever
1024it is called.
1025
1026When \cw{anim_length()} or \cw{flash_length()} are called, you can
1027be sure that there has been a previous call to \cw{changed_state()}.
1028So \cw{changed_state()} can set up data in the \c{game_ui} which will
1029be read by \cw{anim_length()} and \cw{flash_length()}, and those
1030functions will not have to worry about being called without the data
1031having been initialised.
1032
1033\H{backend-moves} Making moves
1034
1035This section describes the functions which actually make moves in
1036the game: that is, the functions which process user input and end up
1037producing new \c{game_state}s.
1038
1039\S{backend-interpret-move} \cw{interpret_move()}
1040
1041\c char *(*interpret_move)(const game_state *state, game_ui *ui,
1042\c const game_drawstate *ds,
1043\c int x, int y, int button);
1044
1045This function receives user input and processes it. Its input
1046parameters are the current \c{game_state}, the current \c{game_ui}
1047and the current \c{game_drawstate}, plus details of the input event.
1048\c{button} is either an ASCII value or a special code (listed below)
1049indicating an arrow or function key or a mouse event; when
1050\c{button} is a mouse event, \c{x} and \c{y} contain the pixel
1051coordinates of the mouse pointer relative to the top left of the
1052puzzle's drawing area.
1053
1054(The pointer to the \c{game_drawstate} is marked \c{const}, because
1055\c{interpret_move} should not write to it. The normal use of that
1056pointer will be to read the game's tile size parameter in order to
1057divide mouse coordinates by it.)
1058
1059\cw{interpret_move()} may return in four different ways:
1060
1061\b Returning \cw{MOVE_UNUSED} or \cw{MOVE_NO_EFFECT} indicates that no
1062action whatsoever occurred in response to the input event; the puzzle
1063was not interested in it at all. The distinction between this is that
1064\cw{MOVE_NO_EFFECT} implies that the state of the game is what makes
1065the event uninteresting, while \cw{MOVE_NO_EFFECT} means that the
1066event is intrinsically uninteresting. For example, a mouse click on
1067an already-revealed square in Mines might return \cw{MOVE_NO_EFFECT}
1068while a click outside the board would return \cw{MOVE_UNUSED}.
1069
1070\b Returning the special value \cw{MOVE_UI_UPDATE} indicates that the input
1071event has resulted in a change being made to the \c{game_ui} which
1072will require a redraw of the game window, but that no actual \e{move}
1073was made (i.e. no new \c{game_state} needs to be created).
1074
1075\b Returning anything else indicates that a move was made and that a
1076new \c{game_state} must be created. However, instead of actually
1077constructing a new \c{game_state} itself, this function is required
1078to return a printable ASCII string description of the details of the
1079move. This string will be passed to \cw{execute_move()}
1080(\k{backend-execute-move}) to actually create the new
1081\c{game_state}. (Encoding moves as strings in this way means that
1082the mid-end can keep the strings as well as the game states, and the
1083strings can be written to disk when saving the game and fed to
1084\cw{execute_move()} again on reloading.)
1085
1086The return value from \cw{interpret_move()} is expected to be
1087dynamically allocated if and only if it is not either \cw{NULL}
1088\e{or} one of the special string constants \cw{MOVE_UNUSED},
1089\cw{MOVE_NO_EFFECT}, or \cw{MOVE_UI_UPDATE}.
1090
1091After this function is called, the back end is permitted to rely on
1092some subsequent operations happening in sequence:
1093
1094\b \cw{execute_move()} will be called to convert this move
1095description into a new \c{game_state}
1096
1097\b \cw{changed_state()} will be called with the new \c{game_state}.
1098
1099This means that if \cw{interpret_move()} needs to do updates to the
1100\c{game_ui} which are easier to perform by referring to the new
1101\c{game_state}, it can safely leave them to be done in
1102\cw{changed_state()} and not worry about them failing to happen.
1103
1104(Note, however, that \cw{execute_move()} may \e{also} be called in
1105other circumstances. It is only \cw{interpret_move()} which can rely
1106on a subsequent call to \cw{changed_state()}.)
1107
1108The special key codes supported by this function are:
1109
1110\dt \cw{LEFT_BUTTON}, \cw{MIDDLE_BUTTON}, \cw{RIGHT_BUTTON}
1111
1112\dd Indicate that one of the mouse buttons was pressed down.
1113
1114\dt \cw{LEFT_DRAG}, \cw{MIDDLE_DRAG}, \cw{RIGHT_DRAG}
1115
1116\dd Indicate that the mouse was moved while one of the mouse buttons
1117was still down. The mid-end guarantees that when one of these events
1118is received, it will always have been preceded by a button-down
1119event (and possibly other drag events) for the same mouse button,
1120and no event involving another mouse button will have appeared in
1121between.
1122
1123\dt \cw{LEFT_RELEASE}, \cw{MIDDLE_RELEASE}, \cw{RIGHT_RELEASE}
1124
1125\dd Indicate that a mouse button was released. The mid-end
1126guarantees that when one of these events is received, it will always
1127have been preceded by a button-down event (and possibly some drag
1128events) for the same mouse button, and no event involving another
1129mouse button will have appeared in between.
1130
1131\dt \cw{CURSOR_UP}, \cw{CURSOR_DOWN}, \cw{CURSOR_LEFT},
1132\cw{CURSOR_RIGHT}
1133
1134\dd Indicate that an arrow key was pressed.
1135
1136\dt \cw{CURSOR_SELECT}, \cw{CURSOR_SELECT2}
1137
1138\dd On platforms which have one or two prominent \q{select} button
1139alongside their cursor keys, indicates that one of those buttons was
1140pressed. On other platforms, these represent the Enter (or Return)
1141and Space keys respectively.
1142
1143In addition, there are some modifiers which can be bitwise-ORed into
1144the \c{button} parameter:
1145
1146\dt \cw{MOD_CTRL}, \cw{MOD_SHFT}
1147
1148\dd These indicate that the Control or Shift key was pressed alongside
1149the key. They only apply to the cursor keys and the ASCII horizontal
1150tab character \cw{\\t}, not to mouse buttons or anything else.
1151
1152\dt \cw{MOD_NUM_KEYPAD}
1153
1154\dd This applies to some ASCII values, and indicates that the key
1155code was input via the numeric keypad rather than the main keyboard.
1156Some puzzles may wish to treat this differently (for example, a
1157puzzle might want to use the numeric keypad as an eight-way
1158directional pad), whereas others might not (a game involving numeric
1159input probably just wants to treat the numeric keypad as numbers).
1160
1161\dt \cw{MOD_MASK}
1162
1163\dd This mask is the bitwise OR of all the available modifiers; you
1164can bitwise-AND with \cw{~MOD_MASK} to strip all the modifiers off any
1165input value; as this is a common operation, the
1166\cw{STRIP_BUTTON_MODIFIERS()} macro can do this for you (see
1167\k{utils-strip-button-modifiers}).
1168
1169\S{backend-execute-move} \cw{execute_move()}
1170
1171\c game_state *(*execute_move)(const game_state *state, char *move);
1172
1173This function takes an input \c{game_state} and a move string as
1174output from \cw{interpret_move()}. It returns a newly allocated
1175\c{game_state} which contains the result of applying the specified
1176move to the input game state.
1177
1178This function may return \cw{NULL} if it cannot parse the move
1179string (and this is definitely preferable to crashing or failing an
1180assertion, since one way this can happen is if loading a corrupt
1181save file). However, it must not return \cw{NULL} for any move
1182string that really was output from \cw{interpret_move()}: this is
1183punishable by assertion failure in the mid-end.
1184
1185\S{backend-can-solve} \c{can_solve}
1186
1187\c bool can_solve;
1188
1189This field is set to \cw{true} if the game's \cw{solve()} function
1190does something. If it's set to \cw{false}, the game will not even
1191offer the \q{Solve} menu option.
1192
1193\S{backend-solve} \cw{solve()}
1194
1195\c char *(*solve)(const game_state *orig, const game_state *curr,
1196\c const char *aux, const char **error);
1197
1198This function is called when the user selects the \q{Solve} option
1199from the menu. If \cw{can_solve} is \cw{false} then it will never
1200be called and can be \cw{NULL}.
1201
1202It is passed two input game states: \c{orig} is the game state from
1203the very start of the puzzle, and \c{curr} is the current one.
1204(Different games find one or other or both of these convenient.) It
1205is also passed the \c{aux} string saved by \cw{new_desc()}
1206(\k{backend-new-desc}), in case that encodes important information
1207needed to provide the solution.
1208
1209If this function is unable to produce a solution (perhaps, for
1210example, the game has no in-built solver so it can only solve
1211puzzles it invented internally and has an \c{aux} string for) then
1212it may return \cw{NULL}. If it does this, it must also set
1213\c{*error} to an error message to be presented to the user (such as
1214\q{Solution not known for this puzzle}); that error message is not
1215expected to be dynamically allocated.
1216
1217If this function \e{does} produce a solution, it returns a printable
1218ASCII move string suitable for feeding to \cw{execute_move()}
1219(\k{backend-execute-move}). Like a (non-empty) string returned from
1220\cw{interpret_move()}, the returned string should be dynamically
1221allocated.
1222
1223\H{backend-drawing} Drawing the game graphics
1224
1225This section discusses the back end functions that deal with
1226drawing.
1227
1228\S{backend-new-drawstate} \cw{new_drawstate()}
1229
1230\c game_drawstate *(*new_drawstate)(drawing *dr,
1231\c const game_state *state);
1232
1233This function allocates and returns a new \c{game_drawstate}
1234structure for drawing a particular puzzle. It is passed a pointer to
1235a \c{game_state}, in case it needs to refer to that when setting up
1236any initial data.
1237
1238This function may not rely on the puzzle having been newly started;
1239a new draw state can be constructed at any time if the front end
1240requests a forced redraw. For games like Pattern, in which initial
1241game states are much simpler than general ones, this might be
1242important to keep in mind.
1243
1244The parameter \c{dr} is a drawing object (see \k{drawing}) which the
1245function might need to use to allocate blitters. (However, this
1246isn't recommended; it's usually more sensible to wait to allocate a
1247blitter until \cw{set_size()} is called, because that way you can
1248tailor it to the scale at which the puzzle is being drawn.)
1249
1250\S{backend-free-drawstate} \cw{free_drawstate()}
1251
1252\c void (*free_drawstate)(drawing *dr, game_drawstate *ds);
1253
1254This function frees a \c{game_drawstate} structure, and any
1255subsidiary allocations contained within it.
1256
1257The parameter \c{dr} is a drawing object (see \k{drawing}), which
1258might be required if you are freeing a blitter.
1259
1260\S{backend-preferred-tilesize} \c{preferred_tilesize}
1261
1262\c int preferred_tilesize;
1263
1264Each game is required to define a single integer parameter which
1265expresses, in some sense, the scale at which it is drawn. This is
1266described in the APIs as \cq{tilesize}, since most puzzles are on a
1267square (or possibly triangular or hexagonal) grid and hence a
1268sensible interpretation of this parameter is to define it as the
1269size of one grid tile in pixels; however, there's no actual
1270requirement that the \q{tile size} be proportional to the game
1271window size. Window size is required to increase monotonically with
1272\q{tile size}, however.
1273
1274The data element \c{preferred_tilesize} indicates the tile size which
1275should be used in the absence of a good reason to do otherwise (such
1276as the screen being too small to fit the whole puzzle, or the user
1277explicitly requesting a resize).
1278
1279\S{backend-compute-size} \cw{compute_size()}
1280
1281\c void (*compute_size)(const game_params *params, int tilesize,
1282\c const game_ui *ui, int *x, int *y);
1283
1284This function is passed a \c{game_params} structure and a tile size.
1285It returns, in \c{*x} and \c{*y}, the size in pixels of the drawing
1286area that would be required to render a puzzle with those parameters
1287at that tile size.
1288
1289\S{backend-set-size} \cw{set_size()}
1290
1291\c void (*set_size)(drawing *dr, game_drawstate *ds,
1292\c const game_params *params, int tilesize);
1293
1294This function is responsible for setting up a \c{game_drawstate} to
1295draw at a given tile size. Typically this will simply involve
1296copying the supplied \c{tilesize} parameter into a \c{tilesize}
1297field inside the draw state; for some more complex games it might
1298also involve setting up other dimension fields, or possibly
1299allocating a blitter (see \k{drawing-blitter}).
1300
1301The parameter \c{dr} is a drawing object (see \k{drawing}), which is
1302required if a blitter needs to be allocated.
1303
1304Back ends may assume (and may enforce by assertion) that this
1305function will be called at most once for any \c{game_drawstate}. If
1306a puzzle needs to be redrawn at a different size, the mid-end will
1307create a fresh drawstate.
1308
1309\S{backend-colours} \cw{colours()}
1310
1311\c float *(*colours)(frontend *fe, int *ncolours);
1312
1313This function is responsible for telling the front end what colours
1314the puzzle will need to draw itself.
1315
1316It returns the number of colours required in \c{*ncolours}, and the
1317return value from the function itself is a dynamically allocated
1318array of three times that many \c{float}s, containing the red, green
1319and blue components of each colour respectively as numbers in the
1320range [0,1].
1321
1322The second parameter passed to this function is a front end handle.
1323The only things it is permitted to do with this handle are to call
1324the front-end function called \cw{frontend_default_colour()} (see
1325\k{frontend-default-colour}) or the utility function called
1326\cw{game_mkhighlight()} (see \k{utils-game-mkhighlight}). (The
1327latter is a wrapper on the former, so front end implementors only
1328need to provide \cw{frontend_default_colour()}.) This allows
1329\cw{colours()} to take local configuration into account when
1330deciding on its own colour allocations. Most games use the front
1331end's default colour as their background, apart from a few which
1332depend on drawing relief highlights so they adjust the background
1333colour if it's too light for highlights to show up against it.
1334
1335The first colour in the list is slightly special. The mid-end fills
1336the drawing area with it before the first call to \cw{redraw()} (see
1337\k{backend-redraw}). Some front ends also use it fill the part of the
1338puzzle window outside the puzzle. This means that it is usually
1339sensible to make colour 0 the background colour for the puzzle.
1340
1341Note that the colours returned from this function are for
1342\e{drawing}, not for printing. Printing has an entirely different
1343colour allocation policy.
1344
1345\S{backend-anim-length} \cw{anim_length()}
1346
1347\c float (*anim_length)(const game_state *oldstate,
1348\c const game_state *newstate,
1349\c int dir, game_ui *ui);
1350
1351This function is called when a move is made, undone or redone. It is
1352given the old and the new \c{game_state}, and its job is to decide
1353whether the transition between the two needs to be animated or can
1354be instant.
1355
1356\c{oldstate} is the state that was current until this call;
1357\c{newstate} is the state that will be current after it. \c{dir}
1358specifies the chronological order of those states: if it is
1359positive, then the transition is the result of a move or a redo (and
1360so \c{newstate} is the later of the two moves), whereas if it is
1361negative then the transition is the result of an undo (so that
1362\c{newstate} is the \e{earlier} move).
1363
1364If this function decides the transition should be animated, it
1365returns the desired length of the animation in seconds. If not, it
1366returns zero.
1367
1368State changes as a result of a Restart operation are never animated;
1369the mid-end will handle them internally and never consult this
1370function at all. State changes as a result of Solve operations are
1371also not animated by default, although you can change this for a
1372particular game by setting a flag in \c{flags} (\k{backend-flags}).
1373
1374The function is also passed a pointer to the local \c{game_ui}. It
1375may refer to information in here to help with its decision (see
1376\k{writing-conditional-anim} for an example of this), and/or it may
1377\e{write} information about the nature of the animation which will
1378be read later by \cw{redraw()}.
1379
1380When this function is called, it may rely on \cw{changed_state()}
1381having been called previously, so if \cw{anim_length()} needs to
1382refer to information in the \c{game_ui}, then \cw{changed_state()}
1383is a reliable place to have set that information up.
1384
1385Move animations do not inhibit further input events. If the user
1386continues playing before a move animation is complete, the animation
1387will be abandoned and the display will jump straight to the final
1388state.
1389
1390\S{backend-flash-length} \cw{flash_length()}
1391
1392\c float (*flash_length)(const game_state *oldstate,
1393\c const game_state *newstate,
1394\c int dir, game_ui *ui);
1395
1396This function is called when a move is completed. (\q{Completed}
1397means that not only has the move been made, but any animation which
1398accompanied it has finished.) It decides whether the transition from
1399\c{oldstate} to \c{newstate} merits a \q{flash}.
1400
1401A flash is much like a move animation, but it is \e{not} interrupted
1402by further user interface activity; it runs to completion in
1403parallel with whatever else might be going on on the display. The
1404only thing which will rush a flash to completion is another flash.
1405
1406The purpose of flashes is to indicate that the game has been
1407completed. They were introduced as a separate concept from move
1408animations because of Net: the habit of most Net players (and
1409certainly me) is to rotate a tile into place and immediately lock
1410it, then move on to another tile. When you make your last move, at
1411the instant the final tile is rotated into place the screen starts
1412to flash to indicate victory \dash but if you then press the lock
1413button out of habit, then the move animation is cancelled, and the
1414victory flash does not complete. (And if you \e{don't} press the
1415lock button, the completed grid will look untidy because there will
1416be one unlocked square.) Therefore, I introduced a specific concept
1417of a \q{flash} which is separate from a move animation and can
1418proceed in parallel with move animations and any other display
1419activity, so that the victory flash in Net is not cancelled by that
1420final locking move.
1421
1422The input parameters to \cw{flash_length()} are exactly the same as
1423the ones to \cw{anim_length()}: see \k{backend-anim-length}.
1424
1425Just like \cw{anim_length()}, when this function is called, it may
1426rely on \cw{changed_state()} having been called previously, so if it
1427needs to refer to information in the \c{game_ui} then
1428\cw{changed_state()} is a reliable place to have set that
1429information up.
1430
1431(Some games use flashes to indicate defeat as well as victory;
1432Mines, for example, flashes in a different colour when you tread on
1433a mine from the colour it uses when you complete the game. In order
1434to achieve this, its \cw{flash_length()} function has to store a
1435flag in the \c{game_ui} to indicate which flash type is required.)
1436
1437\S{backend-get-cursor-location} \cw{get_cursor_location()}
1438
1439\c void (*get_cursor_location)(const game_ui *ui,
1440\c const game_drawstate *ds,
1441\c const game_state *state,
1442\c const game_params *params,
1443\c int *x, int *y,
1444\c int *w, int *h);
1445
1446This function queries the backend for the rectangular region
1447containing the cursor (in games that have one), or other region of
1448interest.
1449
1450This function is called by only
1451\cw{midend_get_cursor_location()} (\k{midend-get-cursor-location}). Its
1452purpose is to allow front ends to query the location of the backend's
1453cursor. With knowledge of this location, a front end can, for example,
1454ensure that the region of interest remains visible if the puzzle is
1455too big to fit on the screen at once.
1456
1457On returning, \cw{*x}, \cw{*y} should be set to the X and Y
1458coordinates of the upper-left corner of the rectangular region of
1459interest, and \cw{*w} and \cw{*h} should be the width and height of
1460that region, respectively. In the event that a cursor is not visible
1461on screen, this function should return and leave the return parameters
1462untouched \dash the midend will notice this. The backend need not
1463bother checking that \cw{x}, \cw{y}, \cw{w} and \cw{h} are
1464non-\cw{NULL} \dash the midend guarantees that they will not be.
1465
1466Defining what constitutes a \q{region of interest} is left up to the
1467backend. If a game provides a conventional cursor \dash such as Mines,
1468Solo, or any of the other grid-based games \dash the most logical
1469choice is of course the location of the cursor itself. However, in
1470other cases such as Cube or Inertia, there is no \q{cursor} in the
1471conventional sense \dash the player instead controls an object moving
1472around the screen. In these cases, it makes sense to define the region
1473of interest as the bounding box of the player object or another
1474sensible region \dash such as the grid square the player is sitting on
1475in Cube.
1476
1477If a backend does not provide a cursor mechanism at all, the backend
1478is free to provide an empty implementation of this function, or a
1479\cw{NULL} pointer in the \cw{game} structure \dash the midend will
1480notice either of these cases and behave appropriately.
1481
1482\S{backend-status} \cw{status()}
1483
1484\c int (*status)(const game_state *state);
1485
1486This function returns a status value indicating whether the current
1487game is still in play, or has been won, or has been conclusively lost.
1488The mid-end uses this to implement \cw{midend_status()}
1489(\k{midend-status}).
1490
1491The return value should be +1 if the game has been successfully
1492solved. If the game has been lost in a situation where further play is
1493unlikely, the return value should be -1. If neither is true (so play
1494is still ongoing), return zero.
1495
1496Front ends may wish to use a non-zero status as a cue to proactively
1497offer the option of starting a new game. Therefore, back ends should
1498not return -1 if the game has been \e{technically} lost but undoing
1499and continuing is still a realistic possibility.
1500
1501(For instance, games with hidden information such as Guess or Mines
1502might well return a non-zero status whenever they reveal the solution,
1503whether or not the player guessed it correctly, on the grounds that a
1504player would be unlikely to hide the solution and continue playing
1505after the answer was spoiled. On the other hand, games where you can
1506merely get into a dead end such as Same Game or Inertia might choose
1507to return 0 in that situation, on the grounds that the player would
1508quite likely press Undo and carry on playing.)
1509
1510\S{backend-redraw} \cw{redraw()}
1511
1512\c void (*redraw)(drawing *dr, game_drawstate *ds,
1513\c const game_state *oldstate,
1514\c const game_state *newstate,
1515\c int dir, const game_ui *ui,
1516\c float anim_time, float flash_time);
1517
1518This function is responsible for actually drawing the contents of
1519the game window, and for redrawing every time the game state or the
1520\c{game_ui} changes.
1521
1522The parameter \c{dr} is a drawing object which may be passed to the
1523drawing API functions (see \k{drawing} for documentation of the
1524drawing API). This function may not save \c{dr} and use it
1525elsewhere; it must only use it for calling back to the drawing API
1526functions within its own lifetime.
1527
1528\c{ds} is the local \c{game_drawstate}, of course, and \c{ui} is the
1529local \c{game_ui}.
1530
1531\c{newstate} is the semantically-current game state, and is always
1532non-\cw{NULL}. If \c{oldstate} is also non-\cw{NULL}, it means that
1533a move has recently been made and the game is still in the process
1534of displaying an animation linking the old and new states; in this
1535situation, \c{anim_time} will give the length of time (in seconds)
1536that the animation has already been running. If \c{oldstate} is
1537\cw{NULL}, then \c{anim_time} is unused (and will hopefully be set
1538to zero to avoid confusion).
1539
1540\c{dir} specifies the chronological order of those states: if it is
1541positive, then the transition is the result of a move or a redo (and
1542so \c{newstate} is the later of the two moves), whereas if it is
1543negative then the transition is the result of an undo (so that
1544\c{newstate} is the \e{earlier} move). This allows move animations
1545that are not time-symmetric (such as Inertia, where gems are consumed
1546during the animation) to be drawn the right way round.
1547
1548\c{flash_time}, if it is is non-zero, denotes that the game is in
1549the middle of a flash, and gives the time since the start of the
1550flash. See \k{backend-flash-length} for general discussion of
1551flashes.
1552
1553The very first time this function is called for a new
1554\c{game_drawstate}, it is expected to redraw the \e{entire} drawing
1555area. Since this often involves drawing visual furniture which is
1556never subsequently altered, it is often simplest to arrange this by
1557having a special \q{first time} flag in the draw state, and
1558resetting it after the first redraw. This function can assume that
1559the mid-end has filled the drawing area with colour 0 before the first
1560call.
1561
1562When this function (or any subfunction) calls the drawing API, it is
1563expected to pass colour indices which were previously defined by the
1564\cw{colours()} function.
1565
1566\H{backend-printing} Printing functions
1567
1568This section discusses the back end functions that deal with
1569printing puzzles out on paper.
1570
1571\S{backend-can-print} \c{can_print}
1572
1573\c bool can_print;
1574
1575This flag is set to \cw{true} if the puzzle is capable of printing
1576itself on paper. (This makes sense for some puzzles, such as Solo,
1577which can be filled in with a pencil. Other puzzles, such as
1578Twiddle, inherently involve moving things around and so would not
1579make sense to print.)
1580
1581If this flag is \cw{false}, then the functions \cw{print_size()}
1582and \cw{print()} will never be called and can be \cw{NULL}.
1583
1584\S{backend-can-print-in-colour} \c{can_print_in_colour}
1585
1586\c bool can_print_in_colour;
1587
1588This flag is set to \cw{true} if the puzzle is capable of printing
1589itself differently when colour is available. For example, Map can
1590actually print coloured regions in different \e{colours} rather than
1591resorting to cross-hatching.
1592
1593If the \c{can_print} flag is \cw{false}, then this flag will be
1594ignored.
1595
1596\S{backend-print-size} \cw{print_size()}
1597
1598\c void (*print_size)(const game_params *params, const game_ui *ui,
1599\c float *x, float *y);
1600
1601This function is passed a \c{game_params} structure and a tile size.
1602It returns, in \c{*x} and \c{*y}, the preferred size in
1603\e{millimetres} of that puzzle if it were to be printed out on paper.
1604
1605If the \c{can_print} flag is \cw{false}, this function will never be
1606called.
1607
1608\S{backend-print} \cw{print()}
1609
1610\c void (*print)(drawing *dr, const game_state *state,
1611\c const game_ui *ui, int tilesize);
1612
1613This function is called when a puzzle is to be printed out on paper.
1614It should use the drawing API functions (see \k{drawing}) to print
1615itself.
1616
1617This function is separate from \cw{redraw()} because it is often
1618very different:
1619
1620\b The printing function may not depend on pixel accuracy, since
1621printer resolution is variable. Draw as if your canvas had infinite
1622resolution.
1623
1624\b The printing function sometimes needs to display things in a
1625completely different style. Net, for example, is very different as
1626an on-screen puzzle and as a printed one.
1627
1628\b The printing function is often much simpler since it has no need
1629to deal with repeated partial redraws.
1630
1631However, there's no reason the printing and redraw functions can't
1632share some code if they want to.
1633
1634When this function (or any subfunction) calls the drawing API, the
1635colour indices it passes should be colours which have been allocated
1636by the \cw{print_*_colour()} functions within this execution of
1637\cw{print()}. This is very different from the fixed small number of
1638colours used in \cw{redraw()}, because printers do not have a
1639limitation on the total number of colours that may be used. Some
1640puzzles' printing functions might wish to allocate only one \q{ink}
1641colour and use it for all drawing; others might wish to allocate
1642\e{more} colours than are used on screen.
1643
1644One possible colour policy worth mentioning specifically is that a
1645puzzle's printing function might want to allocate the \e{same}
1646colour indices as are used by the redraw function, so that code
1647shared between drawing and printing does not have to keep switching
1648its colour indices. In order to do this, the simplest thing is to
1649make use of the fact that colour indices returned from
1650\cw{print_*_colour()} are guaranteed to be in increasing order from
1651zero. So if you have declared an \c{enum} defining three colours
1652\cw{COL_BACKGROUND}, \cw{COL_THIS} and \cw{COL_THAT}, you might then
1653write
1654
1655\c int c;
1656\c c = print_mono_colour(dr, 1); assert(c == COL_BACKGROUND);
1657\c c = print_mono_colour(dr, 0); assert(c == COL_THIS);
1658\c c = print_mono_colour(dr, 0); assert(c == COL_THAT);
1659
1660If the \c{can_print} flag is \cw{false}, this function will never be
1661called.
1662
1663\H{backend-misc} Miscellaneous
1664
1665\S{backend-can-format-as-text-ever} \c{can_format_as_text_ever}
1666
1667\c bool can_format_as_text_ever;
1668
1669This field is \cw{true} if the game supports formatting a
1670game state as ASCII text (typically ASCII art) for copying to the
1671clipboard and pasting into other applications. If it is \cw{false},
1672front ends will not offer the \q{Copy} command at all.
1673
1674If this field is \cw{true}, the game does not necessarily have to
1675support text formatting for \e{all} games: e.g. a game which can be
1676played on a square grid or a triangular one might only support copy
1677and paste for the former, because triangular grids in ASCII art are
1678just too difficult.
1679
1680If this field is \cw{false}, the functions
1681\cw{can_format_as_text_now()} (\k{backend-can-format-as-text-now})
1682and \cw{text_format()} (\k{backend-text-format}) are never called
1683and can be \cw{NULL}.
1684
1685\S{backend-can-format-as-text-now} \c{can_format_as_text_now()}
1686
1687\c bool (*can_format_as_text_now)(const game_params *params);
1688
1689This function is passed a \c{game_params}, and returns \cw{true} if
1690the game can support ASCII text output for this particular game type.
1691If it returns \cw{false}, front ends will grey out or otherwise
1692disable the \q{Copy} command.
1693
1694Games may enable and disable the copy-and-paste function for
1695different game \e{parameters}, but are currently constrained to
1696return the same answer from this function for all game \e{states}
1697sharing the same parameters. In other words, the \q{Copy} function
1698may enable or disable itself when the player changes game preset,
1699but will never change during play of a single game or when another
1700game of exactly the same type is generated.
1701
1702This function should not take into account aspects of the game
1703parameters which are not encoded by \cw{encode_params()}
1704(\k{backend-encode-params}) when the \c{full} parameter is set to
1705\cw{false}. Such parameters will not necessarily match up between a
1706call to this function and a subsequent call to \cw{text_format()}
1707itself. (For instance, game \e{difficulty} should not affect whether
1708the game can be copied to the clipboard. Only the actual visible
1709\e{shape} of the game can affect that.)
1710
1711\S{backend-text-format} \cw{text_format()}
1712
1713\c char *(*text_format)(const game_state *state);
1714
1715This function is passed a \c{game_state}, and returns a newly
1716allocated C string containing an ASCII representation of that game
1717state. It is used to implement the \q{Copy} operation in many front
1718ends.
1719
1720This function will only ever be called if the back end field
1721\c{can_format_as_text_ever} (\k{backend-can-format-as-text-ever}) is
1722\cw{true} \e{and} the function \cw{can_format_as_text_now()}
1723(\k{backend-can-format-as-text-now}) has returned \cw{true} for the
1724currently selected game parameters.
1725
1726The returned string may contain line endings (and will probably want
1727to), using the normal C internal \cq{\\n} convention. For
1728consistency between puzzles, all multi-line textual puzzle
1729representations should \e{end} with a newline as well as containing
1730them internally. (There are currently no puzzles which have a
1731one-line ASCII representation, so there's no precedent yet for
1732whether that should come with a newline or not.)
1733
1734\S{backend-wants-statusbar} \cw{wants_statusbar}
1735
1736\c bool wants_statusbar;
1737
1738This field is set to \cw{true} if the puzzle has a use for a textual
1739status line (to display score, completion status, currently active
1740tiles, etc). If the \c{redraw()} function ever intends to call
1741\c{status_bar()} in the drawing API (\k{drawing-status-bar}), then it
1742should set this flag to \c{true}.
1743
1744\S{backend-is-timed} \c{is_timed}
1745
1746\c bool is_timed;
1747
1748This field is \cw{true} if the puzzle is time-critical. If
1749so, the mid-end will maintain a game timer while the user plays.
1750
1751If this field is \cw{false}, then \cw{timing_state()} will never be
1752called and can be \cw{NULL}.
1753
1754\S{backend-timing-state} \cw{timing_state()}
1755
1756\c bool (*timing_state)(const game_state *state, game_ui *ui);
1757
1758This function is passed the current \c{game_state} and the local
1759\c{game_ui}; it returns \cw{true} if the game timer should currently
1760be running.
1761
1762A typical use for the \c{game_ui} in this function is to note when
1763the game was first completed (by setting a flag in
1764\cw{changed_state()} \dash see \k{backend-changed-state}), and
1765freeze the timer thereafter so that the user can undo back through
1766their solution process without altering their time.
1767
1768\S{backend-request-keys} \cw{request_keys()}
1769
1770\c key_label *(*request_keys)(const game_params *params, int *nkeys);
1771
1772This function returns a dynamically allocated array of \cw{key_label}
1773items containing the buttons the back end deems absolutely
1774\e{necessary} for gameplay, not an exhaustive list of every button the
1775back end could accept. For example, Keen only returns the digits up to
1776the game size and the backspace character, \cw{\\b}, even though it
1777\e{could} accept \cw{M}, as only these buttons are actually needed to
1778play the game. Each \cw{key_label} item contains the following fields:
1779
1780\c struct key_label {
1781\c char *label; /* label for frontend use */
1782\c int button; /* button to pass to midend */
1783\c } key_label;
1784
1785The \cw{label} field of this structure can (and often will) be set by
1786the backend to \cw{NULL}, in which case the midend will instead call
1787\c{button2label()} (\k{utils-button2label}) and fill in a generic
1788label. The \cw{button} field is the associated code that can be passed
1789to the midend when the frontend deems appropriate.
1790
1791If \cw{label} is not \cw{NULL}, then it's a dynamically allocated
1792string. Therefore, freeing an array of these structures needs more
1793than just a single free operatio. The function \c{free_keys()}
1794(\k{utils-free-keys}) can be used to free a whole array of these
1795structures conveniently.
1796
1797The backend should set \cw{*nkeys} to the number of elements in the
1798returned array.
1799
1800The field for this function pointer in the \cw{game} structure might
1801be set to \cw{NULL} (and indeed it is for the majority of the games)
1802to indicate that no additional buttons (apart from the cursor keys)
1803are required to play the game.
1804
1805This function should not be called directly by frontends. Instead,
1806frontends should use \cw{midend_request_keys()}
1807(\k{midend-request-keys}).
1808
1809\S{backend-current-key-label} \cw{current_key_label()}
1810
1811\c const char *(*current_key_label)(const game_ui *ui,
1812\c const game_state *state,
1813\c int button);
1814
1815This function is called to ask the back-end how certain keys should be
1816labelled on platforms (such a feature phones) where this is
1817conventional.
1818These labels are expected to reflect what the keys will do right now,
1819so they can change depending on the game and UI state.
1820
1821The \c{ui} and \c{state} arguments describe the state of the game for
1822which key labels are required.
1823The \c{button} argument is the same as the one passed to
1824\cw{interpret_move()}.
1825At present, the only values of \c{button} that can be passed to
1826\cw{current_key_label()} are \cw{CURSOR_SELECT} and \cw{CURSOR_SELECT2}.
1827The return value is a short string describing what the requested key
1828will do if pressed.
1829Usually the string should be a static string constant.
1830If it's really necessary to use a dynamically-allocated string, it
1831should remain valid until the next call to \cw{current_key_label()} or
1832\cw{free_ui()} with the same \cw{game_ui} (so it can be referenced from
1833the \cw{game_ui} and freed at the next one of those calls).
1834
1835There's no fixed upper limit on the length of string that this
1836function can return, but more than about 12 characters is likely to
1837cause problems for front-ends. If two buttons have the same effect,
1838their labels should be identical so that the front end can detect
1839this. Similarly, keys that do different things should have different
1840labels. The label should be an empty string (\cw{""}) if the key does
1841nothing.
1842
1843Like \cw{request_keys()}, the \cw{current_key_label} pointer in the
1844\c{game} structure is allowed to be \cw{NULL}, in which case the
1845mid-end will treat it as though it always returned \cw{""}.
1846
1847\S{backend-flags} \c{flags}
1848
1849\c int flags;
1850
1851This field contains miscellaneous per-backend flags. It consists of
1852the bitwise OR of some combination of the following:
1853
1854\dt \cw{BUTTON_BEATS(x,y)}
1855
1856\dd Given any \cw{x} and \cw{y} from the set \{\cw{LEFT_BUTTON},
1857\cw{MIDDLE_BUTTON}, \cw{RIGHT_BUTTON}\}, this macro evaluates to a
1858bit flag which indicates that when buttons \cw{x} and \cw{y} are
1859both pressed simultaneously, the mid-end should consider \cw{x} to
1860have priority. (In the absence of any such flags, the mid-end will
1861always consider the most recently pressed button to have priority.)
1862
1863\dt \cw{SOLVE_ANIMATES}
1864
1865\dd This flag indicates that moves generated by \cw{solve()}
1866(\k{backend-solve}) are candidates for animation just like any other
1867move. For most games, solve moves should not be animated, so the
1868mid-end doesn't even bother calling \cw{anim_length()}
1869(\k{backend-anim-length}), thus saving some special-case code in
1870each game. On the rare occasion that animated solve moves are
1871actually required, you can set this flag.
1872
1873\dt \cw{REQUIRE_RBUTTON}
1874
1875\dd This flag indicates that the puzzle cannot be usefully played
1876without the use of mouse buttons other than the left one. On some
1877PDA platforms, this flag is used by the front end to enable
1878right-button emulation through an appropriate gesture. Note that a
1879puzzle is not required to set this just because it \e{uses} the
1880right button, but only if its use of the right button is critical to
1881playing the game. (Slant, for example, uses the right button to
1882cycle through the three square states in the opposite order from the
1883left button, and hence can manage fine without it.)
1884
1885\dt \cw{REQUIRE_NUMPAD}
1886
1887\dd This flag indicates that the puzzle cannot be usefully played
1888without the use of number-key input. On some PDA platforms it causes
1889an emulated number pad to appear on the screen. Similarly to
1890\cw{REQUIRE_RBUTTON}, a puzzle need not specify this simply if its
1891use of the number keys is not critical.
1892
1893\H{backend-initiative} Things a back end may do on its own initiative
1894
1895This section describes a couple of things that a back end may choose
1896to do by calling functions elsewhere in the program, which would not
1897otherwise be obvious.
1898
1899\S{backend-newrs} Create a random state
1900
1901If a back end needs random numbers at some point during normal play,
1902it can create a fresh \c{random_state} by first calling
1903\c{get_random_seed} (\k{frontend-get-random-seed}) and then passing
1904the returned seed data to \cw{random_new()}.
1905
1906This is likely not to be what you want. If a puzzle needs randomness
1907in the middle of play, it's likely to be more sensible to store some
1908sort of random state within the \c{game_state}, so that the random
1909numbers are tied to the particular game state and hence the player
1910can't simply keep undoing their move until they get numbers they
1911like better.
1912
1913This facility is currently used only in Net, to implement the
1914\q{jumble} command, which sets every unlocked tile to a new random
1915orientation. This randomness \e{is} a reasonable use of the feature,
1916because it's non-adversarial \dash there's no advantage to the user
1917in getting different random numbers.
1918
1919\S{backend-supersede} Supersede its own game description
1920
1921In response to a move, a back end is (reluctantly) permitted to call
1922\cw{midend_supersede_game_desc()}:
1923
1924\c void midend_supersede_game_desc(midend *me,
1925\c char *desc, char *privdesc);
1926
1927When the user selects \q{New Game}, the mid-end calls
1928\cw{new_desc()} (\k{backend-new-desc}) to get a new game
1929description, and (as well as using that to generate an initial game
1930state) stores it for the save file and for telling to the user. The
1931function above overwrites that game description, and also splits it
1932in two. \c{desc} becomes the new game description which is provided
1933to the user on request, and is also the one used to construct a new
1934initial game state if the user selects \q{Restart}. \c{privdesc} is
1935a \q{private} game description, used to reconstruct the game's
1936initial state when reloading.
1937
1938The distinction between the two, as well as the need for this
1939function at all, comes from Mines. Mines begins with a blank grid
1940and no idea of where the mines actually are; \cw{new_desc()} does
1941almost no work in interactive mode, and simply returns a string
1942encoding the \c{random_state}. When the user first clicks to open a
1943tile, \e{then} Mines generates the mine positions, in such a way
1944that the game is soluble from that starting point. Then it uses this
1945function to supersede the random-state game description with a
1946proper one. But it needs two: one containing the initial click
1947location (because that's what you want to happen if you restart the
1948game, and also what you want to send to a friend so that they play
1949\e{the same game} as you), and one without the initial click
1950location (because when you save and reload the game, you expect to
1951see the same blank initial state as you had before saving).
1952
1953I should stress again that this function is a horrid hack. Nobody
1954should use it if they're not Mines; if you think you need to use it,
1955think again repeatedly in the hope of finding a better way to do
1956whatever it was you needed to do.
1957
1958\C{drawing} The drawing API
1959
1960The back end function \cw{redraw()} (\k{backend-redraw}) is required
1961to draw the puzzle's graphics on the window's drawing area. The back
1962end function \cw{print()} similarly draws the puzzle on paper, if the
1963puzzle is printable. To do this portably, the back end is provided
1964with a drawing API allowing it to talk directly to the front end. In
1965this chapter I document that API, both for the benefit of back end
1966authors trying to use it and for front end authors trying to implement
1967it.
1968
1969The drawing API as seen by the back end is a collection of global
1970functions, each of which takes a pointer to a \c{drawing} structure
1971(a \q{drawing object}). These objects are supplied as parameters to
1972the back end's \cw{redraw()} and \cw{print()} functions.
1973
1974In fact these global functions are not implemented directly by the
1975front end; instead, they are implemented centrally in \c{drawing.c}
1976and form a small piece of middleware. The drawing API as supplied by
1977the front end is a structure containing a set of function pointers,
1978plus a \cq{void *} handle which is passed to each of those
1979functions. This enables a single front end to switch between
1980multiple implementations of the drawing API if necessary. For
1981example, the Windows API supplies a printing mechanism integrated
1982into the same GDI which deals with drawing in windows, and therefore
1983the same API implementation can handle both drawing and printing;
1984but on Unix, the most common way for applications to print is by
1985producing PostScript output directly, and although it would be
1986\e{possible} to write a single (say) \cw{draw_rect()} function which
1987checked a global flag to decide whether to do GTK drawing operations
1988or output PostScript to a file, it's much nicer to have two separate
1989functions and switch between them as appropriate.
1990
1991When drawing, the puzzle window is indexed by pixel coordinates,
1992with the top left pixel defined as \cw{(0,0)} and the bottom right
1993pixel \cw{(w-1,h-1)}, where \c{w} and \c{h} are the width and height
1994values returned by the back end function \cw{compute_size()}
1995(\k{backend-compute-size}).
1996
1997When printing, the puzzle's print area is indexed in exactly the
1998same way (with an arbitrary tile size provided by the printing
1999module \c{printing.c}), to facilitate sharing of code between the
2000drawing and printing routines. However, when printing, puzzles may
2001no longer assume that the coordinate unit has any relationship to a
2002pixel; the printer's actual resolution might very well not even be
2003known at print time, so the coordinate unit might be smaller or
2004larger than a pixel. Puzzles' print functions should restrict
2005themselves to drawing geometric shapes rather than fiddly pixel
2006manipulation.
2007
2008\e{Puzzles' redraw functions may assume that the surface they draw
2009on is persistent}. It is the responsibility of every front end to
2010preserve the puzzle's window contents in the face of GUI window
2011expose issues and similar. It is not permissible to request that the
2012back end redraw any part of a window that it has already drawn,
2013unless something has actually changed as a result of making moves in
2014the puzzle.
2015
2016Most front ends accomplish this by having the drawing routines draw
2017on a stored bitmap rather than directly on the window, and copying
2018the bitmap to the window every time a part of the window needs to be
2019redrawn. Therefore, it is vitally important that whenever the back
2020end does any drawing it informs the front end of which parts of the
2021window it has accessed, and hence which parts need repainting. This
2022is done by calling \cw{draw_update()} (\k{drawing-draw-update}).
2023
2024Persistence of old drawing is convenient. However, a puzzle should
2025be very careful about how it updates its drawing area. The problem
2026is that some front ends do anti-aliased drawing: rather than simply
2027choosing between leaving each pixel untouched or painting it a
2028specified colour, an antialiased drawing function will \e{blend} the
2029original and new colours in pixels at a figure's boundary according
2030to the proportion of the pixel occupied by the figure (probably
2031modified by some heuristic fudge factors). All of this produces a
2032smoother appearance for curves and diagonal lines.
2033
2034An unfortunate effect of drawing an anti-aliased figure repeatedly
2035is that the pixels around the figure's boundary come steadily more
2036saturated with \q{ink} and the boundary appears to \q{spread out}.
2037Worse, redrawing a figure in a different colour won't fully paint
2038over the old boundary pixels, so the end result is a rather ugly
2039smudge.
2040
2041A good strategy to avoid unpleasant anti-aliasing artifacts is to
2042identify a number of rectangular areas which need to be redrawn,
2043clear them to the background colour, and then redraw their contents
2044from scratch, being careful all the while not to stray beyond the
2045boundaries of the original rectangles. The \cw{clip()} function
2046(\k{drawing-clip}) comes in very handy here. Games based on a square
2047grid can often do this fairly easily. Other games may need to be
2048somewhat more careful. For example, Loopy's redraw function first
2049identifies portions of the display which need to be updated. Then,
2050if the changes are fairly well localised, it clears and redraws a
2051rectangle containing each changed area. Otherwise, it gives up and
2052redraws the entire grid from scratch.
2053
2054It is possible to avoid clearing to background and redrawing from
2055scratch if one is very careful about which drawing functions one
2056uses: if a function is documented as not anti-aliasing under some
2057circumstances, you can rely on each pixel in a drawing either being
2058left entirely alone or being set to the requested colour, with no
2059blending being performed.
2060
2061In the following sections I first discuss the drawing API as seen by
2062the back end, and then the \e{almost} identical function-pointer
2063form seen by the front end.
2064
2065\H{drawing-backend} Drawing API as seen by the back end
2066
2067This section documents the back-end drawing API, in the form of
2068functions which take a \c{drawing} object as an argument.
2069
2070\S{drawing-draw-rect} \cw{draw_rect()}
2071
2072\c void draw_rect(drawing *dr, int x, int y, int w, int h,
2073\c int colour);
2074
2075Draws a filled rectangle in the puzzle window.
2076
2077\c{x} and \c{y} give the coordinates of the top left pixel of the
2078rectangle. \c{w} and \c{h} give its width and height. Thus, the
2079horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
2080inclusive, and the vertical extent from \c{y} to \c{y+h-1}
2081inclusive.
2082
2083\c{colour} is an integer index into the colours array returned by
2084the back end function \cw{colours()} (\k{backend-colours}).
2085
2086There is no separate pixel-plotting function. If you want to plot a
2087single pixel, the approved method is to use \cw{draw_rect()} with
2088width and height set to 1.
2089
2090Unlike many of the other drawing functions, this function is
2091guaranteed to be pixel-perfect: the rectangle will be sharply
2092defined and not anti-aliased or anything like that.
2093
2094This function may be used for both drawing and printing.
2095
2096\S{drawing-draw-rect-outline} \cw{draw_rect_outline()}
2097
2098\c void draw_rect_outline(drawing *dr, int x, int y, int w, int h,
2099\c int colour);
2100
2101Draws an outline rectangle in the puzzle window.
2102
2103\c{x} and \c{y} give the coordinates of the top left pixel of the
2104rectangle. \c{w} and \c{h} give its width and height. Thus, the
2105horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
2106inclusive, and the vertical extent from \c{y} to \c{y+h-1}
2107inclusive.
2108
2109\c{colour} is an integer index into the colours array returned by
2110the back end function \cw{colours()} (\k{backend-colours}).
2111
2112From a back end perspective, this function may be considered to be
2113part of the drawing API. However, front ends are not required to
2114implement it, since it is actually implemented centrally (in
2115\cw{misc.c}) as a wrapper on \cw{draw_polygon()}.
2116
2117This function may be used for both drawing and printing.
2118
2119\S{drawing-draw-rect-corner} \cw{draw_rect_corners()}
2120
2121\c void draw_rect_corners(drawing *dr, int cx, int cy, int r, int col);
2122
2123Draws four L-shapes at the corners of a square, in the manner of a
2124target reticule. This is a convenience function for back ends to use
2125to display a keyboard cursor (if they want one in that style).
2126
2127\c{cx} and \c{cy} give the coordinates of the centre of the square.
2128\c{r} is half the side length of the square, so that the corners are
2129at \cw{(cx-r,cy-r)}, \cw{(cx+r,cy-r)}, \cw{(cx-r,cy+r)} and
2130\cw{(cx+r,cy+r)}.
2131
2132\c{colour} is an integer index into the colours array returned by
2133the back end function \cw{colours()} (\k{backend-colours}).
2134
2135\S{drawing-draw-line} \cw{draw_line()}
2136
2137\c void draw_line(drawing *dr, int x1, int y1, int x2, int y2,
2138\c int colour);
2139
2140Draws a straight line in the puzzle window.
2141
2142\c{x1} and \c{y1} give the coordinates of one end of the line.
2143\c{x2} and \c{y2} give the coordinates of the other end. The line
2144drawn includes both those points.
2145
2146\c{colour} is an integer index into the colours array returned by
2147the back end function \cw{colours()} (\k{backend-colours}).
2148
2149Some platforms may perform anti-aliasing on this function.
2150Therefore, do not assume that you can erase a line by drawing the
2151same line over it in the background colour; anti-aliasing might lead
2152to perceptible ghost artefacts around the vanished line. Horizontal
2153and vertical lines, however, are pixel-perfect and not anti-aliased.
2154
2155This function may be used for both drawing and printing.
2156
2157\S{drawing-draw-polygon} \cw{draw_polygon()}
2158
2159\c void draw_polygon(drawing *dr, const int *coords, int npoints,
2160\c int fillcolour, int outlinecolour);
2161
2162Draws an outlined or filled polygon in the puzzle window.
2163
2164\c{coords} is an array of \cw{(2*npoints)} integers, containing the
2165\c{x} and \c{y} coordinates of \c{npoints} vertices.
2166
2167\c{fillcolour} and \c{outlinecolour} are integer indices into the
2168colours array returned by the back end function \cw{colours()}
2169(\k{backend-colours}). \c{fillcolour} may also be \cw{-1} to
2170indicate that the polygon should be outlined only.
2171
2172The polygon defined by the specified list of vertices is first
2173filled in \c{fillcolour}, if specified, and then outlined in
2174\c{outlinecolour}.
2175
2176\c{outlinecolour} may \e{not} be \cw{-1}; it must be a valid colour
2177(and front ends are permitted to enforce this by assertion). This is
2178because different platforms disagree on whether a filled polygon
2179should include its boundary line or not, so drawing \e{only} a
2180filled polygon would have non-portable effects. If you want your
2181filled polygon not to have a visible outline, you must set
2182\c{outlinecolour} to the same as \c{fillcolour}.
2183
2184Some platforms may perform anti-aliasing on this function.
2185Therefore, do not assume that you can erase a polygon by drawing the
2186same polygon over it in the background colour. Also, be prepared for
2187the polygon to extend a pixel beyond its obvious bounding box as a
2188result of this; if you really need it not to do this to avoid
2189interfering with other delicate graphics, you should probably use
2190\cw{clip()} (\k{drawing-clip}). You can rely on horizontal and
2191vertical lines not being anti-aliased.
2192
2193This function may be used for both drawing and printing.
2194
2195\S{drawing-draw-circle} \cw{draw_circle()}
2196
2197\c void draw_circle(drawing *dr, int cx, int cy, int radius,
2198\c int fillcolour, int outlinecolour);
2199
2200Draws an outlined or filled circle in the puzzle window.
2201
2202\c{cx} and \c{cy} give the coordinates of the centre of the circle.
2203\c{radius} gives its radius. The total horizontal pixel extent of
2204the circle is from \c{cx-radius+1} to \c{cx+radius-1} inclusive, and
2205the vertical extent similarly around \c{cy}.
2206
2207\c{fillcolour} and \c{outlinecolour} are integer indices into the
2208colours array returned by the back end function \cw{colours()}
2209(\k{backend-colours}). \c{fillcolour} may also be \cw{-1} to
2210indicate that the circle should be outlined only.
2211
2212The circle is first filled in \c{fillcolour}, if specified, and then
2213outlined in \c{outlinecolour}.
2214
2215\c{outlinecolour} may \e{not} be \cw{-1}; it must be a valid colour
2216(and front ends are permitted to enforce this by assertion). This is
2217because different platforms disagree on whether a filled circle
2218should include its boundary line or not, so drawing \e{only} a
2219filled circle would have non-portable effects. If you want your
2220filled circle not to have a visible outline, you must set
2221\c{outlinecolour} to the same as \c{fillcolour}.
2222
2223Some platforms may perform anti-aliasing on this function.
2224Therefore, do not assume that you can erase a circle by drawing the
2225same circle over it in the background colour. Also, be prepared for
2226the circle to extend a pixel beyond its obvious bounding box as a
2227result of this; if you really need it not to do this to avoid
2228interfering with other delicate graphics, you should probably use
2229\cw{clip()} (\k{drawing-clip}).
2230
2231This function may be used for both drawing and printing.
2232
2233\S{drawing-draw-thick-line} \cw{draw_thick_line()}
2234
2235\c void draw_thick_line(drawing *dr, float thickness,
2236\c float x1, float y1, float x2, float y2,
2237\c int colour)
2238
2239Draws a line in the puzzle window, giving control over the line's
2240thickness.
2241
2242\c{x1} and \c{y1} give the coordinates of one end of the line.
2243\c{x2} and \c{y2} give the coordinates of the other end.
2244\c{thickness} gives the thickness of the line, in pixels.
2245
2246Note that the coordinates and thickness are floating-point: the
2247continuous coordinate system is in effect here. It's important to
2248be able to address points with better-than-pixel precision in this
2249case, because one can't otherwise properly express the endpoints of
2250lines with both odd and even thicknesses.
2251
2252Some platforms may perform anti-aliasing on this function. The
2253precise pixels affected by a thick-line drawing operation may vary
2254between platforms, and no particular guarantees are provided.
2255Indeed, even horizontal or vertical lines may be anti-aliased.
2256
2257This function may be used for both drawing and printing.
2258
2259If the specified thickness is less than 1.0, 1.0 is used.
2260This ensures that thin lines are visible even at small scales.
2261
2262\S{drawing-draw-text} \cw{draw_text()}
2263
2264\c void draw_text(drawing *dr, int x, int y, int fonttype,
2265\c int fontsize, int align, int colour,
2266\c const char *text);
2267
2268Draws text in the puzzle window.
2269
2270\c{x} and \c{y} give the coordinates of a point. The relation of
2271this point to the location of the text is specified by \c{align},
2272which is a bitwise OR of horizontal and vertical alignment flags:
2273
2274\dt \cw{ALIGN_VNORMAL}
2275
2276\dd Indicates that \c{y} is aligned with the baseline of the text.
2277
2278\dt \cw{ALIGN_VCENTRE}
2279
2280\dd Indicates that \c{y} is aligned with the vertical centre of the
2281text. (In fact, it's aligned with the vertical centre of normal
2282\e{capitalised} text: displaying two pieces of text with
2283\cw{ALIGN_VCENTRE} at the same \cw{y}-coordinate will cause their
2284baselines to be aligned with one another, even if one is an ascender
2285and the other a descender.)
2286
2287\dt \cw{ALIGN_HLEFT}
2288
2289\dd Indicates that \c{x} is aligned with the left-hand end of the
2290text.
2291
2292\dt \cw{ALIGN_HCENTRE}
2293
2294\dd Indicates that \c{x} is aligned with the horizontal centre of
2295the text.
2296
2297\dt \cw{ALIGN_HRIGHT}
2298
2299\dd Indicates that \c{x} is aligned with the right-hand end of the
2300text.
2301
2302\c{fonttype} is either \cw{FONT_FIXED} or \cw{FONT_VARIABLE}, for a
2303monospaced or proportional font respectively. (No more detail than
2304that may be specified; it would only lead to portability issues
2305between different platforms.)
2306
2307\c{fontsize} is the desired size, in pixels, of the text. This size
2308corresponds to the overall point size of the text, not to any
2309internal dimension such as the cap-height.
2310
2311\c{colour} is an integer index into the colours array returned by
2312the back end function \cw{colours()} (\k{backend-colours}).
2313
2314This function may be used for both drawing and printing.
2315
2316The character set used to encode the text passed to this function is
2317specified \e{by the drawing object}, although it must be a superset
2318of ASCII. If a puzzle wants to display text that is not contained in
2319ASCII, it should use the \cw{text_fallback()} function
2320(\k{drawing-text-fallback}) to query the drawing object for an
2321appropriate representation of the characters it wants.
2322
2323\S{drawing-text-fallback} \cw{text_fallback()}
2324
2325\c char *text_fallback(drawing *dr, const char *const *strings,
2326\c int nstrings);
2327
2328This function is used to request a translation of UTF-8 text into
2329whatever character encoding is expected by the drawing object's
2330implementation of \cw{draw_text()}.
2331
2332The input is a list of strings encoded in UTF-8: \cw{nstrings} gives
2333the number of strings in the list, and \cw{strings[0]},
2334\cw{strings[1]}, ..., \cw{strings[nstrings-1]} are the strings
2335themselves.
2336
2337The returned string (which is dynamically allocated and must be
2338freed when finished with) is derived from the first string in the
2339list that the drawing object expects to be able to display reliably;
2340it will consist of that string translated into the character set
2341expected by \cw{draw_text()}.
2342
2343Drawing implementations are not required to handle anything outside
2344ASCII, but are permitted to assume that \e{some} string will be
2345successfully translated. So every call to this function must include
2346a string somewhere in the list (presumably the last element) which
2347consists of nothing but ASCII, to be used by any front end which
2348cannot handle anything else.
2349
2350For example, if a puzzle wished to display a string including a
2351multiplication sign (U+00D7 in Unicode, represented by the bytes C3
235297 in UTF-8), it might do something like this:
2353
2354\c static const char *const times_signs[] = { "\xC3\x97", "x" };
2355\c char *times_sign = text_fallback(dr, times_signs, 2);
2356\c sprintf(buffer, "%d%s%d", width, times_sign, height);
2357\c sfree(times_sign);
2358\c draw_text(dr, x, y, font, size, align, colour, buffer);
2359\c sfree(buffer);
2360
2361which would draw a string with a times sign in the middle on
2362platforms that support it, and fall back to a simple ASCII \cq{x}
2363where there was no alternative.
2364
2365\S{drawing-clip} \cw{clip()}
2366
2367\c void clip(drawing *dr, int x, int y, int w, int h);
2368
2369Establishes a clipping rectangle in the puzzle window.
2370
2371\c{x} and \c{y} give the coordinates of the top left pixel of the
2372clipping rectangle. \c{w} and \c{h} give its width and height. Thus,
2373the horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
2374inclusive, and the vertical extent from \c{y} to \c{y+h-1}
2375inclusive. (These are exactly the same semantics as
2376\cw{draw_rect()}.)
2377
2378After this call, no drawing operation will affect anything outside
2379the specified rectangle. The effect can be reversed by calling
2380\cw{unclip()} (\k{drawing-unclip}). The clipping rectangle is
2381pixel-perfect: pixels within the rectangle are affected as usual by
2382drawing functions; pixels outside are completely untouched.
2383
2384Back ends should not assume that a clipping rectangle will be
2385automatically cleared up by the front end if it's left lying around;
2386that might work on current front ends, but shouldn't be relied upon.
2387Always explicitly call \cw{unclip()}.
2388
2389This function may be used for both drawing and printing.
2390
2391\S{drawing-unclip} \cw{unclip()}
2392
2393\c void unclip(drawing *dr);
2394
2395Reverts the effect of a previous call to \cw{clip()}. After this
2396call, all drawing operations will be able to affect the entire
2397puzzle window again.
2398
2399This function may be used for both drawing and printing.
2400
2401\S{drawing-draw-update} \cw{draw_update()}
2402
2403\c void draw_update(drawing *dr, int x, int y, int w, int h);
2404
2405Informs the front end that a rectangular portion of the puzzle
2406window has been drawn on and needs to be updated.
2407
2408\c{x} and \c{y} give the coordinates of the top left pixel of the
2409update rectangle. \c{w} and \c{h} give its width and height. Thus,
2410the horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
2411inclusive, and the vertical extent from \c{y} to \c{y+h-1}
2412inclusive. (These are exactly the same semantics as
2413\cw{draw_rect()}.)
2414
2415The back end redraw function \e{must} call this function to report
2416any changes it has made to the window. Otherwise, those changes may
2417not become immediately visible, and may then appear at an
2418unpredictable subsequent time such as the next time the window is
2419covered and re-exposed.
2420
2421This function is only important when drawing. It may be called when
2422printing as well, but doing so is not compulsory, and has no effect.
2423(So if you have a shared piece of code between the drawing and
2424printing routines, that code may safely call \cw{draw_update()}.)
2425
2426\S{drawing-status-bar} \cw{status_bar()}
2427
2428\c void status_bar(drawing *dr, const char *text);
2429
2430Sets the text in the game's status bar to \c{text}. The text is copied
2431from the supplied buffer, so the caller is free to deallocate or
2432modify the buffer after use.
2433
2434(This function is not exactly a \e{drawing} function, but it shares
2435with the drawing API the property that it may only be called from
2436within the back end redraw function. And it's implemented by front
2437ends via the \c{drawing_api} function pointer table. So this is the
2438best place to document it.)
2439
2440The supplied text is filtered through the mid-end for optional
2441rewriting before being passed on to the front end; the mid-end will
2442prepend the current game time if the game is timed (and may in
2443future perform other rewriting if it seems like a good idea).
2444
2445This function is for drawing only; it must never be called during
2446printing.
2447
2448\S{drawing-blitter} Blitter functions
2449
2450This section describes a group of related functions which save and
2451restore a section of the puzzle window. This is most commonly used
2452to implement user interfaces involving dragging a puzzle element
2453around the window: at the end of each call to \cw{redraw()}, if an
2454object is currently being dragged, the back end saves the window
2455contents under that location and then draws the dragged object, and
2456at the start of the next \cw{redraw()} the first thing it does is to
2457restore the background.
2458
2459The front end defines an opaque type called a \c{blitter}, which is
2460capable of storing a rectangular area of a specified size.
2461
2462Blitter functions are for drawing only; they must never be called
2463during printing.
2464
2465\S2{drawing-blitter-new} \cw{blitter_new()}
2466
2467\c blitter *blitter_new(drawing *dr, int w, int h);
2468
2469Creates a new blitter object which stores a rectangle of size \c{w}
2470by \c{h} pixels. Returns a pointer to the blitter object.
2471
2472Blitter objects are best stored in the \c{game_drawstate}. A good
2473time to create them is in the \cw{set_size()} function
2474(\k{backend-set-size}), since it is at this point that you first
2475know how big a rectangle they will need to save.
2476
2477\S2{drawing-blitter-free} \cw{blitter_free()}
2478
2479\c void blitter_free(drawing *dr, blitter *bl);
2480
2481Disposes of a blitter object. Best called in \cw{free_drawstate()}.
2482(However, check that the blitter object is not \cw{NULL} before
2483attempting to free it; it is possible that a draw state might be
2484created and freed without ever having \cw{set_size()} called on it
2485in between.)
2486
2487\S2{drawing-blitter-save} \cw{blitter_save()}
2488
2489\c void blitter_save(drawing *dr, blitter *bl, int x, int y);
2490
2491This is a true drawing API function, in that it may only be called
2492from within the game redraw routine. It saves a rectangular portion
2493of the puzzle window into the specified blitter object.
2494
2495\c{x} and \c{y} give the coordinates of the top left corner of the
2496saved rectangle. The rectangle's width and height are the ones
2497specified when the blitter object was created.
2498
2499This function is required to cope and do the right thing if \c{x}
2500and \c{y} are out of range. (The right thing probably means saving
2501whatever part of the blitter rectangle overlaps with the visible
2502area of the puzzle window.)
2503
2504\S2{drawing-blitter-load} \cw{blitter_load()}
2505
2506\c void blitter_load(drawing *dr, blitter *bl, int x, int y);
2507
2508This is a true drawing API function, in that it may only be called
2509from within the game redraw routine. It restores a rectangular
2510portion of the puzzle window from the specified blitter object.
2511
2512\c{x} and \c{y} give the coordinates of the top left corner of the
2513rectangle to be restored. The rectangle's width and height are the
2514ones specified when the blitter object was created.
2515
2516Alternatively, you can specify both \c{x} and \c{y} as the special
2517value \cw{BLITTER_FROMSAVED}, in which case the rectangle will be
2518restored to exactly where it was saved from. (This is probably what
2519you want to do almost all the time, if you're using blitters to
2520implement draggable puzzle elements.)
2521
2522This function is required to cope and do the right thing if \c{x}
2523and \c{y} (or the equivalent ones saved in the blitter) are out of
2524range. (The right thing probably means restoring whatever part of
2525the blitter rectangle overlaps with the visible area of the puzzle
2526window.)
2527
2528If this function is called on a blitter which had previously been
2529saved from a partially out-of-range rectangle, then the parts of the
2530saved bitmap which were not visible at save time are undefined. If
2531the blitter is restored to a different position so as to make those
2532parts visible, the effect on the drawing area is undefined.
2533
2534\S{print-mono-colour} \cw{print_mono_colour()}
2535
2536\c int print_mono_colour(drawing *dr, int grey);
2537
2538This function allocates a colour index for a simple monochrome
2539colour during printing.
2540
2541\c{grey} must be 0 or 1. If \c{grey} is 0, the colour returned is
2542black; if \c{grey} is 1, the colour is white.
2543
2544\S{print-grey-colour} \cw{print_grey_colour()}
2545
2546\c int print_grey_colour(drawing *dr, float grey);
2547
2548This function allocates a colour index for a grey-scale colour
2549during printing.
2550
2551\c{grey} may be any number between 0 (black) and 1 (white); for
2552example, 0.5 indicates a medium grey.
2553
2554The chosen colour will be rendered to the limits of the printer's
2555halftoning capability.
2556
2557\S{print-hatched-colour} \cw{print_hatched_colour()}
2558
2559\c int print_hatched_colour(drawing *dr, int hatch);
2560
2561This function allocates a colour index which does not represent a
2562literal \e{colour}. Instead, regions shaded in this colour will be
2563hatched with parallel lines. The \c{hatch} parameter defines what
2564type of hatching should be used in place of this colour:
2565
2566\dt \cw{HATCH_SLASH}
2567
2568\dd This colour will be hatched by lines slanting to the right at 45
2569degrees.
2570
2571\dt \cw{HATCH_BACKSLASH}
2572
2573\dd This colour will be hatched by lines slanting to the left at 45
2574degrees.
2575
2576\dt \cw{HATCH_HORIZ}
2577
2578\dd This colour will be hatched by horizontal lines.
2579
2580\dt \cw{HATCH_VERT}
2581
2582\dd This colour will be hatched by vertical lines.
2583
2584\dt \cw{HATCH_PLUS}
2585
2586\dd This colour will be hatched by criss-crossing horizontal and
2587vertical lines.
2588
2589\dt \cw{HATCH_X}
2590
2591\dd This colour will be hatched by criss-crossing diagonal lines.
2592
2593Colours defined to use hatching may not be used for drawing lines or
2594text; they may only be used for filling areas. That is, they may be
2595used as the \c{fillcolour} parameter to \cw{draw_circle()} and
2596\cw{draw_polygon()}, and as the colour parameter to
2597\cw{draw_rect()}, but may not be used as the \c{outlinecolour}
2598parameter to \cw{draw_circle()} or \cw{draw_polygon()}, or with
2599\cw{draw_line()} or \cw{draw_text()}.
2600
2601\S{print-rgb-mono-colour} \cw{print_rgb_mono_colour()}
2602
2603\c int print_rgb_mono_colour(drawing *dr, float r, float g,
2604\c float b, float grey);
2605
2606This function allocates a colour index for a fully specified RGB
2607colour during printing.
2608
2609\c{r}, \c{g} and \c{b} may each be anywhere in the range from 0 to 1.
2610
2611If printing in black and white only, these values will be ignored,
2612and either pure black or pure white will be used instead, according
2613to the \q{grey} parameter. (The fallback colour is the same as the
2614one which would be allocated by \cw{print_mono_colour(grey)}.)
2615
2616\S{print-rgb-grey-colour} \cw{print_rgb_grey_colour()}
2617
2618\c int print_rgb_grey_colour(drawing *dr, float r, float g,
2619\c float b, float grey);
2620
2621This function allocates a colour index for a fully specified RGB
2622colour during printing.
2623
2624\c{r}, \c{g} and \c{b} may each be anywhere in the range from 0 to 1.
2625
2626If printing in black and white only, these values will be ignored,
2627and a shade of grey given by the \c{grey} parameter will be used
2628instead. (The fallback colour is the same as the one which would be
2629allocated by \cw{print_grey_colour(grey)}.)
2630
2631\S{print-rgb-hatched-colour} \cw{print_rgb_hatched_colour()}
2632
2633\c int print_rgb_hatched_colour(drawing *dr, float r, float g,
2634\c float b, float hatched);
2635
2636This function allocates a colour index for a fully specified RGB
2637colour during printing.
2638
2639\c{r}, \c{g} and \c{b} may each be anywhere in the range from 0 to 1.
2640
2641If printing in black and white only, these values will be ignored,
2642and a form of cross-hatching given by the \c{hatch} parameter will
2643be used instead; see \k{print-hatched-colour} for the possible
2644values of this parameter. (The fallback colour is the same as the
2645one which would be allocated by \cw{print_hatched_colour(hatch)}.)
2646
2647\S{print-line-width} \cw{print_line_width()}
2648
2649\c void print_line_width(drawing *dr, int width);
2650
2651This function is called to set the thickness of lines drawn during
2652printing. It is meaningless in drawing: all lines drawn by
2653\cw{draw_line()}, \cw{draw_circle} and \cw{draw_polygon()} are one
2654pixel in thickness. However, in printing there is no clear
2655definition of a pixel and so line widths must be explicitly
2656specified.
2657
2658The line width is specified in the usual coordinate system. Note,
2659however, that it is a hint only: the central printing system may
2660choose to vary line thicknesses at user request or due to printer
2661capabilities.
2662
2663\S{print-line-dotted} \cw{print_line_dotted()}
2664
2665\c void print_line_dotted(drawing *dr, bool dotted);
2666
2667This function is called to toggle the drawing of dotted lines during
2668printing. It is not supported during drawing.
2669
2670Setting \cq{dotted} to \cw{true} means that future lines drawn by
2671\cw{draw_line()}, \cw{draw_circle} and \cw{draw_polygon()} will be
2672dotted. Setting it to \cw{false} means that they will be solid.
2673
2674Some front ends may impose restrictions on the width of dotted
2675lines. Asking for a dotted line via this front end will override any
2676line width request if the front end requires it.
2677
2678\H{drawing-frontend} The drawing API as implemented by the front end
2679
2680This section describes the drawing API in the function-pointer form
2681in which it is implemented by a front end.
2682
2683(It isn't only platform-specific front ends which implement this
2684API; the platform-independent module \c{ps.c} also provides an
2685implementation of it which outputs PostScript. Thus, any platform
2686which wants to do PS printing can do so with minimum fuss.)
2687
2688The following entries all describe function pointer fields in a
2689structure called \c{drawing_api}. Each of the functions takes a
2690\cq{void *} context pointer, which it should internally cast back to
2691a more useful type. Thus, a drawing \e{object} (\c{drawing *)}
2692suitable for passing to the back end redraw or printing functions
2693is constructed by passing a \c{drawing_api} and a \cq{void *} to the
2694function \cw{drawing_new()} (see \k{drawing-new}).
2695
2696\S{drawingapi-draw-text} \cw{draw_text()}
2697
2698\c void (*draw_text)(void *handle, int x, int y, int fonttype,
2699\c int fontsize, int align, int colour,
2700\c const char *text);
2701
2702This function behaves exactly like the back end \cw{draw_text()}
2703function; see \k{drawing-draw-text}.
2704
2705\S{drawingapi-draw-rect} \cw{draw_rect()}
2706
2707\c void (*draw_rect)(void *handle, int x, int y, int w, int h,
2708\c int colour);
2709
2710This function behaves exactly like the back end \cw{draw_rect()}
2711function; see \k{drawing-draw-rect}.
2712
2713\S{drawingapi-draw-line} \cw{draw_line()}
2714
2715\c void (*draw_line)(void *handle, int x1, int y1, int x2, int y2,
2716\c int colour);
2717
2718This function behaves exactly like the back end \cw{draw_line()}
2719function; see \k{drawing-draw-line}.
2720
2721\S{drawingapi-draw-polygon} \cw{draw_polygon()}
2722
2723\c void (*draw_polygon)(void *handle, const int *coords, int npoints,
2724\c int fillcolour, int outlinecolour);
2725
2726This function behaves exactly like the back end \cw{draw_polygon()}
2727function; see \k{drawing-draw-polygon}.
2728
2729\S{drawingapi-draw-circle} \cw{draw_circle()}
2730
2731\c void (*draw_circle)(void *handle, int cx, int cy, int radius,
2732\c int fillcolour, int outlinecolour);
2733
2734This function behaves exactly like the back end \cw{draw_circle()}
2735function; see \k{drawing-draw-circle}.
2736
2737\S{drawingapi-draw-thick-line} \cw{draw_thick_line()}
2738
2739\c void draw_thick_line(drawing *dr, float thickness,
2740\c float x1, float y1, float x2, float y2,
2741\c int colour)
2742
2743This function behaves exactly like the back end
2744\cw{draw_thick_line()} function; see \k{drawing-draw-thick-line}.
2745
2746An implementation of this API which doesn't provide high-quality
2747rendering of thick lines is permitted to define this function
2748pointer to be \cw{NULL}. The middleware in \cw{drawing.c} will notice
2749and provide a low-quality alternative using \cw{draw_polygon()}.
2750
2751\S{drawingapi-draw-update} \cw{draw_update()}
2752
2753\c void (*draw_update)(void *handle, int x, int y, int w, int h);
2754
2755This function behaves exactly like the back end \cw{draw_update()}
2756function; see \k{drawing-draw-update}.
2757
2758An implementation of this API which only supports printing is
2759permitted to define this function pointer to be \cw{NULL} rather
2760than bothering to define an empty function. The middleware in
2761\cw{drawing.c} will notice and avoid calling it.
2762
2763\S{drawingapi-clip} \cw{clip()}
2764
2765\c void (*clip)(void *handle, int x, int y, int w, int h);
2766
2767This function behaves exactly like the back end \cw{clip()}
2768function; see \k{drawing-clip}.
2769
2770\S{drawingapi-unclip} \cw{unclip()}
2771
2772\c void (*unclip)(void *handle);
2773
2774This function behaves exactly like the back end \cw{unclip()}
2775function; see \k{drawing-unclip}.
2776
2777\S{drawingapi-start-draw} \cw{start_draw()}
2778
2779\c void (*start_draw)(void *handle);
2780
2781This function is called at the start of drawing. It allows the front
2782end to initialise any temporary data required to draw with, such as
2783device contexts.
2784
2785Implementations of this API which do not provide drawing services
2786may define this function pointer to be \cw{NULL}; it will never be
2787called unless drawing is attempted.
2788
2789\S{drawingapi-end-draw} \cw{end_draw()}
2790
2791\c void (*end_draw)(void *handle);
2792
2793This function is called at the end of drawing. It allows the front
2794end to do cleanup tasks such as deallocating device contexts and
2795scheduling appropriate GUI redraw events.
2796
2797Implementations of this API which do not provide drawing services
2798may define this function pointer to be \cw{NULL}; it will never be
2799called unless drawing is attempted.
2800
2801\S{drawingapi-status-bar} \cw{status_bar()}
2802
2803\c void (*status_bar)(void *handle, const char *text);
2804
2805This function behaves exactly like the back end \cw{status_bar()}
2806function; see \k{drawing-status-bar}.
2807
2808Front ends implementing this function need not worry about it being
2809called repeatedly with the same text; the middleware code in
2810\cw{status_bar()} will take care of this.
2811
2812Implementations of this API which do not provide drawing services
2813may define this function pointer to be \cw{NULL}; it will never be
2814called unless drawing is attempted.
2815
2816\S{drawingapi-blitter-new} \cw{blitter_new()}
2817
2818\c blitter *(*blitter_new)(void *handle, int w, int h);
2819
2820This function behaves exactly like the back end \cw{blitter_new()}
2821function; see \k{drawing-blitter-new}.
2822
2823Implementations of this API which do not provide drawing services
2824may define this function pointer to be \cw{NULL}; it will never be
2825called unless drawing is attempted.
2826
2827\S{drawingapi-blitter-free} \cw{blitter_free()}
2828
2829\c void (*blitter_free)(void *handle, blitter *bl);
2830
2831This function behaves exactly like the back end \cw{blitter_free()}
2832function; see \k{drawing-blitter-free}.
2833
2834Implementations of this API which do not provide drawing services
2835may define this function pointer to be \cw{NULL}; it will never be
2836called unless drawing is attempted.
2837
2838\S{drawingapi-blitter-save} \cw{blitter_save()}
2839
2840\c void (*blitter_save)(void *handle, blitter *bl, int x, int y);
2841
2842This function behaves exactly like the back end \cw{blitter_save()}
2843function; see \k{drawing-blitter-save}.
2844
2845Implementations of this API which do not provide drawing services
2846may define this function pointer to be \cw{NULL}; it will never be
2847called unless drawing is attempted.
2848
2849\S{drawingapi-blitter-load} \cw{blitter_load()}
2850
2851\c void (*blitter_load)(void *handle, blitter *bl, int x, int y);
2852
2853This function behaves exactly like the back end \cw{blitter_load()}
2854function; see \k{drawing-blitter-load}.
2855
2856Implementations of this API which do not provide drawing services
2857may define this function pointer to be \cw{NULL}; it will never be
2858called unless drawing is attempted.
2859
2860\S{drawingapi-begin-doc} \cw{begin_doc()}
2861
2862\c void (*begin_doc)(void *handle, int pages);
2863
2864This function is called at the beginning of a printing run. It gives
2865the front end an opportunity to initialise any required printing
2866subsystem. It also provides the number of pages in advance.
2867
2868Implementations of this API which do not provide printing services
2869may define this function pointer to be \cw{NULL}; it will never be
2870called unless printing is attempted.
2871
2872\S{drawingapi-begin-page} \cw{begin_page()}
2873
2874\c void (*begin_page)(void *handle, int number);
2875
2876This function is called during printing, at the beginning of each
2877page. It gives the page number (numbered from 1 rather than 0, so
2878suitable for use in user-visible contexts).
2879
2880Implementations of this API which do not provide printing services
2881may define this function pointer to be \cw{NULL}; it will never be
2882called unless printing is attempted.
2883
2884\S{drawingapi-begin-puzzle} \cw{begin_puzzle()}
2885
2886\c void (*begin_puzzle)(void *handle, float xm, float xc,
2887\c float ym, float yc, int pw, int ph, float wmm);
2888
2889This function is called during printing, just before printing a
2890single puzzle on a page. It specifies the size and location of the
2891puzzle on the page.
2892
2893\c{xm} and \c{xc} specify the horizontal position of the puzzle on
2894the page, as a linear function of the page width. The front end is
2895expected to multiply the page width by \c{xm}, add \c{xc} (measured
2896in millimetres), and use the resulting x-coordinate as the left edge
2897of the puzzle.
2898
2899Similarly, \c{ym} and \c{yc} specify the vertical position of the
2900puzzle as a function of the page height: the page height times
2901\c{ym}, plus \c{yc} millimetres, equals the desired distance from
2902the top of the page to the top of the puzzle.
2903
2904(This unwieldy mechanism is required because not all printing
2905systems can communicate the page size back to the software. The
2906PostScript back end, for example, writes out PS which determines the
2907page size at print time by means of calling \cq{clippath}, and
2908centres the puzzles within that. Thus, exactly the same PS file
2909works on A4 or on US Letter paper without needing local
2910configuration, which simplifies matters.)
2911
2912\cw{pw} and \cw{ph} give the size of the puzzle in drawing API
2913coordinates. The printing system will subsequently call the puzzle's
2914own print function, which will in turn call drawing API functions in
2915the expectation that an area \cw{pw} by \cw{ph} units is available
2916to draw the puzzle on.
2917
2918Finally, \cw{wmm} gives the desired width of the puzzle in
2919millimetres. (The aspect ratio is expected to be preserved, so if
2920the desired puzzle height is also needed then it can be computed as
2921\cw{wmm*ph/pw}.)
2922
2923Implementations of this API which do not provide printing services
2924may define this function pointer to be \cw{NULL}; it will never be
2925called unless printing is attempted.
2926
2927\S{drawingapi-end-puzzle} \cw{end_puzzle()}
2928
2929\c void (*end_puzzle)(void *handle);
2930
2931This function is called after the printing of a specific puzzle is
2932complete.
2933
2934Implementations of this API which do not provide printing services
2935may define this function pointer to be \cw{NULL}; it will never be
2936called unless printing is attempted.
2937
2938\S{drawingapi-end-page} \cw{end_page()}
2939
2940\c void (*end_page)(void *handle, int number);
2941
2942This function is called after the printing of a page is finished.
2943
2944Implementations of this API which do not provide printing services
2945may define this function pointer to be \cw{NULL}; it will never be
2946called unless printing is attempted.
2947
2948\S{drawingapi-end-doc} \cw{end_doc()}
2949
2950\c void (*end_doc)(void *handle);
2951
2952This function is called after the printing of the entire document is
2953finished. This is the moment to close files, send things to the
2954print spooler, or whatever the local convention is.
2955
2956Implementations of this API which do not provide printing services
2957may define this function pointer to be \cw{NULL}; it will never be
2958called unless printing is attempted.
2959
2960\S{drawingapi-line-width} \cw{line_width()}
2961
2962\c void (*line_width)(void *handle, float width);
2963
2964This function is called to set the line thickness, during printing
2965only. Note that the width is a \cw{float} here, where it was an
2966\cw{int} as seen by the back end. This is because \cw{drawing.c} may
2967have scaled it on the way past.
2968
2969However, the width is still specified in the same coordinate system
2970as the rest of the drawing.
2971
2972Implementations of this API which do not provide printing services
2973may define this function pointer to be \cw{NULL}; it will never be
2974called unless printing is attempted.
2975
2976\S{drawingapi-line-dotted} \cw{line_dotted()}
2977
2978\c void (*line_dotted)(void *handle, bool dotted);
2979
2980This function is called to toggle drawing of dotted lines, during
2981printing only.
2982
2983Implementations of this API which do not provide printing services
2984may define this function pointer to be \cw{NULL}; it will never be
2985called unless printing is attempted.
2986
2987\S{drawingapi-text-fallback} \cw{text_fallback()}
2988
2989\c char *(*text_fallback)(void *handle, const char *const *strings,
2990\c int nstrings);
2991
2992This function behaves exactly like the back end \cw{text_fallback()}
2993function; see \k{drawing-text-fallback}.
2994
2995Implementations of this API which do not support any characters
2996outside ASCII may define this function pointer to be \cw{NULL}, in
2997which case the central code in \cw{drawing.c} will provide a default
2998implementation.
2999
3000\H{drawingapi-frontend} The drawing API as called by the front end
3001
3002There are a small number of functions provided in \cw{drawing.c}
3003which the front end needs to \e{call}, rather than helping to
3004implement. They are described in this section.
3005
3006\S{drawing-new} \cw{drawing_new()}
3007
3008\c drawing *drawing_new(const drawing_api *api, midend *me,
3009\c void *handle);
3010
3011This function creates a drawing object. It is passed a
3012\c{drawing_api}, which is a structure containing nothing but
3013function pointers; and also a \cq{void *} handle. The handle is
3014passed back to each function pointer when it is called.
3015
3016The \c{midend} parameter is used for rewriting the status bar
3017contents: \cw{status_bar()} (see \k{drawing-status-bar}) has to call
3018a function in the mid-end which might rewrite the status bar text.
3019If the drawing object is to be used only for printing, or if the
3020game is known not to call \cw{status_bar()}, this parameter may be
3021\cw{NULL}.
3022
3023\S{drawing-free} \cw{drawing_free()}
3024
3025\c void drawing_free(drawing *dr);
3026
3027This function frees a drawing object. Note that the \cq{void *}
3028handle is not freed; if that needs cleaning up it must be done by
3029the front end.
3030
3031\S{drawing-print-get-colour} \cw{print_get_colour()}
3032
3033\c void print_get_colour(drawing *dr, int colour,
3034\c bool printing_in_colour,
3035\c int *hatch, float *r, float *g, float *b);
3036
3037This function is called by the implementations of the drawing API
3038functions when they are called in a printing context. It takes a
3039colour index as input, and returns the description of the colour as
3040requested by the back end.
3041
3042\c{printing_in_colour} is \cw{true} iff the implementation is printing
3043in colour. This will alter the results returned if the colour in
3044question was specified with a black-and-white fallback value.
3045
3046If the colour should be rendered by hatching, \c{*hatch} is filled
3047with the type of hatching desired. See \k{print-grey-colour} for
3048details of the values this integer can take.
3049
3050If the colour should be rendered as solid colour, \c{*hatch} is
3051given a negative value, and \c{*r}, \c{*g} and \c{*b} are filled
3052with the RGB values of the desired colour (if printing in colour),
3053or all filled with the grey-scale value (if printing in black and
3054white).
3055
3056\C{midend} The API provided by the mid-end
3057
3058This chapter documents the API provided by the mid-end to be called
3059by the front end. You probably only need to read this if you are a
3060front end implementor, i.e. you are porting Puzzles to a new
3061platform. If you're only interested in writing new puzzles, you can
3062safely skip this chapter.
3063
3064All the persistent state in the mid-end is encapsulated within a
3065\c{midend} structure, to facilitate having multiple mid-ends in any
3066port which supports multiple puzzle windows open simultaneously.
3067Each \c{midend} is intended to handle the contents of a single
3068puzzle window.
3069
3070\H{midend-new} \cw{midend_new()}
3071
3072\c midend *midend_new(frontend *fe, const game *ourgame,
3073\c const drawing_api *drapi, void *drhandle);
3074
3075Allocates and returns a new mid-end structure.
3076
3077The \c{fe} argument is stored in the mid-end. It will be used when
3078calling back to functions such as \cw{activate_timer()}
3079(\k{frontend-activate-timer}), and will be passed on to the back end
3080function \cw{colours()} (\k{backend-colours}).
3081
3082The parameters \c{drapi} and \c{drhandle} are passed to
3083\cw{drawing_new()} (\k{drawing-new}) to construct a drawing object
3084which will be passed to the back end function \cw{redraw()}
3085(\k{backend-redraw}). Hence, all drawing-related function pointers
3086defined in \c{drapi} can expect to be called with \c{drhandle} as
3087their first argument.
3088
3089The \c{ourgame} argument points to a container structure describing
3090a game back end. The mid-end thus created will only be capable of
3091handling that one game. (So even in a monolithic front end
3092containing all the games, this imposes the constraint that any
3093individual puzzle window is tied to a single game. Unless, of
3094course, you feel brave enough to change the mid-end for the window
3095without closing the window...)
3096
3097\H{midend-free} \cw{midend_free()}
3098
3099\c void midend_free(midend *me);
3100
3101Frees a mid-end structure and all its associated data.
3102
3103\H{midend-tilesize} \cw{midend_tilesize()}
3104
3105\c int midend_tilesize(midend *me);
3106
3107Returns the \cq{tilesize} parameter being used to display the
3108current puzzle (\k{backend-preferred-tilesize}).
3109
3110\H{midend-set-params} \cw{midend_set_params()}
3111
3112\c void midend_set_params(midend *me, game_params *params);
3113
3114Sets the current game parameters for a mid-end. Subsequent games
3115generated by \cw{midend_new_game()} (\k{midend-new-game}) will use
3116these parameters until further notice.
3117
3118The usual way in which the front end will have an actual
3119\c{game_params} structure to pass to this function is if it had
3120previously got it from \cw{midend_get_presets()}
3121(\k{midend-get-presets}). Thus, this function is usually called in
3122response to the user making a selection from the presets menu.
3123
3124\H{midend-get-params} \cw{midend_get_params()}
3125
3126\c game_params *midend_get_params(midend *me);
3127
3128Returns the current game parameters stored in this mid-end.
3129
3130The returned value is dynamically allocated, and should be freed
3131when finished with by passing it to the game's own
3132\cw{free_params()} function (see \k{backend-free-params}).
3133
3134\H{midend-size} \cw{midend_size()}
3135
3136\c void midend_size(midend *me, int *x, int *y,
3137\c bool user_size, double device_pixel_ratio);
3138
3139Tells the mid-end to figure out its window size.
3140
3141On input, \c{*x} and \c{*y} should contain the maximum or requested
3142size for the window. (Typically this will be the size of the screen
3143that the window has to fit on, or similar.) The mid-end will
3144repeatedly call the back end function \cw{compute_size()}
3145(\k{backend-compute-size}), searching for a tile size that best
3146satisfies the requirements. On exit, \c{*x} and \c{*y} will contain
3147the size needed for the puzzle window's drawing area. (It is of
3148course up to the front end to adjust this for any additional window
3149furniture such as menu bars and window borders, if necessary. The
3150status bar is also not included in this size.)
3151
3152Use \c{user_size} to indicate whether \c{*x} and \c{*y} are a
3153requested size, or just a maximum size.
3154
3155If \c{user_size} is set to \cw{true}, the mid-end will treat the
3156input size as a request, and will pick a tile size which
3157approximates it \e{as closely as possible}, going over the game's
3158preferred tile size if necessary to achieve this. The mid-end will
3159also use the resulting tile size as its preferred one until further
3160notice, on the assumption that this size was explicitly requested
3161by the user. Use this option if you want your front end to support
3162dynamic resizing of the puzzle window with automatic scaling of the
3163puzzle to fit.
3164
3165If \c{user_size} is set to \cw{false}, then the game's tile size
3166will never go over its preferred one, although it may go under in
3167order to fit within the maximum bounds specified by \c{*x} and
3168\c{*y}. This is the recommended approach when opening a new window
3169at default size: the game will use its preferred size unless it has
3170to use a smaller one to fit on the screen. If the tile size is
3171shrunk for this reason, the change will not persist; if a smaller
3172grid is subsequently chosen, the tile size will recover.
3173
3174The mid-end will try as hard as it can to return a size which is
3175less than or equal to the input size, in both dimensions. In extreme
3176circumstances it may fail (if even the lowest possible tile size
3177gives window dimensions greater than the input), in which case it
3178will return a size greater than the input size. Front ends should be
3179prepared for this to happen (i.e. don't crash or fail an assertion),
3180but may handle it in any way they see fit: by rejecting the game
3181parameters which caused the problem, by opening a window larger than
3182the screen regardless of inconvenience, by introducing scroll bars
3183on the window, by drawing on a large bitmap and scaling it into a
3184smaller window, or by any other means you can think of. It is likely
3185that when the tile size is that small the game will be unplayable
3186anyway, so don't put \e{too} much effort into handling it
3187creatively.
3188
3189If your platform has no limit on window size (or if you're planning
3190to use scroll bars for large puzzles), you can pass dimensions of
3191\cw{INT_MAX} as input to this function. You should probably not do
3192that \e{and} set the \c{user_size} flag, though!
3193
3194The \cw{device_pixel_ratio} allows the front end to specify that its
3195pixels are unusually large or small (or should be treated as such).
3196The mid-end uses this to adjust the tile size, both at startup (if the
3197ratio is not 1) and if the ratio changes.
3198
3199A \cw{device_pixel_ratio} of 1 indicates normal-sized pixels.
3200\q{Normal} is not precisely defined, but it's about 4 pixels per
3201millimetre on a screen designed to be viewed from a metre away, or a
3202size such that text 15 pixels high is comfortably readable. Some
3203platforms have a concept of a logical pixel that this can be mapped
3204onto. For instance, Cascading Style Sheets (CSS) has a unit called
3205\cq{px} that only matches physical pixels at a \cw{device_pixel_ratio}
3206of 1.
3207
3208The \cw{device_pixel_ratio} indicates the number of physical pixels in
3209a normal-sized pixel, so values less than 1 indicate unusually large
3210pixels and values greater than 1 indicate unusually small pixels.
3211
3212The midend relies on the frontend calling \cw{midend_new_game()}
3213(\k{midend-new-game}) before calling \cw{midend_size()}.
3214
3215\H{midend-reset-tilesize} \cw{midend_reset_tilesize()}
3216
3217\c void midend_reset_tilesize(midend *me);
3218
3219This function resets the midend's preferred tile size to that of the
3220standard puzzle.
3221
3222As discussed in \k{midend-size}, puzzle resizes are typically
3223'sticky', in that once the user has dragged the puzzle to a different
3224window size, the resulting tile size will be remembered and used when
3225the puzzle configuration changes. If you \e{don't} want that, e.g. if
3226you want to provide a command to explicitly reset the puzzle size back
3227to its default, then you can call this just before calling
3228\cw{midend_size()} (which, in turn, you would probably call with
3229\c{user_size} set to \cw{false}).
3230
3231\H{midend-new-game} \cw{midend_new_game()}
3232
3233\c void midend_new_game(midend *me);
3234
3235Causes the mid-end to begin a new game. Normally the game will be a
3236new randomly generated puzzle. However, if you have previously
3237called \cw{midend_game_id()} or \cw{midend_set_config()}, the game
3238generated might be dictated by the results of those functions. (In
3239particular, you \e{must} call \cw{midend_new_game()} after calling
3240either of those functions, or else no immediate effect will be
3241visible.)
3242
3243You will probably need to call \cw{midend_size()} after calling this
3244function, because if the game parameters have been changed since the
3245last new game then the window size might need to change. (If you
3246know the parameters \e{haven't} changed, you don't need to do this.)
3247
3248This function will create a new \c{game_drawstate}, but does not
3249actually perform a redraw (since you often need to call
3250\cw{midend_size()} before the redraw can be done). So after calling
3251this function and after calling \cw{midend_size()}, you should then
3252call \cw{midend_redraw()}. (It is not necessary to call
3253\cw{midend_force_redraw()}; that will discard the draw state and
3254create a fresh one, which is unnecessary in this case since there's
3255a fresh one already. It would work, but it's usually excessive.)
3256
3257\H{midend-restart-game} \cw{midend_restart_game()}
3258
3259\c void midend_restart_game(midend *me);
3260
3261This function causes the current game to be restarted. This is done
3262by placing a new copy of the original game state on the end of the
3263undo list (so that an accidental restart can be undone).
3264
3265This function automatically causes a redraw, i.e. the front end can
3266expect its drawing API to be called from \e{within} a call to this
3267function. Some back ends require that \cw{midend_size()}
3268(\k{midend-size}) is called before \cw{midend_restart_game()}.
3269
3270\H{midend-force-redraw} \cw{midend_force_redraw()}
3271
3272\c void midend_force_redraw(midend *me);
3273
3274Forces a complete redraw of the puzzle window, by means of
3275discarding the current \c{game_drawstate} and creating a new one
3276from scratch before calling the game's \cw{redraw()} function.
3277
3278The front end can expect its drawing API to be called from within a
3279call to this function. Some back ends require that \cw{midend_size()}
3280(\k{midend-size}) is called before \cw{midend_force_redraw()}.
3281
3282\H{midend-redraw} \cw{midend_redraw()}
3283
3284\c void midend_redraw(midend *me);
3285
3286Causes a partial redraw of the puzzle window, by means of simply
3287calling the game's \cw{redraw()} function. (That is, the only things
3288redrawn will be things that have changed since the last redraw.)
3289
3290The front end can expect its drawing API to be called from within a
3291call to this function. Some back ends require that \cw{midend_size()}
3292(\k{midend-size}) is called before \cw{midend_redraw()}.
3293
3294\H{midend-process-key} \cw{midend_process_key()}
3295
3296\c int midend_process_key(midend *me, int x, int y, int button)
3297
3298The front end calls this function to report a mouse or keyboard event.
3299The parameters \c{x} and \c{y} are identical to the ones passed to the
3300back end function \cw{interpret_move()} (\k{backend-interpret-move}).
3301
3302\c{button} is similar to the parameter passed to
3303\cw{interpret_move()}. However, the midend is more relaxed about
3304values passed to in, and some additional special button values
3305are defined for the front end to pass to the midend (see below).
3306
3307Also, the front end is \e{not} required to provide guarantees about
3308mouse event ordering. The mid-end will sort out multiple simultaneous
3309button presses and changes of button; the front end's responsibility
3310is simply to pass on the mouse events it receives as accurately as
3311possible.
3312
3313(Some platforms may need to emulate absent mouse buttons by means of
3314using a modifier key such as Shift with another mouse button. This
3315tends to mean that if Shift is pressed or released in the middle of
3316a mouse drag, the mid-end will suddenly stop receiving, say,
3317\cw{LEFT_DRAG} events and start receiving \cw{RIGHT_DRAG}s, with no
3318intervening button release or press events. This too is something
3319which the mid-end will sort out for you; the front end has no
3320obligation to maintain sanity in this area.)
3321
3322The front end \e{should}, however, always eventually send some kind
3323of button release. On some platforms this requires special effort:
3324Windows, for example, requires a call to the system API function
3325\cw{SetCapture()} in order to ensure that your window receives a
3326mouse-up event even if the pointer has left the window by the time
3327the mouse button is released. On any platform that requires this
3328sort of thing, the front end \e{is} responsible for doing it.
3329
3330Calling this function is very likely to result in calls back to the
3331front end's drawing API and/or \cw{activate_timer()}
3332(\k{frontend-activate-timer}).
3333
3334The return value from \cw{midend_process_key()} is one of the
3335following constants:
3336
3337\dt \cw{PKR_QUIT}
3338
3339\dd Means that the effect of the keypress was to request termination
3340of the program. A front end should shut down the puzzle in response
3341to a \cw{PKR_QUIT} return.
3342
3343\dt \cw{PKR_SOME_EFFECT}
3344
3345\dd The keypress had some other effect, either in the mid-end or in
3346the puzzle itself.
3347
3348\dt \cw{PKR_NO_EFFECT}
3349
3350\dd The keypress had no effect, but might have had an effect in
3351slightly different circumstances. For instance it requested a move
3352that wasn't possible.
3353
3354\dt \cw{PKR_UNUSED}
3355
3356\dd The key was one that neither the mid-end nor the back-end has any
3357use for at all.
3358
3359A front end might respond to the last value by passing the key on to
3360something else that might be interested in it.
3361
3362The following additional values of \c{button} are permitted to be
3363passed to this function by the front end, but are never passed on to
3364the back end. They indicate front-end specific UI operations, such as
3365selecting an option from a drop-down menu. (Otherwise the front end
3366would have to translate the \q{New Game} menu item into an \cq{n}
3367keypress, for example.)
3368
3369\dt \cw{UI_NEWGAME}
3370
3371\dd Indicates that the user requested a new game, similar to pressing
3372\cq{n}.
3373
3374\dt \cw{UI_SOLVE}
3375
3376\dd Indicates that the user requested the solution of the current game.
3377
3378\dt \cw{UI_UNDO}
3379
3380\dd Indicates that the user attempted to undo a move.
3381
3382\dt \cw{UI_REDO}
3383
3384\dd Indicates that the user attempted to redo an undone move.
3385
3386\dt \cw{UI_QUIT}
3387
3388\dd Indicates that the user asked to quit the game. (Of course, a
3389front end might perfectly well handle this on its own. But including
3390it in this enumeration allows the front end to treat all these menu
3391items the same, by translating each of them into a button code passed
3392to the midend, and handle quitting by noticing the \c{false} return
3393value from \cw{midend_process_key()}.)
3394
3395The midend tolerates any modifier being set on any key and removes
3396them as necessary before passing the key on to the backend. It will
3397also handle translating printable characters combined with
3398\cw{MOD_CTRL} into control characters.
3399
3400\H{midend-request-keys} \cw{midend_request_keys()}
3401
3402\c key_label *midend_request_keys(midend *me, int *nkeys);
3403
3404This function behaves similarly to the backend's \cw{request_keys()}
3405function (\k{backend-request-keys}). If the backend does not provide
3406\cw{request_keys()}, this function will return \cw{NULL} and set
3407\cw{*nkeys} to zero. Otherwise, this function will fill in the generic
3408labels (i.e. the \cw{key_label} items that have their \cw{label}
3409fields set to \cw{NULL}) by using \cw{button2label()}
3410(\k{utils-button2label}).
3411
3412\H{midend-current-key-label} \cw{midend_current_key_label()}
3413
3414\c const char *midend_current_key_label(midend *me, int button);
3415
3416This is a thin wrapper around the backend's \cw{current_key_label()}
3417function (\k{backend-current-key-label}). Front ends that need to
3418label \cw{CURSOR_SELECT} or \cw{CURSOR_SELECT2} should call this
3419function after each move (at least after each call to
3420\cw{midend_process_key()}) to get the current labels. The front end
3421should arrange to copy the returned string somewhere before the next
3422call to the mid-end, just in case it's dynamically allocated. If the
3423button supplied does nothing, the label returned will be an empty
3424string.
3425
3426\H{midend-colours} \cw{midend_colours()}
3427
3428\c float *midend_colours(midend *me, int *ncolours);
3429
3430Returns an array of the colours required by the game, in exactly the
3431same format as that returned by the back end function \cw{colours()}
3432(\k{backend-colours}). Front ends should call this function rather
3433than calling the back end's version directly, since the mid-end adds
3434standard customisation facilities. (At the time of writing, those
3435customisation facilities are implemented hackily by means of
3436environment variables, but it's not impossible that they may become
3437more full and formal in future.)
3438
3439\H{midend-timer} \cw{midend_timer()}
3440
3441\c void midend_timer(midend *me, float tplus);
3442
3443If the mid-end has called \cw{activate_timer()}
3444(\k{frontend-activate-timer}) to request regular callbacks for
3445purposes of animation or timing, this is the function the front end
3446should call on a regular basis. The argument \c{tplus} gives the
3447time, in seconds, since the last time either this function was
3448called or \cw{activate_timer()} was invoked.
3449
3450One of the major purposes of timing in the mid-end is to perform
3451move animation. Therefore, calling this function is very likely to
3452result in calls back to the front end's drawing API.
3453
3454\H{midend-get-presets} \cw{midend_get_presets()}
3455
3456\c struct preset_menu *midend_get_presets(midend *me, int *id_limit);
3457
3458Returns a data structure describing this game's collection of preset
3459game parameters, organised into a hierarchical structure of menus and
3460submenus.
3461
3462The return value is a pointer to a data structure containing the
3463following fields (among others, which are not intended for front end
3464use):
3465
3466\c struct preset_menu {
3467\c int n_entries;
3468\c struct preset_menu_entry *entries;
3469\c /* and other things */
3470\e iiiiiiiiiiiiiiiiiiiiii
3471\c };
3472
3473Those fields describe the intended contents of one particular menu in
3474the hierarchy. \cq{entries} points to an array of \cq{n_entries}
3475items, each of which is a structure containing the following fields:
3476
3477\c struct preset_menu_entry {
3478\c char *title;
3479\c game_params *params;
3480\c struct preset_menu *submenu;
3481\c int id;
3482\c };
3483
3484Of these fields, \cq{title} and \cq{id} are present in every entry,
3485giving (respectively) the textual name of the menu item and an integer
3486identifier for it. The integer id will correspond to the one returned
3487by \c{midend_which_preset} (\k{midend-which-preset}), when that preset
3488is the one selected.
3489
3490The other two fields are mutually exclusive. Each \c{struct
3491preset_menu_entry} will have one of those fields \cw{NULL} and the
3492other one non-null. If the menu item is an actual preset, then
3493\cq{params} will point to the set of game parameters that go with the
3494name; if it's a submenu, then \cq{submenu} instead will be non-null,
3495and will point at a subsidiary \c{struct preset_menu}.
3496
3497The complete hierarchy of these structures is owned by the mid-end,
3498and will be freed when the mid-end is freed. The front end should not
3499attempt to free any of it.
3500
3501The integer identifiers will be allocated densely from 0 upwards, so
3502that it's reasonable for the front end to allocate an array which uses
3503them as indices, if it needs to store information per preset menu
3504item. For this purpose, the front end may pass the second parameter
3505\cq{id_limit} to \cw{midend_get_presets} as the address of an \c{int}
3506variable, into which \cw{midend_get_presets} will write an integer one
3507larger than the largest id number actually used (i.e. the number of
3508elements the front end would need in the array).
3509
3510Submenu-type entries also have integer identifiers.
3511
3512\H{midend-which-preset} \cw{midend_which_preset()}
3513
3514\c int midend_which_preset(midend *me);
3515
3516Returns the numeric index of the preset game parameter structure
3517which matches the current game parameters, or a negative number if
3518no preset matches. Front ends could use this to maintain a tick
3519beside one of the items in the menu (or tick the \q{Custom} option
3520if the return value is less than zero).
3521
3522The returned index value (if non-negative) will match the \c{id} field
3523of the corresponding \cw{struct preset_menu_entry} returned by
3524\c{midend_get_presets()} (\k{midend-get-presets}).
3525
3526\H{midend-wants-statusbar} \cw{midend_wants_statusbar()}
3527
3528\c bool midend_wants_statusbar(midend *me);
3529
3530This function returns \cw{true} if the puzzle has a use for a
3531textual status line (to display score, completion status, currently
3532active tiles, time, or anything else).
3533
3534Front ends should call this function rather than talking directly to
3535the back end.
3536
3537\H{midend-get-config} \cw{midend_get_config()}
3538
3539\c config_item *midend_get_config(midend *me, int which,
3540\c char **wintitle);
3541
3542Returns a dialog box description for user configuration.
3543
3544On input, \cw{which} should be set to one of three values, which
3545select which of the various dialog box descriptions is returned:
3546
3547\dt \cw{CFG_SETTINGS}
3548
3549\dd Requests the GUI parameter configuration box generated by the
3550puzzle itself. This should be used when the user selects \q{Custom}
3551from the game types menu (or equivalent). The mid-end passes this
3552request on to the back end function \cw{configure()}
3553(\k{backend-configure}).
3554
3555\dt \cw{CFG_DESC}
3556
3557\dd Requests a box suitable for entering a descriptive game ID (and
3558viewing the existing one). The mid-end generates this dialog box
3559description itself. This should be used when the user selects
3560\q{Specific} from the game menu (or equivalent).
3561
3562\dt \cw{CFG_SEED}
3563
3564\dd Requests a box suitable for entering a random-seed game ID (and
3565viewing the existing one). The mid-end generates this dialog box
3566description itself. This should be used when the user selects
3567\q{Random Seed} from the game menu (or equivalent).
3568
3569\dt \cw{CFG_PREFS}
3570
3571\dd Requests a box suitable for configuring user preferences.
3572
3573(An additional value \cw{CFG_FRONTEND_SPECIFIC} is provided in this
3574enumeration, so that frontends can extend it for their own internal
3575use. For example, you might wrap this function with a
3576\cw{frontend_get_config} which handles some values of \c{which} itself
3577and hands others on to the midend, depending on whether \cw{which <
3578CFG_FRONTEND_SPECIFIC}.)
3579
3580The returned value is an array of \cw{config_item}s, exactly as
3581described in \k{backend-configure}. Another returned value is an
3582ASCII string giving a suitable title for the configuration window,
3583in \c{*wintitle}.
3584
3585Both returned values are dynamically allocated and will need to be
3586freed. The window title can be freed in the obvious way; the
3587\cw{config_item} array is a slightly complex structure, so a utility
3588function \cw{free_cfg()} is provided to free it for you. See
3589\k{utils-free-cfg}.
3590
3591(Of course, you will probably not want to free the \cw{config_item}
3592array until the dialog box is dismissed, because before then you
3593will probably need to pass it to \cw{midend_set_config}.)
3594
3595\H{midend-set-config} \cw{midend_set_config()}
3596
3597\c const char *midend_set_config(midend *me, int which,
3598\c config_item *cfg);
3599
3600Passes the mid-end the results of a configuration dialog box.
3601\c{which} should have the same value which it had when
3602\cw{midend_get_config()} was called; \c{cfg} should be the array of
3603\c{config_item}s returned from \cw{midend_get_config()}, modified to
3604contain the results of the user's editing operations.
3605
3606This function returns \cw{NULL} on success, or otherwise (if the
3607configuration data was in some way invalid) an ASCII string
3608containing an error message suitable for showing to the user.
3609
3610If the function succeeds, it is likely that the game parameters will
3611have been changed and it is certain that a new game will be
3612requested. The front end should therefore call
3613\cw{midend_new_game()}, and probably also re-think the window size
3614using \cw{midend_size()} and eventually perform a refresh using
3615\cw{midend_redraw()}.
3616
3617\H{midend-game-id} \cw{midend_game_id()}
3618
3619\c const char *midend_game_id(midend *me, const char *id);
3620
3621Passes the mid-end a string game ID (of any of the valid forms
3622\cq{params}, \cq{params:description} or \cq{params#seed}) which the
3623mid-end will process and use for the next generated game.
3624
3625This function returns \cw{NULL} on success, or otherwise (if the
3626configuration data was in some way invalid) an ASCII string
3627containing an error message (not dynamically allocated) suitable for
3628showing to the user. In the event of an error, the mid-end's
3629internal state will be left exactly as it was before the call.
3630
3631If the function succeeds, it is likely that the game parameters will
3632have been changed and it is certain that a new game will be
3633requested. The front end should therefore call
3634\cw{midend_new_game()}, and probably also re-think the window size
3635using \cw{midend_size()} and eventually case a refresh using
3636\cw{midend_redraw()}.
3637
3638\H{midend-get-game-id} \cw{midend_get_game_id()}
3639
3640\c char *midend_get_game_id(midend *me);
3641
3642Returns a descriptive game ID (i.e. one in the form
3643\cq{params:description}) describing the game currently active in the
3644mid-end. The returned string is dynamically allocated.
3645
3646\H{midend-get-random-seed} \cw{midend_get_random_seed()}
3647
3648\c char *midend_get_random_seed(midend *me);
3649
3650Returns a random game ID (i.e. one in the form \cq{params#seedstring})
3651describing the game currently active in the mid-end, if there is one.
3652If the game was created by entering a description, no random seed will
3653currently exist and this function will return \cw{NULL}.
3654
3655The returned string, if it is non-\cw{NULL}, is dynamically allocated.
3656
3657Unlike the descriptive game ID, the random seed can contain characters
3658outside the printable ASCII set.
3659
3660\H{midend-can-format-as-text-now} \cw{midend_can_format_as_text_now()}
3661
3662\c bool midend_can_format_as_text_now(midend *me);
3663
3664Returns \cw{true} if the game code is capable of formatting puzzles
3665of the currently selected game type as ASCII.
3666
3667If this returns \cw{false}, then \cw{midend_text_format()}
3668(\k{midend-text-format}) will return \cw{NULL}.
3669
3670\H{midend-text-format} \cw{midend_text_format()}
3671
3672\c char *midend_text_format(midend *me);
3673
3674Formats the current game's current state as ASCII text suitable for
3675copying to the clipboard. The returned string is dynamically
3676allocated.
3677
3678If the game's \c{can_format_as_text_ever} flag is \cw{false}, or if
3679its \cw{can_format_as_text_now()} function returns \cw{false}, then
3680this function will return \cw{NULL}.
3681
3682If the returned string contains multiple lines (which is likely), it
3683will use the normal C line ending convention (\cw{\\n} only). On
3684platforms which use a different line ending convention for data in
3685the clipboard, it is the front end's responsibility to perform the
3686conversion.
3687
3688\H{midend-solve} \cw{midend_solve()}
3689
3690\c const char *midend_solve(midend *me);
3691
3692Requests the mid-end to perform a Solve operation.
3693
3694On success, \cw{NULL} is returned. On failure, an error message (not
3695dynamically allocated) is returned, suitable for showing to the
3696user.
3697
3698The front end can expect its drawing API and/or
3699\cw{activate_timer()} to be called from within a call to this
3700function. Some back ends require that \cw{midend_size()}
3701(\k{midend-size}) is called before \cw{midend_solve()}.
3702
3703\H{midend-get-cursor-location} \cw{midend_get_cursor_location()}
3704
3705\c bool midend_get_cursor_location(midend *me,
3706\c int *x, int *y,
3707\c int *w, int *h);
3708
3709This function requests the location of the back end's on-screen cursor
3710or other region of interest.
3711
3712What exactly this region contains is up to the backend, but in general
3713the region will be an area that the player is controlling with the
3714cursor keys \dash such as the player location in Cube and Inertia, or
3715the cursor in any of the conventional grid-based games. With knowledge
3716of this location, a front end can, for example, ensure that the region
3717of interest remains visible even if the entire puzzle is too big to
3718fit on the screen.
3719
3720On success, this function returns \cw{true}, and the locations pointed
3721to by \cw{x}, \cw{y}, \cw{w} and \cw{h} are updated to describe the
3722cursor region, which has an upper-left corner located at \cw{(*x,*y)}
3723and a size of \cw{*w} pixels wide by \cw{*h} pixels tall. The caller
3724may pass \cw{NULL} for any number of these pointers, which will be
3725ignored.
3726
3727On failure, this function returns \cw{false}. Failure can occur if
3728there is currently no active cursor region, or if the back end lacks
3729cursor support.
3730
3731\H{midend-status} \cw{midend_status()}
3732
3733\c int midend_status(midend *me);
3734
3735This function returns +1 if the midend is currently displaying a game
3736in a solved state, -1 if the game is in a permanently lost state, or 0
3737otherwise. This function just calls the back end's \cw{status()}
3738function. Front ends may wish to use this as a cue to proactively
3739offer the option of starting a new game.
3740
3741(See \k{backend-status} for more detail about the back end's
3742\cw{status()} function and discussion of what should count as which
3743status code.)
3744
3745\H{midend-can-undo} \cw{midend_can_undo()}
3746
3747\c bool midend_can_undo(midend *me);
3748
3749Returns \cw{true} if the midend is currently in a state where the undo
3750operation is meaningful (i.e. at least one position exists on the undo
3751chain before the present one). Front ends may wish to use this to
3752visually activate and deactivate an undo button.
3753
3754\H{midend-can-redo} \cw{midend_can_redo()}
3755
3756\c bool midend_can_redo(midend *me);
3757
3758Returns \cw{true} if the midend is currently in a state where the redo
3759operation is meaningful (i.e. at least one position exists on the redo
3760chain after the present one). Front ends may wish to use this to
3761visually activate and deactivate a redo button.
3762
3763\H{midend-serialise} \cw{midend_serialise()}
3764
3765\c void midend_serialise(midend *me,
3766\c void (*write)(void *ctx, const void *buf, int len), void *wctx);
3767
3768Calling this function causes the mid-end to convert its entire
3769internal state into a long ASCII text string, and to pass that
3770string (piece by piece) to the supplied \c{write} function.
3771The string will consist of printable ASCII characters and line
3772feeds.
3773
3774Desktop implementations can use this function to save a game in any
3775state (including half-finished) to a disk file, by supplying a
3776\c{write} function which is a wrapper on \cw{fwrite()} (or local
3777equivalent). Other implementations may find other uses for it, such
3778as compressing the large and sprawling mid-end state into a
3779manageable amount of memory when a palmtop application is suspended
3780so that another one can run; in this case \cw{write} might want to
3781write to a memory buffer rather than a file. There may be other uses
3782for it as well.
3783
3784This function will call back to the supplied \c{write} function a
3785number of times, with the first parameter (\c{ctx}) equal to
3786\c{wctx}, and the other two parameters pointing at a piece of the
3787output string.
3788
3789\H{midend-deserialise} \cw{midend_deserialise()}
3790
3791\c const char *midend_deserialise(midend *me,
3792\c bool (*read)(void *ctx, void *buf, int len), void *rctx);
3793
3794This function is the counterpart to \cw{midend_serialise()}. It
3795calls the supplied \cw{read} function repeatedly to read a quantity
3796of data, and attempts to interpret that data as a serialised mid-end
3797as output by \cw{midend_serialise()}.
3798
3799The \cw{read} function is called with the first parameter (\c{ctx})
3800equal to \c{rctx}, and should attempt to read \c{len} bytes of data
3801into the buffer pointed to by \c{buf}. It should return \cw{false}
3802on failure or \cw{true} on success. It should not report success
3803unless it has filled the entire buffer; on platforms which might be
3804reading from a pipe or other blocking data source, \c{read} is
3805responsible for looping until the whole buffer has been filled.
3806
3807If the de-serialisation operation is successful, the mid-end's
3808internal data structures will be replaced by the results of the
3809load, and \cw{NULL} will be returned. Otherwise, the mid-end's state
3810will be completely unchanged and an error message (typically some
3811variation on \q{save file is corrupt}) will be returned. As usual,
3812the error message string is not dynamically allocated.
3813
3814If this function succeeds, it is likely that the game parameters
3815will have been changed. The front end should therefore probably
3816re-think the window size using \cw{midend_size()}, and probably
3817cause a refresh using \cw{midend_redraw()}.
3818
3819Because each mid-end is tied to a specific game back end, this
3820function will fail if you attempt to read in a save file generated by
3821a different game from the one configured in this mid-end, even if your
3822application is a monolithic one containing all the puzzles. See
3823\k{identify-game} for a helper function which will allow you to
3824identify a save file before you instantiate your mid-end in the first
3825place.
3826
3827\H{midend-save-prefs} \cw{midend_save_prefs()}
3828
3829\c void midend_save_prefs(
3830\c midend *me, void (*write)(void *ctx, const void *buf, int len),
3831\c void *wctx);
3832
3833Calling this function causes the mid-end to write out the states of
3834all user-settable preference options, including its own cross-platform
3835preferences and ones exported by a particular game via
3836\cw{get_prefs()} and \cw{set_prefs()} (\k{backend-get-prefs},
3837\k{backend-set-prefs}). The output is a textual format suitable for
3838writing into a configuration file on disk.
3839
3840The \c{write} and \c{wctx} parameters have the same semantics as for
3841\cw{midend_serialise()} (\k{midend-serialise}).
3842
3843\H{midend-load-prefs} \cw{midend_load_prefs()}
3844
3845\c const char *midend_load_prefs(
3846\c midend *me, bool (*read)(void *ctx, void *buf, int len),
3847\c void *rctx);
3848
3849This function is used to load a configuration file in the same format
3850emitted by \cw{midend_save_prefs()}, and import all the preferences
3851described in the file into the current mid-end.
3852
3853\H{identify-game} \cw{identify_game()}
3854
3855\c const char *identify_game(char **name,
3856\c bool (*read)(void *ctx, void *buf, int len), void *rctx);
3857
3858This function examines a serialised midend stream, of the same kind
3859used by \cw{midend_serialise()} and \cw{midend_deserialise()}, and
3860returns the \cw{name} field of the game back end from which it was
3861saved.
3862
3863You might want this if your front end was a monolithic one containing
3864all the puzzles, and you wanted to be able to load an arbitrary save
3865file and automatically switch to the right game. Probably your next
3866step would be to iterate through \cw{gamelist} (\k{frontend-backend})
3867looking for a game structure whose \cw{name} field matched the
3868returned string, and give an error if you didn't find one.
3869
3870On success, the return value of this function is \cw{NULL}, and the
3871game name string is written into \cw{*name}. The caller should free
3872that string after using it.
3873
3874On failure, \cw{*name} is \cw{NULL}, and the return value is an error
3875message (which does not need freeing at all).
3876
3877(This isn't strictly speaking a midend function, since it doesn't
3878accept or return a pointer to a midend. You'd probably call it just
3879\e{before} deciding what kind of midend you wanted to instantiate.)
3880
3881\H{midend-request-id-changes} \cw{midend_request_id_changes()}
3882
3883\c void midend_request_id_changes(midend *me,
3884\c void (*notify)(void *), void *ctx);
3885
3886This function is called by the front end to request notification by
3887the mid-end when the current game IDs (either descriptive or
3888random-seed) change. This can occur as a result of keypresses ('n' for
3889New Game, for example) or when a puzzle supersedes its game
3890description (see \k{backend-supersede}). After this function is
3891called, any change of the game ids will cause the mid-end to call
3892\cw{notify(ctx)} after the change.
3893
3894This is for use by puzzles which want to present the game description
3895to the user constantly (e.g. as an HTML hyperlink) instead of only
3896showing it when the user explicitly requests it.
3897
3898This is a function I anticipate few front ends needing to implement,
3899so I make it a callback rather than a static function in order to
3900relieve most front ends of the need to provide an empty
3901implementation.
3902
3903\H{midend-which-game} \cw{midend_which_game()}
3904
3905\c const game *midend_which_preset(midend *me);
3906
3907This function returns the \c{game} structure for the puzzle type this
3908midend is committed to.
3909
3910\H{frontend-backend} Direct reference to the back end structure by
3911the front end
3912
3913Although \e{most} things the front end needs done should be done by
3914calling the mid-end, there are a few situations in which the front
3915end needs to refer directly to the game back end structure.
3916
3917The most obvious of these is
3918
3919\b passing the game back end as a parameter to \cw{midend_new()}.
3920
3921There are a few other back end features which are not wrapped by the
3922mid-end because there didn't seem much point in doing so:
3923
3924\b fetching the \c{name} field to use in window titles and similar
3925
3926\b reading the \c{can_configure}, \c{can_solve} and
3927\c{can_format_as_text_ever} fields to decide whether to add those
3928items to the menu bar or equivalent
3929
3930\b reading the \c{winhelp_topic} field (Windows only)
3931
3932\b the GTK front end provides a \cq{--generate} command-line option
3933which directly calls the back end to do most of its work. This is
3934not really part of the main front end code, though, and I'm not sure
3935it counts.
3936
3937In order to find the game back end structure, the front end does one
3938of two things:
3939
3940\b If the particular front end is compiling a separate binary per
3941game, then the back end structure is a global variable with the
3942standard name \cq{thegame}:
3943
3944\lcont{
3945
3946\c extern const game thegame;
3947
3948}
3949
3950\b If the front end is compiled as a monolithic application
3951containing all the puzzles together (in which case the preprocessor
3952symbol \cw{COMBINED} must be defined when compiling most of the code
3953base), then there will be two global variables defined:
3954
3955\lcont{
3956
3957\c extern const game *gamelist[];
3958\c extern const int gamecount;
3959
3960\c{gamelist} will be an array of \c{gamecount} game structures,
3961declared in the automatically constructed source module \c{list.c}.
3962The application should search that array for the game it wants,
3963probably by reaching into each game structure and looking at its
3964\c{name} field.
3965
3966}
3967
3968\H{frontend-api} Mid-end to front-end calls
3969
3970This section describes the small number of functions which a front
3971end must provide to be called by the mid-end or other standard
3972utility modules.
3973
3974\H{frontend-get-random-seed} \cw{get_random_seed()}
3975
3976\c void get_random_seed(void **randseed, int *randseedsize);
3977
3978This function is called by a new mid-end, and also occasionally by
3979game back ends. Its job is to return a piece of data suitable for
3980using as a seed for initialisation of a new \c{random_state}.
3981
3982On exit, \c{*randseed} should be set to point at a newly allocated
3983piece of memory containing some seed data, and \c{*randseedsize}
3984should be set to the length of that data.
3985
3986A simple and entirely adequate implementation is to return a piece
3987of data containing the current system time at the highest
3988conveniently available resolution.
3989
3990\H{frontend-activate-timer} \cw{activate_timer()}
3991
3992\c void activate_timer(frontend *fe);
3993
3994This is called by the mid-end to request that the front end begin
3995calling it back at regular intervals.
3996
3997The timeout interval is left up to the front end; the finer it is,
3998the smoother move animations will be, but the more CPU time will be
3999used. Current front ends use values around 20ms (i.e. 50Hz).
4000
4001After this function is called, the mid-end will expect to receive
4002calls to \cw{midend_timer()} on a regular basis.
4003
4004\H{frontend-deactivate-timer} \cw{deactivate_timer()}
4005
4006\c void deactivate_timer(frontend *fe);
4007
4008This is called by the mid-end to request that the front end stop
4009calling \cw{midend_timer()}.
4010
4011\H{frontend-fatal} \cw{fatal()}
4012
4013\c void fatal(const char *fmt, ...);
4014
4015This is called by some utility functions if they encounter a
4016genuinely fatal error such as running out of memory. It is a
4017variadic function in the style of \cw{printf()}, and is expected to
4018show the formatted error message to the user any way it can and then
4019terminate the application. It must not return.
4020
4021\H{frontend-default-colour} \cw{frontend_default_colour()}
4022
4023\c void frontend_default_colour(frontend *fe, float *output);
4024
4025This function expects to be passed a pointer to an array of three
4026\cw{float}s. It returns the platform's local preferred background
4027colour in those three floats, as red, green and blue values (in that
4028order) ranging from \cw{0.0} to \cw{1.0}.
4029
4030This function should only ever be called by the back end function
4031\cw{colours()} (\k{backend-colours}). (Thus, it isn't a
4032\e{midend}-to-frontend function as such, but there didn't seem to be
4033anywhere else particularly good to put it. Sorry.)
4034
4035\C{utils} Utility APIs
4036
4037This chapter documents a variety of utility APIs provided for the
4038general use of the rest of the Puzzles code.
4039
4040\H{utils-random} Random number generation
4041
4042Platforms' local random number generators vary widely in quality and
4043seed size. Puzzles therefore supplies its own high-quality random
4044number generator, with the additional advantage of giving the same
4045results if fed the same seed data on different platforms. This
4046allows game random seeds to be exchanged between different ports of
4047Puzzles and still generate the same games.
4048
4049Unlike the ANSI C \cw{rand()} function, the Puzzles random number
4050generator has an \e{explicit} state object called a
4051\c{random_state}. One of these is managed by each mid-end, for
4052example, and passed to the back end to generate a game with.
4053
4054\S{utils-random-init} \cw{random_new()}
4055
4056\c random_state *random_new(char *seed, int len);
4057
4058Allocates, initialises and returns a new \c{random_state}. The input
4059data is used as the seed for the random number stream (i.e. using
4060the same seed at a later time will generate the same stream).
4061
4062The seed data can be any data at all; there is no requirement to use
4063printable ASCII, or NUL-terminated strings, or anything like that.
4064
4065\S{utils-random-copy} \cw{random_copy()}
4066
4067\c random_state *random_copy(random_state *tocopy);
4068
4069Allocates a new \c{random_state}, copies the contents of another
4070\c{random_state} into it, and returns the new state. If exactly the
4071same sequence of functions is subsequently called on both the copy and
4072the original, the results will be identical. This may be useful for
4073speculatively performing some operation using a given random state,
4074and later replaying that operation precisely.
4075
4076\S{utils-random-free} \cw{random_free()}
4077
4078\c void random_free(random_state *state);
4079
4080Frees a \c{random_state}.
4081
4082\S{utils-random-bits} \cw{random_bits()}
4083
4084\c unsigned long random_bits(random_state *state, int bits);
4085
4086Returns a random number from 0 to \cw{2^bits-1} inclusive. \c{bits}
4087should be between 1 and 32 inclusive.
4088
4089\S{utils-random-upto} \cw{random_upto()}
4090
4091\c unsigned long random_upto(random_state *state, unsigned long limit);
4092
4093Returns a random number from 0 to \cw{limit-1} inclusive. \c{limit}
4094may not be zero.
4095
4096\S{utils-random-state-encode} \cw{random_state_encode()}
4097
4098\c char *random_state_encode(random_state *state);
4099
4100Encodes the entire contents of a \c{random_state} in printable
4101ASCII. Returns a dynamically allocated string containing that
4102encoding. This can subsequently be passed to
4103\cw{random_state_decode()} to reconstruct the same \c{random_state}.
4104
4105\S{utils-random-state-decode} \cw{random_state_decode()}
4106
4107\c random_state *random_state_decode(char *input);
4108
4109Decodes a string generated by \cw{random_state_encode()} and
4110reconstructs an equivalent \c{random_state} to the one encoded, i.e.
4111it should produce the same stream of random numbers.
4112
4113This function has no error reporting; if you pass it an invalid
4114string it will simply generate an arbitrary random state, which may
4115turn out to be noticeably non-random.
4116
4117\S{utils-shuffle} \cw{shuffle()}
4118
4119\c void shuffle(void *array, int nelts, int eltsize, random_state *rs);
4120
4121Shuffles an array into a random order. The interface is much like
4122ANSI C \cw{qsort()}, except that there's no need for a compare
4123function.
4124
4125\c{array} is a pointer to the first element of the array. \c{nelts}
4126is the number of elements in the array; \c{eltsize} is the size of a
4127single element (typically measured using \c{sizeof}). \c{rs} is a
4128\c{random_state} used to generate all the random numbers for the
4129shuffling process.
4130
4131\H{utils-presets} Presets menu management
4132
4133The function \c{midend_get_presets()} (\k{midend-get-presets}) returns
4134a data structure describing a menu hierarchy. Back ends can also
4135choose to provide such a structure to the mid-end, if they want to
4136group their presets hierarchically. To make this easy, there are a few
4137utility functions to construct preset menu structures, and also one
4138intended for front-end use.
4139
4140\S{utils-preset-menu-new} \cw{preset_menu_new()}
4141
4142\c struct preset_menu *preset_menu_new(void);
4143
4144Allocates a new \c{struct preset_menu}, and initialises it to hold no
4145menu items.
4146
4147\S{utils-preset-menu-add_submenu} \cw{preset_menu_add_submenu()}
4148
4149\c struct preset_menu *preset_menu_add_submenu
4150\c (struct preset_menu *parent, char *title);
4151
4152Adds a new submenu to the end of an existing preset menu, and returns
4153a pointer to a newly allocated \c{struct preset_menu} describing the
4154submenu.
4155
4156The string parameter \cq{title} must be dynamically allocated by the
4157caller. The preset-menu structure will take ownership of it, so the
4158caller must not free it.
4159
4160\S{utils-preset-menu-add-preset} \cw{preset_menu_add_preset()}
4161
4162\c void preset_menu_add_preset
4163\c (struct preset_menu *menu, char *title, game_params *params);
4164
4165Adds a preset game configuration to the end of a preset menu.
4166
4167Both the string parameter \cq{title} and the game parameter structure
4168\cq{params} itself must be dynamically allocated by the caller. The
4169preset-menu structure will take ownership of it, so the caller must
4170not free it.
4171
4172\S{utils-preset-menu-lookup-by-id} \cw{preset_menu_lookup_by_id()}
4173
4174\c game_params *preset_menu_lookup_by_id
4175\c (struct preset_menu *menu, int id);
4176
4177Given a numeric index, searches recursively through a preset menu
4178hierarchy to find the corresponding menu entry, and returns a pointer
4179to its existing \c{game_params} structure.
4180
4181This function is intended for front end use (but front ends need not
4182use it if they prefer to do things another way). If a front end finds
4183it inconvenient to store anything more than a numeric index alongside
4184each menu item, then this function provides an easy way for the front
4185end to get back the actual game parameters corresponding to a menu
4186item that the user has selected.
4187
4188\H{utils-alloc} Memory allocation
4189
4190Puzzles has some central wrappers on the standard memory allocation
4191functions, which provide compile-time type checking, and run-time
4192error checking by means of quitting the application if it runs out
4193of memory. This doesn't provide the best possible recovery from
4194memory shortage, but on the other hand it greatly simplifies the
4195rest of the code, because nothing else anywhere needs to worry about
4196\cw{NULL} returns from allocation.
4197
4198\S{utils-snew} \cw{snew()}
4199
4200\c var = snew(type);
4201\e iii iiii
4202
4203This macro takes a single argument which is a \e{type name}. It
4204allocates space for one object of that type. If allocation fails it
4205will call \cw{fatal()} and not return; so if it does return, you can
4206be confident that its return value is non-\cw{NULL}.
4207
4208The return value is cast to the specified type, so that the compiler
4209will type-check it against the variable you assign it into. Thus,
4210this ensures you don't accidentally allocate memory the size of the
4211wrong type and assign it into a variable of the right one (or vice
4212versa!).
4213
4214\S{utils-snewn} \cw{snewn()}
4215
4216\c var = snewn(n, type);
4217\e iii i iiii
4218
4219This macro is the array form of \cw{snew()}. It takes two arguments;
4220the first is a number, and the second is a type name. It allocates
4221space for that many objects of that type, and returns a type-checked
4222non-\cw{NULL} pointer just as \cw{snew()} does.
4223
4224\S{utils-sresize} \cw{sresize()}
4225
4226\c var = sresize(var, n, type);
4227\e iii iii i iiii
4228
4229This macro is a type-checked form of \cw{realloc()}. It takes three
4230arguments: an input memory block, a new size in elements, and a
4231type. It re-sizes the input memory block to a size sufficient to
4232contain that many elements of that type. It returns a type-checked
4233non-\cw{NULL} pointer, like \cw{snew()} and \cw{snewn()}.
4234
4235The input memory block can be \cw{NULL}, in which case this function
4236will behave exactly like \cw{snewn()}. (In principle any
4237ANSI-compliant \cw{realloc()} implementation ought to cope with
4238this, but I've never quite trusted it to work everywhere.)
4239
4240\S{utils-sfree} \cw{sfree()}
4241
4242\c void sfree(void *p);
4243
4244This function is pretty much equivalent to \cw{free()}. It is
4245provided with a dynamically allocated block, and frees it.
4246
4247The input memory block can be \cw{NULL}, in which case this function
4248will do nothing. (In principle any ANSI-compliant \cw{free()}
4249implementation ought to cope with this, but I've never quite trusted
4250it to work everywhere.)
4251
4252\S{utils-dupstr} \cw{dupstr()}
4253
4254\c char *dupstr(const char *s);
4255
4256This function dynamically allocates a duplicate of a C string. Like
4257the \cw{snew()} functions, it guarantees to return non-\cw{NULL} or
4258not return at all.
4259
4260(Many platforms provide the function \cw{strdup()}. As well as
4261guaranteeing never to return \cw{NULL}, my version has the advantage
4262of being defined \e{everywhere}, rather than inconveniently not
4263quite everywhere.)
4264
4265\S{utils-free-cfg} \cw{free_cfg()}
4266
4267\c void free_cfg(config_item *cfg);
4268
4269This function correctly frees an array of \c{config_item}s, including
4270walking the array until it gets to the end and freeing any subsidiary
4271data items in each \c{u} sub-union which are expected to be
4272dynamically allocated.
4273
4274(See \k{backend-configure} for details of the \c{config_item}
4275structure.)
4276
4277\S{utils-free-keys} \cw{free_keys()}
4278
4279\c void free_keys(key_label *keys, int nkeys);
4280
4281This function correctly frees an array of \c{key_label}s, including
4282the dynamically allocated label string for each key.
4283
4284(See \k{backend-request-keys} for details of the \c{key_label}
4285structure.)
4286
4287\H{utils-tree234} Sorted and counted tree functions
4288
4289Many games require complex algorithms for generating random puzzles,
4290and some require moderately complex algorithms even during play. A
4291common requirement during these algorithms is for a means of
4292maintaining sorted or unsorted lists of items, such that items can
4293be removed and added conveniently.
4294
4295For general use, Puzzles provides the following set of functions
4296which maintain 2-3-4 trees in memory. (A 2-3-4 tree is a balanced
4297tree structure, with the property that all lookups, insertions,
4298deletions, splits and joins can be done in \cw{O(log N)} time.)
4299
4300All these functions expect you to be storing a tree of \c{void *}
4301pointers. You can put anything you like in those pointers.
4302
4303By the use of per-node element counts, these tree structures have
4304the slightly unusual ability to look elements up by their numeric
4305index within the list represented by the tree. This means that they
4306can be used to store an unsorted list (in which case, every time you
4307insert a new element, you must explicitly specify the position where
4308you wish to insert it). They can also do numeric lookups in a sorted
4309tree, which might be useful for (for example) tracking the median of
4310a changing data set.
4311
4312As well as storing sorted lists, these functions can be used for
4313storing \q{maps} (associative arrays), by defining each element of a
4314tree to be a (key, value) pair.
4315
4316\S{utils-newtree234} \cw{newtree234()}
4317
4318\c tree234 *newtree234(cmpfn234 cmp);
4319
4320Creates a new empty tree, and returns a pointer to it.
4321
4322The parameter \c{cmp} determines the sorting criterion on the tree.
4323Its prototype is
4324
4325\c typedef int (*cmpfn234)(void *, void *);
4326
4327If you want a sorted tree, you should provide a function matching
4328this prototype, which returns like \cw{strcmp()} does (negative if
4329the first argument is smaller than the second, positive if it is
4330bigger, zero if they compare equal). In this case, the function
4331\cw{addpos234()} will not be usable on your tree (because all
4332insertions must respect the sorting order).
4333
4334If you want an unsorted tree, pass \cw{NULL}. In this case you will
4335not be able to use either \cw{add234()} or \cw{del234()}, or any
4336other function such as \cw{find234()} which depends on a sorting
4337order. Your tree will become something more like an array, except
4338that it will efficiently support insertion and deletion as well as
4339lookups by numeric index.
4340
4341\S{utils-freetree234} \cw{freetree234()}
4342
4343\c void freetree234(tree234 *t);
4344
4345Frees a tree. This function will not free the \e{elements} of the
4346tree (because they might not be dynamically allocated, or you might
4347be storing the same set of elements in more than one tree); it will
4348just free the tree structure itself. If you want to free all the
4349elements of a tree, you should empty it before passing it to
4350\cw{freetree234()}, by means of code along the lines of
4351
4352\c while ((element = delpos234(tree, 0)) != NULL)
4353\c sfree(element); /* or some more complicated free function */
4354\e iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
4355
4356\S{utils-add234} \cw{add234()}
4357
4358\c void *add234(tree234 *t, void *e);
4359
4360Inserts a new element \c{e} into the tree \c{t}. This function
4361expects the tree to be sorted; the new element is inserted according
4362to the sort order.
4363
4364If an element comparing equal to \c{e} is already in the tree, then
4365the insertion will fail, and the return value will be the existing
4366element. Otherwise, the insertion succeeds, and \c{e} is returned.
4367
4368\S{utils-addpos234} \cw{addpos234()}
4369
4370\c void *addpos234(tree234 *t, void *e, int index);
4371
4372Inserts a new element into an unsorted tree. Since there is no
4373sorting order to dictate where the new element goes, you must
4374specify where you want it to go. Setting \c{index} to zero puts the
4375new element right at the start of the list; setting \c{index} to the
4376current number of elements in the tree puts the new element at the
4377end.
4378
4379Return value is \c{e}, in line with \cw{add234()} (although this
4380function cannot fail except by running out of memory, in which case
4381it will bomb out and die rather than returning an error indication).
4382
4383\S{utils-index234} \cw{index234()}
4384
4385\c void *index234(tree234 *t, int index);
4386
4387Returns a pointer to the \c{index}th element of the tree, or
4388\cw{NULL} if \c{index} is out of range. Elements of the tree are
4389numbered from zero.
4390
4391\S{utils-find234} \cw{find234()}
4392
4393\c void *find234(tree234 *t, void *e, cmpfn234 cmp);
4394
4395Searches for an element comparing equal to \c{e} in a sorted tree.
4396
4397If \c{cmp} is \cw{NULL}, the tree's ordinary comparison function
4398will be used to perform the search. However, sometimes you don't
4399want that; suppose, for example, each of your elements is a big
4400structure containing a \c{char *} name field, and you want to find
4401the element with a given name. You \e{could} achieve this by
4402constructing a fake element structure, setting its name field
4403appropriately, and passing it to \cw{find234()}, but you might find
4404it more convenient to pass \e{just} a name string to \cw{find234()},
4405supplying an alternative comparison function which expects one of
4406its arguments to be a bare name and the other to be a large
4407structure containing a name field.
4408
4409Therefore, if \c{cmp} is not \cw{NULL}, then it will be used to
4410compare \c{e} to elements of the tree. The first argument passed to
4411\c{cmp} will always be \c{e}; the second will be an element of the
4412tree.
4413
4414(See \k{utils-newtree234} for the definition of the \c{cmpfn234}
4415function pointer type.)
4416
4417The returned value is the element found, or \cw{NULL} if the search
4418is unsuccessful.
4419
4420\S{utils-findrel234} \cw{findrel234()}
4421
4422\c void *findrel234(tree234 *t, void *e, cmpfn234 cmp, int relation);
4423
4424This function is like \cw{find234()}, but has the additional ability
4425to do a \e{relative} search. The additional parameter \c{relation}
4426can be one of the following values:
4427
4428\dt \cw{REL234_EQ}
4429
4430\dd Find only an element that compares equal to \c{e}. This is
4431exactly the behaviour of \cw{find234()}.
4432
4433\dt \cw{REL234_LT}
4434
4435\dd Find the greatest element that compares strictly less than
4436\c{e}. \c{e} may be \cw{NULL}, in which case it finds the greatest
4437element in the whole tree (which could also be done by
4438\cw{index234(t, count234(t)-1)}).
4439
4440\dt \cw{REL234_LE}
4441
4442\dd Find the greatest element that compares less than or equal to
4443\c{e}. (That is, find an element that compares equal to \c{e} if
4444possible, but failing that settle for something just less than it.)
4445
4446\dt \cw{REL234_GT}
4447
4448\dd Find the smallest element that compares strictly greater than
4449\c{e}. \c{e} may be \cw{NULL}, in which case it finds the smallest
4450element in the whole tree (which could also be done by
4451\cw{index234(t, 0)}).
4452
4453\dt \cw{REL234_GE}
4454
4455\dd Find the smallest element that compares greater than or equal to
4456\c{e}. (That is, find an element that compares equal to \c{e} if
4457possible, but failing that settle for something just bigger than
4458it.)
4459
4460Return value, as before, is the element found or \cw{NULL} if no
4461element satisfied the search criterion.
4462
4463\S{utils-findpos234} \cw{findpos234()}
4464
4465\c void *findpos234(tree234 *t, void *e, cmpfn234 cmp, int *index);
4466
4467This function is like \cw{find234()}, but has the additional feature
4468of returning the index of the element found in the tree; that index
4469is written to \c{*index} in the event of a successful search (a
4470non-\cw{NULL} return value).
4471
4472\c{index} may be \cw{NULL}, in which case this function behaves
4473exactly like \cw{find234()}.
4474
4475\S{utils-findrelpos234} \cw{findrelpos234()}
4476
4477\c void *findrelpos234(tree234 *t, void *e, cmpfn234 cmp, int relation,
4478\c int *index);
4479
4480This function combines all the features of \cw{findrel234()} and
4481\cw{findpos234()}.
4482
4483\S{utils-del234} \cw{del234()}
4484
4485\c void *del234(tree234 *t, void *e);
4486
4487Finds an element comparing equal to \c{e} in the tree, deletes it,
4488and returns it.
4489
4490The input tree must be sorted.
4491
4492The element found might be \c{e} itself, or might merely compare
4493equal to it.
4494
4495Return value is \cw{NULL} if no such element is found.
4496
4497\S{utils-delpos234} \cw{delpos234()}
4498
4499\c void *delpos234(tree234 *t, int index);
4500
4501Deletes the element at position \c{index} in the tree, and returns
4502it.
4503
4504Return value is \cw{NULL} if the index is out of range.
4505
4506\S{utils-count234} \cw{count234()}
4507
4508\c int count234(tree234 *t);
4509
4510Returns the number of elements currently in the tree.
4511
4512\S{utils-splitpos234} \cw{splitpos234()}
4513
4514\c tree234 *splitpos234(tree234 *t, int index, bool before);
4515
4516Splits the input tree into two pieces at a given position, and
4517creates a new tree containing all the elements on one side of that
4518position.
4519
4520If \c{before} is \cw{true}, then all the items at or after position
4521\c{index} are left in the input tree, and the items before that
4522point are returned in the new tree. Otherwise, the reverse happens:
4523all the items at or after \c{index} are moved into the new tree, and
4524those before that point are left in the old one.
4525
4526If \c{index} is equal to 0 or to the number of elements in the input
4527tree, then one of the two trees will end up empty (and this is not
4528an error condition). If \c{index} is further out of range in either
4529direction, the operation will fail completely and return \cw{NULL}.
4530
4531This operation completes in \cw{O(log N)} time, no matter how large
4532the tree or how balanced or unbalanced the split.
4533
4534\S{utils-split234} \cw{split234()}
4535
4536\c tree234 *split234(tree234 *t, void *e, cmpfn234 cmp, int rel);
4537
4538Splits a sorted tree according to its sort order.
4539
4540\c{rel} can be any of the relation constants described in
4541\k{utils-findrel234}, \e{except} for \cw{REL234_EQ}. All the
4542elements having that relation to \c{e} will be transferred into the
4543new tree; the rest will be left in the old one.
4544
4545The parameter \c{cmp} has the same semantics as it does in
4546\cw{find234()}: if it is not \cw{NULL}, it will be used in place of
4547the tree's own comparison function when comparing elements to \c{e},
4548in such a way that \c{e} itself is always the first of its two
4549operands.
4550
4551Again, this operation completes in \cw{O(log N)} time, no matter how
4552large the tree or how balanced or unbalanced the split.
4553
4554\S{utils-join234} \cw{join234()}
4555
4556\c tree234 *join234(tree234 *t1, tree234 *t2);
4557
4558Joins two trees together by concatenating the lists they represent.
4559All the elements of \c{t2} are moved into \c{t1}, in such a way that
4560they appear \e{after} the elements of \c{t1}. The tree \c{t2} is
4561freed; the return value is \c{t1}.
4562
4563If you apply this function to a sorted tree and it violates the sort
4564order (i.e. the smallest element in \c{t2} is smaller than or equal
4565to the largest element in \c{t1}), the operation will fail and
4566return \cw{NULL}.
4567
4568This operation completes in \cw{O(log N)} time, no matter how large
4569the trees being joined together.
4570
4571\S{utils-join234r} \cw{join234r()}
4572
4573\c tree234 *join234r(tree234 *t1, tree234 *t2);
4574
4575Joins two trees together in exactly the same way as \cw{join234()},
4576but this time the combined tree is returned in \c{t2}, and \c{t1} is
4577destroyed. The elements in \c{t1} still appear before those in
4578\c{t2}.
4579
4580Again, this operation completes in \cw{O(log N)} time, no matter how
4581large the trees being joined together.
4582
4583\S{utils-copytree234} \cw{copytree234()}
4584
4585\c tree234 *copytree234(tree234 *t, copyfn234 copyfn,
4586\c void *copyfnstate);
4587
4588Makes a copy of an entire tree.
4589
4590If \c{copyfn} is \cw{NULL}, the tree will be copied but the elements
4591will not be; i.e. the new tree will contain pointers to exactly the
4592same physical elements as the old one.
4593
4594If you want to copy each actual element during the operation, you
4595can instead pass a function in \c{copyfn} which makes a copy of each
4596element. That function has the prototype
4597
4598\c typedef void *(*copyfn234)(void *state, void *element);
4599
4600and every time it is called, the \c{state} parameter will be set to
4601the value you passed in as \c{copyfnstate}.
4602
4603\H{utils-dsf} Disjoint set forests
4604
4605This section describes a set of functions implementing the data
4606structure variously known as \q{union-find} or \q{Tarjan's disjoint
4607set forest}. In this code base, it's universally abbreviated as a
4608\q{dsf}.
4609
4610A dsf represents a collection of elements partitioned into
4611\q{equivalence classes}, in circumstances where equivalences are added
4612incrementally. That is, all elements start off considered to be
4613different, and you gradually declare more and more of them to be equal
4614via the \cw{dsf_merge()} operation, which says that two particular
4615elements should be regarded as equal from now on.
4616
4617For example, if I start off with A,B,U,V all distinct, and I merge A
4618with B and merge U with V, then the structure will tell me that A and
4619U are not equivalent. But if I then merge B with V, then after that,
4620the structure will tell me that A and U \e{are} equivalent, by
4621following the transitive chain of equivalences it knows about.
4622
4623The dsf data structure is therefore ideal for tracking incremental
4624connectivity in an undirected graph (again, \q{incremental} meaning
4625that you only ever add edges, never delete them), and other
4626applications in which you gradually acquire knowledge you didn't
4627previously have about what things are the same as each other. It's
4628used extensively in puzzle solver and generator algorithms, and
4629sometimes during gameplay as well.
4630
4631The time complexity of dsf operations is not \e{quite} constant time,
4632in theory, but it's so close to it as to make no difference in
4633practice. In particular, any time a dsf has to do non-trivial work, it
4634updates the structure so that that work won't be needed a second time.
4635Use dsf operations without worrying about how long they take!
4636
4637For some puzzle-game applications, it's useful to augment this data
4638structure with extra information about how the elements of an
4639equivalence class relate to each other. There's more than one way you
4640might do this; the one supported here is useful in cases where the
4641objects you're tracking are going to end up in one of two states (say,
4642black/white, or on/off), and for any two objects you either know that
4643they're in the same one of those states, or you know they're in
4644opposite states, or you don't know which yet. Puzzles calls this a
4645\q{flip dsf}: it tracks whether objects in the same equivalence class
4646are flipped relative to each other.
4647
4648As well as querying whether two elements are equivalent, this dsf
4649implementation also allows you to ask for the number of elements in a
4650given equivalence class, and the smallest element in the class. (The
4651latter is used, for example, to decide which square to print the clue
4652in each region of a Keen puzzle.)
4653
4654\S{utils-dsf-new} \cw{dsf_new()}, \cw{dsf_new_flip()}, \cw{dsf_new_min()}
4655
4656\c DSF *dsf_new(int size);
4657\c DSF *dsf_new_flip(int size);
4658\c DSF *dsf_new_min(int size);
4659
4660Each of these functions allocates space for a dsf describing \c{size}
4661elements, and initialises it so that every element is in an
4662equivalence class by itself.
4663
4664The elements described by the dsf are represented by the integers from
4665\cw{0} to \cw{size-1} inclusive.
4666
4667\cw{dsf_new_flip()} will create a dsf which has the extra ability to
4668track whether objects in the same equivalence class are flipped
4669relative to each other.
4670
4671\cw{dsf_new_min()} will create a dsf which has the extra ability to
4672track the smallest element of each equivalence class.
4673
4674The returned object from any of these functions must be freed using
4675\cw{dsf_free()}.
4676
4677\S{utils-dsf-free} \cw{dsf_free()}
4678
4679\c void dsf_free(DSF *dsf);
4680
4681Frees a dsf allocated by any of the \cw{dsf_new()} functions.
4682
4683\S{utils-dsf-reinit} \cw{dsf_reinit()}
4684
4685\c void dsf_reinit(DSF *dsf);
4686
4687Reinitialises an existing dsf to the state in which all elements are
4688distinct, without having to free and reallocate it.
4689
4690\S{utils-dsf-copy} \cw{dsf_copy()}
4691
4692\c void dsf_copy(DSF *to, DSF *from);
4693
4694Copies the contents of one dsf over the top of another. Everything
4695previously stored in \c{to} is overwritten.
4696
4697The two dsfs must have been created with the same size, and the
4698destination dsf may not have any extra information that the source dsf
4699does not have.
4700
4701\S{utils-dsf-merge} \cw{dsf_merge()}
4702
4703\c void dsf_merge(DSF *dsf, int v1, int v2);
4704
4705Updates a dsf so that elements \c{v1} and \c{v2} will now be
4706considered to be in the same equivalence class. If they were already
4707in the same class, this function will safely do nothing.
4708
4709This function may not be called on a flip dsf. Use \cw{dsf_merge_flip}
4710instead.
4711
4712\S{utils-dsf-canonify} \cw{dsf_canonify()}
4713
4714\c int dsf_canonify(DSF *dsf, int val);
4715
4716Returns the \q{canonical} element of the equivalence class in the dsf
4717containing \c{val}. This will be some element of the same equivalence
4718class. So in order to determine whether two elements are in the same
4719equivalence class, you can call \cw{dsf_canonify} on both of them, and
4720compare the results.
4721
4722Canonical elements don't necessarily stay the same if the dsf is
4723mutated via \c{dsf_merge}. But between two calls to \c{dsf_merge},
4724they stay the same.
4725
4726\S{utils-dsf-size} \cw{dsf_size()}
4727
4728\c int dsf_size(DSF *dsf, int val);
4729
4730Returns the number of elements currently in the equivalence class
4731containing \c{val}.
4732
4733\c{val} itself counts, so in a newly created dsf, the return value
4734will be 1.
4735
4736\S{utils-dsf-merge-flip} \cw{dsf_merge_flip()}
4737
4738\c void edsf_merge(DSF *dsf, int v1, int v2, bool flip);
4739
4740Updates a flip dsf so that elements \c{v1} and \c{v2} are in the same
4741equivalence class. If \c{flip} is \cw{false}, they will be regarded as
4742in the same state as each other; if \c{flip} is \cw{true} then they
4743will be regarded as being in opposite states.
4744
4745If \c{v1} and \c{v2} were already in the same equivalence class, then
4746the new value of \c{flip} will be checked against what the edsf
4747previously believed, and an assertion failure will occur if you
4748contradict that.
4749
4750For example, if you start from a blank flip dsf and do this:
4751
4752\c dsf_merge_flip(dsf, 0, 1, false);
4753\c dsf_merge_flip(dsf, 1, 2, true);
4754
4755then it will create a dsf in which elements 0,1,2 are all in the same
4756class, with 0,1 in the same state as each other and 2 in the opposite
4757state from both. And then this call will do nothing, because it agrees
4758with what the dsf already knew:
4759
4760\c dsf_merge_flip(dsf, 0, 2, true);
4761
4762But this call will fail an assertion:
4763
4764\c dsf_merge_flip(dsf, 0, 2, false);
4765
4766\S{utils-dsf-canonify-flip} \cw{dsf_canonify_flip()}
4767
4768\c int dsf_canonify_flip(DSF *dsf, int val, bool *inverse);
4769
4770Like \c{dsf_canonify()}, this returns the canonical element of the
4771equivalence class of a dsf containing \c{val}.
4772
4773However, it may only be called on a flip dsf, and it also fills in
4774\c{*flip} with a flag indicating whether \c{val} and the canonical
4775element are in opposite states: \cw{true} if they are in opposite
4776states, or \cw{false} if they're in the same state.
4777
4778So if you want to know the relationship between \c{v1} and \c{v2}, you
4779can do this:
4780
4781\c bool inv1, inv2;
4782\c int canon1 = dsf_canonify_flip(dsf, v1, &inv1);
4783\c int canon2 = dsf_canonify_flip(dsf, v2, &inv2);
4784\c if (canon1 != canon2) {
4785\c // v1 and v2 have no known relation
4786\c } else if (inv1 == inv2) {
4787\c // v1 and v2 are known to be in the same state as each other
4788\c } else {
4789\c // v1 and v2 are known to be in opposite states
4790\c }
4791
4792\S{utils-dsf-minimal} \cw{dsf_minimal()}
4793
4794\c int dsf_minimal(DSF *dsf, int val);
4795
4796Returns the smallest element of the equivalence class in the dsf
4797containing \c{val}.
4798
4799For this function to work, the dsf must have been created using
4800\cw{dsf_new_min()}.
4801
4802\H{utils-tdq} To-do queues
4803
4804This section describes a set of functions implementing a \q{to-do
4805queue}, a simple de-duplicating to-do list mechanism. The code calls
4806this a \q{tdq}.
4807
4808A tdq can store integers up to a given size (specified at creation
4809time). But it can't store the same integer more than once. So you can
4810quickly \e{make sure} an integer is in the queue (which will do
4811nothing if it's already there), and you can quickly pop an integer
4812from the queue and return it, both in constant time.
4813
4814The idea is that you might use this in a game solver, in the kind of
4815game where updating your knowledge about one square of a grid means
4816there's a specific other set of squares (such as its neighbours) where
4817it's now worth attempting further deductions. So you keep a tdq of all
4818the grid squares you plan to look at next, and every time you make a
4819deduction in one square, you add the neighbouring squares to the tdq
4820to make sure they get looked at again after that.
4821
4822In solvers where deductions are mostly localised, this avoids the
4823slowdown of having to find the next thing to do every time by looping
4824over the whole grid: instead, you can keep checking the tdq for
4825\e{specific} squares to look at, until you run out.
4826
4827However, it's common to have games in which \e{most} deductions are
4828localised, but not all. In that situation, when your tdq is empty, you
4829can re-fill it with every square in the grid using \cw{tdq_fill()},
4830which will force an iteration over everything again. And then if the
4831tdq becomes empty \e{again} without you having made any progress, give
4832up.
4833
4834\S{utils-tdq-new} \cw{tdq_new()}
4835
4836\c tdq *tdq_new(int n);
4837
4838Allocates space for a tdq that tracks items from \cw{0} to \cw{size-1}
4839inclusive.
4840
4841\S{utils-tdq-free} \cw{tdq_free()}
4842
4843\c void tdq_free(tdq *tdq);
4844
4845Frees a tdq.
4846
4847\S{utils-tdq-add} \cw{tdq_add()}
4848
4849\c void tdq_add(tdq *tdq, int k);
4850
4851Adds the value \c{k} to a tdq. If \c{k} was already in the to-do list,
4852does nothing.
4853
4854\S{utils-tdq-remove} \cw{tdq_remove()}
4855
4856\c int tdq_remove(tdq *tdq);
4857
4858Removes one item from the tdq, and returns it. If the tdq is empty,
4859returns \cw{-1}.
4860
4861\S{utils-tdq-fill} \cw{tdq_fill()}
4862
4863\c void tdq_fill(tdq *tdq);
4864
4865Fills a tdq with every element it can possibly keep track of.
4866
4867\H{utils-findloop} Finding loops in graphs and grids
4868
4869Many puzzles played on grids or graphs have a common gameplay element
4870of connecting things together into paths in such a way that you need
4871to avoid making loops (or, perhaps, making the \e{wrong} kind of
4872loop).
4873
4874Just determining \e{whether} a loop exists in a graph is easy, using a
4875dsf tracking connectivity between the vertices. Simply iterate over
4876each edge of the graph, merging the two vertices at each end of the
4877edge \dash but before you do that, check whether those vertices are
4878\e{already} known to be connected to each other, and if they are, then
4879the new edge is about to complete a loop.
4880
4881But if you also want to identify \e{exactly} the set of edges that are
4882part of any loop, e.g. to highlight the whole loop red during
4883gameplay, then that's a harder problem. This API is provided here for
4884all puzzles to use for that purpose.
4885
4886\S{utils-findloop-new-state} \cw{findloop_new_state()}
4887
4888\c struct findloopstate *findloop_new_state(int nvertices);
4889
4890Allocates a new state structure for the findloop algorithm, capable of
4891handling a graph with up to \c{nvertices} vertices. The vertices will
4892be represented by integers between \c{0} and \c{nvertices-1} inclusive.
4893
4894\S{utils-findloop-free-state} \cw{findloop_free_state()}
4895
4896\c void findloop_free_state(struct findloopstate *state);
4897
4898Frees a state structure allocated by \cw{findloop_new_state()}.
4899
4900\S{utils-findloop-run} \cw{findloop_run()}
4901
4902\c bool findloop_run(struct findloopstate *state, int nvertices,
4903\c neighbour_fn_t neighbour, void *ctx);
4904
4905Runs the loop-finding algorithm, which will explore the graph and
4906identify whether each edge is or is not part of any loop.
4907
4908The algorithm will call the provided function \c{neighbour} to list
4909the neighbouring vertices of each vertex. It should have this
4910prototype:
4911
4912\c int neighbour(int vertex, void *ctx);
4913
4914In this callback, \c{vertex} will be the index of a vertex when the
4915algorithm \e{first} calls it for a given vertex. The function should
4916return the index of one of that vertex's neighbours, or a negative
4917number if there are none.
4918
4919If the function returned a vertex, the algorithm will then call
4920\c{neighbour} again with a \e{negative} number as the \c{vertex}
4921parameter, which means \q{please give me another neighbour of the same
4922vertex as last time}. Again, the function should return a vertex
4923index, or a negative number to indicate that there are no more
4924vertices.
4925
4926The \c{ctx} parameter passed to \cw{findloop_run()} is passed on
4927unchanged to \c{neighbour}, so you can point that at your game state
4928or solver state or whatever.
4929
4930The return value is \cw{true} if at least one loop exists in the
4931graph, and \cw{false} if no loop exists. Also, the algorithm state
4932will have been filled in with information that the following query
4933functions can use to ask about individual graph edges.
4934
4935\S{utils-findloop-is-loop-edge} \cw{findloop_is_loop_edge()}
4936
4937\c bool findloop_is_loop_edge(struct findloopstate *state,
4938\c int u, int v);
4939
4940Queries whether the graph edge between vertices \c{u} and \c{v} is
4941part of a loop. If so, the return value is \cw{true}, otherwise
4942\cw{false}.
4943
4944\S{utils-findloop-is-bridge} \cw{findloop_is_bridge()}
4945
4946\c bool findloop_is_bridge(struct findloopstate *pv,
4947\c int u, int v, int *u_vertices, int *v_vertices);
4948
4949Queries whether the graph edge between vertices \c{u} and \c{v} is a
4950\q{bridge}, i.e. an edge which would break the graph into (more)
4951disconnected components if it were removed.
4952
4953This is the exact inverse of the \q{loop edge} criterion: a vertex
4954returns \cw{true} from \cw{findloop_is_loop_edge()} if and only if it
4955returns \cw{false} from \cw{findloop_is_bridge()}, and vice versa.
4956
4957However, \cw{findloop_is_bridge()} returns more information. If it
4958returns \cw{true}, then it also fills in \c{*u_vertices} and
4959\c{*v_vertices} with the number of vertices connected to the \c{u} and
4960\c{v} sides of the bridge respectively.
4961
4962For example, if you have three vertices A,B,C all connected to each
4963other, and four vertices U,V,W,X all connected to each other, and a
4964single edge between A and V, then calling \cw{findloop_is_bridge()} on
4965the pair A,V will return true (removing that edge would separate the
4966two sets from each other), and will report that there are three
4967vertices on the A side and four on the V side.
4968
4969\H{utils-combi} Choosing r things out of n
4970
4971This section describes a small API for iterating over all combinations
4972of r things out of n.
4973
4974For example, if you asked for all combinations of 3 things out of 5,
4975you'd get back the sets \{0,1,2\}, \{0,1,3\}, \{0,1,4\}, \{0,2,3\},
4976\{0,2,4\}, \{0,3,4\}, \{1,2,3\}, \{1,2,4\}, \{1,3,4\}, and \{2,3,4\}.
4977
4978These functions use a structure called a \c{combi_ctx}, which contains
4979an element \c{int *a} holding each returned combination, plus other
4980fields for implementation use only.
4981
4982\S{utils-combi-new} \cw{new_combi()}
4983
4984\c combi_ctx *new_combi(int r, int n);
4985
4986Allocates a new \c{combi_ctx} structure for enumerating r things out
4987of n.
4988
4989\S{utils-combi-free} \cw{free_combi()}
4990
4991\c void free_combi(combi_ctx *combi);
4992
4993Frees a \c{combi_ctx} structure.
4994
4995\S{utils-combi-reset} \cw{reset_combi()}
4996
4997\c void reset_combi(combi_ctx *combi);
4998
4999Resets an existing \c{combi_ctx} structure to the start of its
5000iteration
5001
5002\S{utils-combi-next} \cw{next_combi()}
5003
5004\c combi_ctx *next_combi(combi_ctx *combi);
5005
5006Requests a combination from a \c{combi_ctx}.
5007
5008If there are none left to return, the return value is \cw{NULL}.
5009Otherwise, it returns the input structure \c{combi}, indicating that
5010it has filled in \cw{combi->a[0]}, \cw{combi->a[1]}, ...,
5011\cw{combi->a[r-1]} with an increasing sequence of distinct integers
5012from \cw{0} to \cw{n-1} inclusive.
5013
5014\H{utils-misc} Miscellaneous utility functions and macros
5015
5016This section contains all the utility functions which didn't
5017sensibly fit anywhere else.
5018
5019\S{utils-maxmin} \cw{max()} and \cw{min()}
5020
5021The main Puzzles header file defines the pretty standard macros
5022\cw{max()} and \cw{min()}, each of which is given two arguments and
5023returns the one which compares greater or less respectively.
5024
5025These macros may evaluate their arguments multiple times. Avoid side
5026effects.
5027
5028\S{utils-max-digits} \cw{MAX_DIGITS()}
5029
5030The \cw{MAX_DIGITS()} macro, defined in the main Puzzles header file,
5031takes a type (or a variable of that type) and expands to an integer
5032constant representing a reasonable upper bound on the number of
5033characters that a number of that type could expand to when formatted
5034as a decimal number using the \c{%u} or \c{%d} format of
5035\cw{printf()}. This is useful for allocating a fixed-size buffer
5036that's guaranteed to be big enough to \cw{sprintf()} a value into.
5037Don't forget to add one for the trailing \cw{'\\0'}!
5038
5039\S{utils-pi} \cw{PI}
5040
5041The main Puzzles header file defines a macro \cw{PI} which expands
5042to a floating-point constant representing pi.
5043
5044(I've never understood why ANSI's \cw{<math.h>} doesn't define this.
5045It'd be so useful!)
5046
5047\S{utils-obfuscate-bitmap} \cw{obfuscate_bitmap()}
5048
5049\c void obfuscate_bitmap(unsigned char *bmp, int bits, bool decode);
5050
5051This function obscures the contents of a piece of data, by
5052cryptographic methods. It is useful for games of hidden information
5053(such as Mines, Guess or Black Box), in which the game ID
5054theoretically reveals all the information the player is supposed to
5055be trying to guess. So in order that players should be able to send
5056game IDs to one another without accidentally spoiling the resulting
5057game by looking at them, these games obfuscate their game IDs using
5058this function.
5059
5060Although the obfuscation function is cryptographic, it cannot
5061properly be called encryption because it has no key. Therefore,
5062anybody motivated enough can re-implement it, or hack it out of the
5063Puzzles source, and strip the obfuscation off one of these game IDs
5064to see what lies beneath. (Indeed, they could usually do it much
5065more easily than that, by entering the game ID into their own copy
5066of the puzzle and hitting Solve.) The aim is not to protect against
5067a determined attacker; the aim is simply to protect people who
5068wanted to play the game honestly from \e{accidentally} spoiling
5069their own fun.
5070
5071The input argument \c{bmp} points at a piece of memory to be
5072obfuscated. \c{bits} gives the length of the data. Note that that
5073length is in \e{bits} rather than bytes: if you ask for obfuscation
5074of a partial number of bytes, then you will get it. Bytes are
5075considered to be used from the top down: thus, for example, setting
5076\c{bits} to 10 will cover the whole of \cw{bmp[0]} and the \e{top
5077two} bits of \cw{bmp[1]}. The remainder of a partially used byte is
5078undefined (i.e. it may be corrupted by the function).
5079
5080The parameter \c{decode} is \cw{false} for an encoding operation,
5081and \cw{true} for a decoding operation. Each is the inverse of the
5082other. (There's no particular reason you shouldn't obfuscate by
5083decoding and restore cleartext by encoding, if you really wanted to;
5084it should still work.)
5085
5086The input bitmap is processed in place.
5087
5088\S{utils-bin2hex} \cw{bin2hex()}
5089
5090\c char *bin2hex(const unsigned char *in, int inlen);
5091
5092This function takes an input byte array and converts it into an
5093ASCII string encoding those bytes in (lower-case) hex. It returns a
5094dynamically allocated string containing that encoding.
5095
5096This function is useful for encoding the result of
5097\cw{obfuscate_bitmap()} in printable ASCII for use in game IDs.
5098
5099\S{utils-hex2bin} \cw{hex2bin()}
5100
5101\c unsigned char *hex2bin(const char *in, int outlen);
5102
5103This function takes an ASCII string containing hex digits, and
5104converts it back into a byte array of length \c{outlen}. If there
5105aren't enough hex digits in the string, the contents of the
5106resulting array will be undefined.
5107
5108This function is the inverse of \cw{bin2hex()}.
5109
5110\S{utils-fgetline} \cw{fgetline()}
5111
5112\c char *fgetline(FILE *fp);
5113
5114This function reads a single line of text from a standard C input
5115stream, and returns it as a dynamically allocated string. The returned
5116string still has a newline on the end.
5117
5118\S{utils-arraysort} \cw{arraysort()}
5119
5120Sorts an array, with slightly more flexibility than the standard C
5121\cw{qsort()}.
5122
5123This function is really implemented as a macro, so it doesn't have a
5124prototype as such. But you could imagine it having a prototype like
5125this:
5126
5127\c void arraysort(element_t *array, size_t nmemb,
5128\c arraysort_cmpfn_t cmp, void *ctx);
5129
5130in which \c{element_t} is an unspecified type.
5131
5132(Really, there's an underlying function that takes an extra parameter
5133giving the size of each array element. But callers are encouraged to
5134use this macro version, which fills that in automatically using
5135\c{sizeof}.)
5136
5137This function behaves essentially like \cw{qsort()}: it expects
5138\c{array} to point to an array of \c{nmemb} elements, and it will sort
5139them in place into the order specified by the comparison function
5140\c{cmp}.
5141
5142The comparison function should have this prototype:
5143
5144\c int cmp(const void *a, const void *b, void *ctx);
5145
5146in which \c{a} and \c{b} point at the two elements to be compared, and
5147the return value is negative if \cw{a<b} (that is, \c{a} should appear
5148before \c{b} in the output array), positive if \cw{a>b}, or zero if
5149\c{a=b}.
5150
5151The \c{ctx} parameter to \cw{arraysort()} is passed directly to the
5152comparison function. This is the feature that makes \cw{arraysort()}
5153more flexible than standard \cw{qsort()}: it lets you vary the sorting
5154criterion in a dynamic manner without having to write global variables
5155in the caller for the compare function to read.
5156
5157\S{utils-colour-mix} \cw{colour_mix()}
5158
5159\c void colour_mix(const float src1[3], const float src2[3], float p,
5160\c float dst[3]);
5161
5162This function mixes the colours \c{src1} and \c{src2} in specified
5163proportions, producing \c{dst}. \c{p} is the proportion of \c{src2}
5164in the result. So if \c{p} is \cw{1.0}, \cw{dst} will be the same as
5165\c{src2}. If \c{p} is \cw{0.0}, \cw{dst} will be the same as
5166\c{src1}. And if \c{p} is somewhere in between, so will \c{dst} be.
5167\c{p} is not restricted to the range \cw{0.0} to \cw{1.0}. Values
5168outside that range will produce extrapolated colours, which may be
5169useful for some purposes, but may also produce impossible colours.
5170
5171\S{utils-game-mkhighlight} \cw{game_mkhighlight()}
5172
5173\c void game_mkhighlight(frontend *fe, float *ret,
5174\c int background, int highlight, int lowlight);
5175
5176It's reasonably common for a puzzle game's graphics to use
5177highlights and lowlights to indicate \q{raised} or \q{lowered}
5178sections. Fifteen, Sixteen and Twiddle are good examples of this.
5179
5180Puzzles using this graphical style are running a risk if they just
5181use whatever background colour is supplied to them by the front end,
5182because that background colour might be too light or dark to see any
5183highlights on at all. (In particular, it's not unheard of for the
5184front end to specify a default background colour of white.)
5185
5186Therefore, such puzzles can call this utility function from their
5187\cw{colours()} routine (\k{backend-colours}). You pass it your front
5188end handle, a pointer to the start of your return array, and three
5189colour indices. It will:
5190
5191\b call \cw{frontend_default_colour()} (\k{frontend-default-colour})
5192to fetch the front end's default background colour
5193
5194\b alter the brightness of that colour if it's unsuitable
5195
5196\b define brighter and darker variants of the colour to be used as
5197highlights and lowlights
5198
5199\b write those results into the relevant positions in the \c{ret}
5200array.
5201
5202Thus, \cw{ret[background*3]} to \cw{ret[background*3+2]} will be set
5203to RGB values defining a sensible background colour, and similary
5204\c{highlight} and \c{lowlight} will be set to sensible colours.
5205
5206Either \c{highlight} or \c{lowlight} may be passed in as \cw{-1} to
5207indicate that the back-end does not require a highlight or lowlight
5208colour, respectively.
5209
5210\S{utils-game-mkhighlight-specific} \cw{game_mkhighlight_specific()}
5211
5212\c void game_mkhighlight_specific(frontend *fe, float *ret,
5213\c int background, int highlight, int lowlight);
5214
5215This function behaves exactly like \cw{game_mkhighlight()}, except
5216that it expects the background colour to have been filled in
5217\e{already} in the elements \cw{ret[background*3]} to
5218\cw{ret[background*3+2]}. It will fill in the other two colours as
5219brighter and darker versions of that.
5220
5221This is useful if you want to show relief sections of a puzzle in more
5222than one base colour.
5223
5224\S{utils-button2label} \cw{button2label()}
5225
5226\c char *button2label(int button);
5227
5228This function generates a descriptive text label for \cw{button},
5229which should be a button code that can be passed to the midend. For
5230example, calling this function with \cw{CURSOR_UP} will result in the
5231string \cw{"Up"}. This function should only be called when the
5232\cw{key_label} item returned by a backend's \cw{request_keys()}
5233(\k{backend-request-keys}) function has its \cw{label} field set to
5234\cw{NULL}; in this case, the corresponding \cw{button} field can be
5235passed to this function to obtain an appropriate label. If, however,
5236the field is not \cw{NULL}, this function should not be called with
5237the corresponding \cw{button} field.
5238
5239The returned string is dynamically allocated and should be
5240\cw{sfree}'d by the caller.
5241
5242\S{utils-move-cursor} \cw{move_cursor()}
5243
5244\c char *move_cursor(int button, int *x, int *y, int w, int h,
5245\c bool wrap, bool *visible);
5246
5247This function can be called by \cw{interpret_move()} to implement the
5248default keyboard API for moving a cursor around a grid.
5249
5250\c{button} is the same value passed in to \cw{interpret_move()}. If
5251it's not any of \cw{CURSOR_UP}, \cw{CURSOR_DOWN}, \cw{CURSOR_LEFT} or
5252\cw{CURSOR_RIGHT}, the function will do nothing.
5253
5254\c{x} and \c{y} point to two integers which on input give the current
5255location of a cursor in a square grid. \c{w} and \c{h} give the
5256dimensions of the grid. On return, \c{x} and \c{y} are updated to give
5257the cursor's new position according to which arrow key was pressed.
5258
5259This function assumes that the grid coordinates run from \cw{0} to
5260\cw{w-1} inclusive (left to right), and from \cw{0} to \cw{h-1}
5261inclusive (top to bottom).
5262
5263If \c{wrap} is \cw{true}, then trying to move the cursor off any edge
5264of the grid will result in it wrapping round to the corresponding
5265square on the opposite edge. If \c{wrap} is \cw{false}, such a move
5266will have no effect.
5267
5268If \c{visible} is not \cw{NULL}, it points to a flag indicating
5269whether the cursor is visible. This will be set to \cw{true} if
5270\c{button} represents a cursor-movement key.
5271
5272The function returns one of the special constants that can be returned
5273by \cw{interpret_move()}. The return value is \cw{MOVE_UNUSED} if
5274\c{button} is unrecognised, \cw{MOVE_UI_UPDATE} if \c{x}, \c{y}, or
5275\c{visible} was updated, and \cw{MOVE_NO EFFECT} otherwise.
5276
5277\S{utils-divvy-rectangle} \cw{divvy_rectangle()}
5278
5279\c int *divvy_rectangle(int w, int h, int k, random_state *rs);
5280
5281Invents a random division of a rectangle into same-sized polyominoes,
5282such as is found in the block layout of a Solo puzzle in jigsaw mode,
5283or the solution to a Palisade puzzle.
5284
5285\c{w} and \c{h} are the dimensions of the rectangle. \c{k} is the size
5286of polyomino desired. It must be a factor of \c{w*h}.
5287
5288\c{rs} is a \cw{random_state} used to supply the random numbers to
5289select a random division of the rectangle.
5290
5291The return value is a dsf (see \k{utils-dsf}) whose equivalence
5292classes correspond to the polyominoes that the rectangle is divided
5293into. The indices of the dsf are of the form \c{y*w+x}, for the cell
5294with coordinates \cw{x,y}.
5295
5296\S{utils-domino-layout} \cw{domino_layout()}
5297
5298\c int *domino_layout(int w, int h, random_state *rs);
5299
5300Invents a random tiling of a rectangle with dominoes.
5301
5302\c{w} and \c{h} are the dimensions of the rectangle. If they are both
5303odd, then one square will be left untiled.
5304
5305\c{rs} is a \cw{random_state} used to supply the random numbers to
5306select a random division of the rectangle.
5307
5308The return value is an array in which element \c{y*w+x} represents the
5309cell with coordinates \cw{x,y}. Each element of the array gives the
5310index (in the same representation) of the other end of its domino. If
5311there's a left-over square, then that element contains its own index.
5312
5313\S{utils-domino-layout-prealloc} \cw{domino_layout_prealloc()}
5314
5315\c void domino_layout_prealloc(int w, int h, random_state *rs,
5316\c int *grid, int *grid2, int *list);
5317
5318Just like \cw{domino_layout()}, but does no memory allocation. You can
5319use this to save allocator overhead if you expect to need to generate
5320many domino tilings of the same grid.
5321
5322\c{grid} and \c{grid2} should each have space for \cw{w*h} ints.
5323\c{list} should have space for \c{2*w*h} ints.
5324
5325The returned array is delivered in \c{grid}.
5326
5327\S{utils-strip-button-modifiers} \cw{STRIP_BUTTON_MODIFIERS()}
5328
5329This macro, defined in the main Puzzles header file, strips the
5330modifier flags from the key code passed as an argument. It is
5331equivalent to a bitwise-AND with \cw{~MOD_MASK}.
5332
5333\S{utils-swap-regions} \cw{swap_regions()}
5334
5335\c void swap_regions(void *av, void *bv, size_t size);
5336
5337Swap two regions of memory of \cw{size} bytes. The two regions must
5338not overlap.
5339
5340\C{writing} How to write a new puzzle
5341
5342This chapter gives a guide to how to actually write a new puzzle:
5343where to start, what to do first, how to solve common problems.
5344
5345The previous chapters have been largely composed of facts. This one
5346is mostly advice.
5347
5348\H{writing-editorial} Choosing a puzzle
5349
5350Before you start writing a puzzle, you have to choose one. Your
5351taste in puzzle games is up to you, of course; and, in fact, you're
5352probably reading this guide because you've \e{already} thought of a
5353game you want to write. But if you want to get it accepted into the
5354official Puzzles distribution, then there's a criterion it has to
5355meet.
5356
5357The current Puzzles editorial policy is that all games should be
5358\e{fair}. A fair game is one which a player can only fail to complete
5359through demonstrable lack of skill \dash that is, such that a better
5360player presented with the same game state would have \e{known} to do
5361something different.
5362
5363For a start, that means every game presented to the user must have
5364\e{at least one solution}. Giving the unsuspecting user a puzzle which
5365is actually impossible is not acceptable.
5366
5367(An exception to this: if the user has selected some non-default
5368option which is clearly labelled as potentially unfair, \e{then}
5369you're allowed to generate possibly insoluble puzzles, because the
5370user isn't unsuspecting any more. Same Game and Mines both have
5371options of this type.)
5372
5373Secondly, if the game includes hidden information, then it must be
5374possible to deduce a correct move at every stage from the currently
5375available information. It's not enough that there should exist some
5376sequence of moves which will get from the start state to the solved
5377state, if the player doesn't necessarily have enough information to
5378\e{find} that solution. For example, in the card solitaire game
5379Klondike, it's possible to reach a dead end because you had an
5380arbitrary choice to make on no information, and made it the wrong way,
5381which violates the fairness criterion, because a better player
5382couldn't have known they needed to make the other choice.
5383
5384(Of course, games in this collection always have an Undo function, so
5385if you did take the wrong route through a Klondike game, you could use
5386Undo to back up and try a different choice. This doesn't count. In a
5387fair game, you should be able to determine a correct move from the
5388information visible \e{now}, without having to make moves to get more
5389information that you can then back up and use.)
5390
5391Sometimes you can adjust the rules of an unfair puzzle to make it meet
5392this definition of fairness. For example, more than one implementation
5393of solitaire-style games (including card solitaires and Mahjong
5394Solitaire) include a UI action to shuffle the remaining cards or tiles
5395without changing their position; this action might be available at any
5396time with a time or points penalty, or it might be illegal to use
5397unless you have no other possible move. Adding an option like this
5398would make a game \e{technically} fair, but it's better to avoid even
5399that if you can.
5400
5401Providing a \e{unique} solution is a little more negotiable; it
5402depends on the puzzle. Solo would have been of unacceptably low
5403quality if it didn't always have a unique solution, whereas Twiddle
5404inherently has multiple solutions by its very nature and it would
5405have been meaningless to even \e{suggest} making it uniquely
5406soluble. Somewhere in between, Flip could reasonably be made to have
5407unique solutions (by enforcing a zero-dimension kernel in every
5408generated matrix) but it doesn't seem like a serious quality problem
5409that it doesn't.
5410
5411Of course, you don't \e{have} to care about all this. There's
5412nothing stopping you implementing any puzzle you want to if you're
5413happy to maintain your puzzle yourself, distribute it from your own
5414web site, fork the Puzzles code completely, or anything like that.
5415It's free software; you can do what you like with it. But any game
5416that you want to be accepted into \e{my} Puzzles code base has to
5417satisfy the fairness criterion, which means all randomly generated
5418puzzles must have a solution (unless the user has deliberately
5419chosen otherwise) and it must be possible \e{in theory} to find that
5420solution without having to guess.
5421
5422\H{writing-gs} Getting started
5423
5424The simplest way to start writing a new puzzle is to copy
5425\c{nullgame.c}. This is a template puzzle source file which does
5426almost nothing, but which contains all the back end function
5427prototypes and declares the back end data structure correctly. It is
5428built every time the rest of Puzzles is built, to ensure that it
5429doesn't get out of sync with the code and remains buildable.
5430
5431So start by copying \c{nullgame.c} into your new source file. Then
5432you'll gradually add functionality until the very boring Null Game
5433turns into your real game.
5434
5435Next you'll need to add your puzzle to the build scripts, in order to
5436compile it conveniently. Puzzles is a CMake project, so you do this by
5437adding a \cw{puzzle()} statement to CMakeLists.txt. Look at the
5438existing ones to see what those look like, and add one that looks
5439similar.
5440
5441Once your source file is building, you can move on to the fun bit.
5442
5443\S{writing-generation} Puzzle generation
5444
5445Randomly generating instances of your puzzle is almost certain to be
5446the most difficult part of the code, and also the task with the
5447highest chance of turning out to be completely infeasible. Therefore
5448I strongly recommend doing it \e{first}, so that if it all goes
5449horribly wrong you haven't wasted any more time than you absolutely
5450had to. What I usually do is to take an unmodified \c{nullgame.c},
5451and start adding code to \cw{new_game_desc()} which tries to
5452generate a puzzle instance and print it out using \cw{printf()}.
5453Once that's working, \e{then} I start connecting it up to the return
5454value of \cw{new_game_desc()}, populating other structures like
5455\c{game_params}, and generally writing the rest of the source file.
5456
5457There are many ways to generate a puzzle which is known to be
5458soluble. In this section I list all the methods I currently know of,
5459in case any of them can be applied to your puzzle. (Not all of these
5460methods will work, or in some cases even make sense, for all
5461puzzles.)
5462
5463Some puzzles are mathematically tractable, meaning you can work out
5464in advance which instances are soluble. Sixteen, for example, has a
5465parity constraint in some settings which renders exactly half the
5466game space unreachable, but it can be mathematically proved that any
5467position not in that half \e{is} reachable. Therefore, Sixteen's
5468grid generation simply consists of selecting at random from a well
5469defined subset of the game space. Cube in its default state is even
5470easier: \e{every} possible arrangement of the blue squares and the
5471cube's starting position is soluble!
5472
5473Another option is to redefine what you mean by \q{soluble}. Black
5474Box takes this approach. There are layouts of balls in the box which
5475are completely indistinguishable from one another no matter how many
5476beams you fire into the box from which angles, which would normally
5477be grounds for declaring those layouts unfair; but fortunately,
5478detecting that indistinguishability is computationally easy. So
5479Black Box doesn't demand that your ball placements match its own; it
5480merely demands that your ball placements be \e{indistinguishable}
5481from the ones it was thinking of. If you have an ambiguous puzzle,
5482then any of the possible answers is considered to be a solution.
5483Having redefined the rules in that way, any puzzle is soluble again.
5484
5485Those are the simple techniques. If they don't work, you have to get
5486cleverer.
5487
5488One way to generate a soluble puzzle is to start from the solved
5489state and make inverse moves until you reach a starting state. Then
5490you know there's a solution, because you can just list the inverse
5491moves you made and make them in the opposite order to return to the
5492solved state.
5493
5494This method can be simple and effective for puzzles where you get to
5495decide what's a starting state and what's not. In Pegs, for example,
5496the generator begins with one peg in the centre of the board and
5497makes inverse moves until it gets bored; in this puzzle, valid
5498inverse moves are easy to detect, and \e{any} state that's reachable
5499from the solved state by inverse moves is a reasonable starting
5500position. So Pegs just continues making inverse moves until the
5501board satisfies some criteria about extent and density, and then
5502stops and declares itself done.
5503
5504For other puzzles, it can be a lot more difficult. Same Game uses
5505this strategy too, and it's lucky to get away with it at all: valid
5506inverse moves aren't easy to find (because although it's easy to
5507insert additional squares in a Same Game position, it's difficult to
5508arrange that \e{after} the insertion they aren't adjacent to any
5509other squares of the same colour), so you're constantly at risk of
5510running out of options and having to backtrack or start again. Also,
5511Same Game grids never start off half-empty, which means you can't
5512just stop when you run out of moves \dash you have to find a way to
5513fill the grid up \e{completely}.
5514
5515The other way to generate a puzzle that's soluble is to start from
5516the other end, and actually write a \e{solver}. This tends to ensure
5517that a puzzle has a \e{unique} solution over and above having a
5518solution at all, so it's a good technique to apply to puzzles for
5519which that's important.
5520
5521One theoretical drawback of generating soluble puzzles by using a
5522solver is that your puzzles are restricted in difficulty to those
5523which the solver can handle. (Most solvers are not fully general:
5524many sets of puzzle rules are NP-complete or otherwise nasty, so
5525most solvers can only handle a subset of the theoretically soluble
5526puzzles.) It's been my experience in practice, however, that this
5527usually isn't a problem; computers are good at very different things
5528from humans, and what the computer thinks is nice and easy might
5529still be pleasantly challenging for a human. For example, when
5530solving Dominosa puzzles I frequently find myself using a variety of
5531reasoning techniques that my solver doesn't know about; in
5532principle, therefore, I should be able to solve the puzzle using
5533only those techniques it \e{does} know about, but this would involve
5534repeatedly searching the entire grid for the one simple deduction I
5535can make. Computers are good at this sort of exhaustive search, but
5536it's been my experience that human solvers prefer to do more complex
5537deductions than to spend ages searching for simple ones. So in many
5538cases I don't find my own playing experience to be limited by the
5539restrictions on the solver.
5540
5541(This isn't \e{always} the case. Solo is a counter-example;
5542generating Solo puzzles using a simple solver does lead to
5543qualitatively easier puzzles. Therefore I had to make the Solo
5544solver rather more advanced than most of them.)
5545
5546There are several different ways to apply a solver to the problem of
5547generating a soluble puzzle. I list a few of them below.
5548
5549The simplest approach is brute force: randomly generate a puzzle,
5550use the solver to see if it's soluble, and if not, throw it away and
5551try again until you get lucky. This is often a viable technique if
5552all else fails, but it tends not to scale well: for many puzzle
5553types, the probability of finding a uniquely soluble instance
5554decreases sharply as puzzle size goes up, so this technique might
5555work reasonably fast for small puzzles but take (almost) forever at
5556larger sizes. Still, if there's no other alternative it can be
5557usable: Pattern and Dominosa both use this technique. (However,
5558Dominosa has a means of tweaking the randomly generated grids to
5559increase the \e{probability} of them being soluble, by ruling out
5560one of the most common ambiguous cases. This improved generation
5561speed by over a factor of 10 on the highest preset!)
5562
5563An approach which can be more scalable involves generating a grid
5564and then tweaking it to make it soluble. This is the technique used
5565by Mines and also by Net: first a random puzzle is generated, and
5566then the solver is run to see how far it gets. Sometimes the solver
5567will get stuck; when that happens, examine the area it's having
5568trouble with, and make a small random change in that area to allow
5569it to make more progress. Continue solving (possibly even without
5570restarting the solver), tweaking as necessary, until the solver
5571finishes. Then restart the solver from the beginning to ensure that
5572the tweaks haven't caused new problems in the process of solving old
5573ones (which can sometimes happen).
5574
5575This strategy works well in situations where the usual solver
5576failure mode is to get stuck in an easily localised spot. Thus it
5577works well for Net and Mines, whose most common failure mode tends
5578to be that most of the grid is fine but there are a few widely
5579separated ambiguous sections; but it would work less well for
5580Dominosa, in which the way you get stuck is to have scoured the
5581whole grid and not found anything you can deduce \e{anywhere}. Also,
5582it relies on there being a low probability that tweaking the grid
5583introduces a new problem at the same time as solving the old one;
5584Mines and Net also have the property that most of their deductions
5585are local, so that it's very unlikely for a tweak to affect
5586something half way across the grid from the location where it was
5587applied. In Dominosa, by contrast, a lot of deductions use
5588information about half the grid (\q{out of all the sixes, only one
5589is next to a three}, which can depend on the values of up to 32 of
5590the 56 squares in the default setting!), so this tweaking strategy
5591would be rather less likely to work well.
5592
5593A more specialised strategy is that used in Solo and Slant. These
5594puzzles have the property that they derive their difficulty from not
5595presenting all the available clues. (In Solo's case, if all the
5596possible clues were provided then the puzzle would already be
5597solved; in Slant it would still require user action to fill in the
5598lines, but it would present no challenge at all). Therefore, a
5599simple generation technique is to leave the decision of which clues
5600to provide until the last minute. In other words, first generate a
5601random \e{filled} grid with all possible clues present, and then
5602gradually remove clues for as long as the solver reports that it's
5603still soluble. Unlike the methods described above, this technique
5604\e{cannot} fail \dash once you've got a filled grid, nothing can
5605stop you from being able to convert it into a viable puzzle.
5606However, it wouldn't even be meaningful to apply this technique to
5607(say) Pattern, in which clues can never be left out, so the only way
5608to affect the set of clues is by altering the solution.
5609
5610(Unfortunately, Solo is complicated by the need to provide puzzles
5611at varying difficulty levels. It's easy enough to generate a puzzle
5612of \e{at most} a given level of difficulty; you just have a solver
5613with configurable intelligence, and you set it to a given level and
5614apply the above technique, thus guaranteeing that the resulting grid
5615is solvable by someone with at most that much intelligence. However,
5616generating a puzzle of \e{at least} a given level of difficulty is
5617rather harder; if you go for \e{at most} Intermediate level, you're
5618likely to find that you've accidentally generated a Trivial grid a
5619lot of the time, because removing just one number is sufficient to
5620take the puzzle from Trivial straight to Ambiguous. In that
5621situation Solo has no remaining options but to throw the puzzle away
5622and start again.)
5623
5624A final strategy is to use the solver \e{during} puzzle
5625construction: lay out a bit of the grid, run the solver to see what
5626it allows you to deduce, and then lay out a bit more to allow the
5627solver to make more progress. There are articles on the web that
5628recommend constructing Sudoku puzzles by this method (which is
5629completely the opposite way round to how Solo does it); for Sudoku
5630it has the advantage that you get to specify your clue squares in
5631advance (so you can have them make pretty patterns).
5632
5633Rectangles uses a strategy along these lines. First it generates a
5634grid by placing the actual rectangles; then it has to decide where
5635in each rectangle to place a number. It uses a solver to help it
5636place the numbers in such a way as to ensure a unique solution. It
5637does this by means of running a test solver, but it runs the solver
5638\e{before} it's placed any of the numbers \dash which means the
5639solver must be capable of coping with uncertainty about exactly
5640where the numbers are! It runs the solver as far as it can until it
5641gets stuck; then it narrows down the possible positions of a number
5642in order to allow the solver to make more progress, and so on. Most
5643of the time this process terminates with the grid fully solved, at
5644which point any remaining number-placement decisions can be made at
5645random from the options not so far ruled out. Note that unlike the
5646Net/Mines tweaking strategy described above, this algorithm does not
5647require a checking run after it completes: if it finishes
5648successfully at all, then it has definitely produced a uniquely
5649soluble puzzle.
5650
5651Most of the strategies described above are not 100% reliable. Each
5652one has a failure rate: every so often it has to throw out the whole
5653grid and generate a fresh one from scratch. (Solo's strategy would
5654be the exception, if it weren't for the need to provide configurable
5655difficulty levels.) Occasional failures are not a fundamental
5656problem in this sort of work, however: it's just a question of
5657dividing the grid generation time by the success rate (if it takes
565810ms to generate a candidate grid and 1/5 of them work, then it will
5659take 50ms on average to generate a viable one), and seeing whether
5660the expected time taken to \e{successfully} generate a puzzle is
5661unacceptably slow. Dominosa's generator has a very low success rate
5662(about 1 out of 20 candidate grids turn out to be usable, and if you
5663think \e{that's} bad then go and look at the source code and find
5664the comment showing what the figures were before the generation-time
5665tweaks!), but the generator itself is very fast so this doesn't
5666matter. Rectangles has a slower generator, but fails well under 50%
5667of the time.
5668
5669So don't be discouraged if you have an algorithm that doesn't always
5670work: if it \e{nearly} always works, that's probably good enough.
5671The one place where reliability is important is that your algorithm
5672must never produce false positives: it must not claim a puzzle is
5673soluble when it isn't. It can produce false negatives (failing to
5674notice that a puzzle is soluble), and it can fail to generate a
5675puzzle at all, provided it doesn't do either so often as to become
5676slow.
5677
5678One last piece of advice: for grid-based puzzles, when writing and
5679testing your generation algorithm, it's almost always a good idea
5680\e{not} to test it initially on a grid that's square (i.e.
5681\cw{w==h}), because if the grid is square then you won't notice if
5682you mistakenly write \c{h} instead of \c{w} (or vice versa)
5683somewhere in the code. Use a rectangular grid for testing, and any
5684size of grid will be likely to work after that.
5685
5686\S{writing-textformats} Designing textual description formats
5687
5688Another aspect of writing a puzzle which is worth putting some
5689thought into is the design of the various text description formats:
5690the format of the game parameter encoding, the game description
5691encoding, and the move encoding.
5692
5693The first two of these should be reasonably intuitive for a user to
5694type in; so provide some flexibility where possible. Suppose, for
5695example, your parameter format consists of two numbers separated by
5696an \c{x} to specify the grid dimensions (\c{10x10} or \c{20x15}),
5697and then has some suffixes to specify other aspects of the game
5698type. It's almost always a good idea in this situation to arrange
5699that \cw{decode_params()} can handle the suffixes appearing in any
5700order, even if \cw{encode_params()} only ever generates them in one
5701order.
5702
5703These formats will also be expected to be reasonably stable: users
5704will expect to be able to exchange game IDs with other users who
5705aren't running exactly the same version of your game. So make them
5706robust and stable: don't build too many assumptions into the game ID
5707format which will have to be changed every time something subtle
5708changes in the puzzle code.
5709
5710\H{writing-howto} Common how-to questions
5711
5712This section lists some common things people want to do when writing
5713a puzzle, and describes how to achieve them within the Puzzles
5714framework.
5715
5716\S{writing-howto-redraw} Redrawing just the changed parts of the window
5717
5718Redrawing the entire window on every move is wasteful. If the user
5719makes a move changing only one square of a grid, it's better to redraw
5720just that square.
5721
5722(Yes, computers are fast these days, but these puzzles still try to be
5723portable to devices at the less fast end of the spectrum, so it's
5724still worth saving effort where it's easy. On the other hand, some
5725puzzles just \e{can't} do this easily \dash Untangle is an example
5726that really does have no better option than to redraw everything.)
5727
5728For a typical grid-oriented puzzle, a robust way to do this is:
5729
5730\b Invent a data representation that describes everything about the
5731appearance of a grid cell in the puzzle window.
5732
5733\b Have \c{game_drawstate} contain an array of those, describing the
5734current appearance of each cell, as it was last drawn in the window.
5735
5736\b In \cw{redraw()}, loop over each cell deciding what the new
5737appearance should be. If it's not the same as the value stored in
5738\c{game_drawstate}, then redraw that cell, and update the entry in the
5739\c{game_drawstate} array.
5740
5741Where possible, I generally make my data representation an integer
5742full of bit flags, to save space, and to make it easy to compare the
5743old and new versions. If yours needs to be bigger than that, you may
5744have to define a small \cw{struct} and write an equality-checking
5745function.
5746
5747The data representation of the \e{appearance} of a square in
5748\c{game_drawstate} will not generally be identical to the
5749representation of the \e{logical state} of a square in \c{game_state},
5750because many things contribute to a square's appearance other than its
5751logical state. For example:
5752
5753\b Extra information overlaid on the square by the user interface,
5754such as a keyboard-controlled cursor, or highlighting of squares
5755currently involved in a mouse drag action.
5756
5757\b Error highlights marking violations of the puzzle constraints.
5758
5759\b Visual intrusions into one square because of things in nearby
5760squares. For example, if you draw thick lines along the edges between
5761grid squares, then the corners of those lines will be visible in
5762logically unrelated squares. An entry in the \c{game_drawstate} array
5763should describe a specific \e{rectangular area of the screen}, so that
5764those areas can be erased and redrawn independently \dash so it must
5765represent anything that appears in that area, even if it's sticking
5766out from a graphic that logically lives in some other square.
5767
5768\b Temporary changes to the appearance of a square because of an
5769ongoing completion flash.
5770
5771\b The current display mode, if a game provides more than one. (For
5772example, the optional letters distinguishing the different coloured
5773pegs in Guess.)
5774
5775All of this must be included in the \c{game_drawstate} representation,
5776but should not be in the \c{game_state} at all. \cw{redraw()} will
5777pull it all together from the \c{game_state}, the \c{game_ui}, and the
5778animation and flash parameters.
5779
5780To make sure that \e{everything} affecting a square's appearance is
5781included in this representation, it's a good idea to have a separate
5782function for drawing a grid square, and deliberately \e{not} pass it a
5783copy of the \c{game_state} or the \c{game_ui} at all. That way, if you
5784want that function to draw anything differently, you \e{have} to do it
5785by including that information in the representation of a square's
5786appearance.
5787
5788But of course there are a couple of exceptions to this rule. A few
5789things \e{don't} have to go in the \c{game_drawstate} array, and can
5790safely be passed separately to the redraw-square function:
5791
5792\b Anything that remains completely fixed throughout the whole of a
5793game, such as the clues provided by the puzzle. This is safe because a
5794\c{game_drawstate} is never reused between puzzle instances: when you
5795press New Game, a new \c{game_drawstate} will always be created from
5796scratch. So the \c{game_drawstate} only needs to describe everything
5797that might \e{change} during gameplay. If you have a sub-\cw{struct}
5798in your \c{game_state} that describes immutable properties of the
5799current game, as suggested in \k{writing-ref-counting}, then it's safe
5800to pass \e{that substructure} to the redraw-square function, and have
5801it retrieve that information directly.
5802
5803\b How far through a move animation the last redraw was. When
5804\cw{redraw()} is called multiple times during an animated move, it's
5805much easier to just assume that any square involved in the animation
5806will \e{always} need redrawing. So \c{anim_length} can safely be
5807passed separately to the redraw-square function \dash but you also
5808have to remember to redraw a square if \e{either} its appearance is
5809different from the last redraw \e{or} it's involved in an animation.
5810
5811\S{writing-howto-cursor} Drawing an object at only one position
5812
5813A common phenomenon is to have an object described in the
5814\c{game_state} or the \c{game_ui} which can only be at one position.
5815A cursor \dash probably specified in the \c{game_ui} \dash is a good
5816example.
5817
5818In the \c{game_ui}, it would \e{obviously} be silly to have an array
5819covering the whole game grid with a boolean flag stating whether the
5820cursor was at each position. Doing that would waste space, would
5821make it difficult to find the cursor in order to do anything with
5822it, and would introduce the potential for synchronisation bugs in
5823which you ended up with two cursors or none. The obviously sensible
5824way to store a cursor in the \c{game_ui} is to have fields directly
5825encoding the cursor's coordinates.
5826
5827However, it is a mistake to assume that the same logic applies to the
5828\c{game_drawstate}. If you replicate the cursor position fields in the
5829draw state, the redraw code will get very complicated. In the draw
5830state, in fact, it \e{is} probably the right thing to have a cursor
5831flag for every position in the grid, and make it part of the
5832representation of each square's appearance, as described in
5833\k{writing-howto-redraw}. So when you iterate over each square in
5834\c{redraw()} working out its position, you set the \q{cursor here}
5835flag in the representation of the square's appearance, if its
5836coordinates match the cursor coordinates stored in the \c{game_ui}.
5837This will automatically ensure that when the cursor moves, the redraw
5838loop will redraw the square that \e{previously} contained the cursor
5839and doesn't any more, and the one that now contains the cursor.
5840
5841\S{writing-keyboard-cursor} Implementing a keyboard-controlled cursor
5842
5843It is often useful to provide a keyboard control method in a
5844basically mouse-controlled game. A keyboard-controlled cursor is
5845best implemented by storing its location in the \c{game_ui} (since
5846if it were in the \c{game_state} then the user would have to
5847separately undo every cursor move operation). So the procedure would
5848be:
5849
5850\b Put cursor position fields in the \c{game_ui}.
5851
5852\b \cw{interpret_move()} responds to arrow keys by modifying the
5853cursor position fields and returning \cw{MOVE_UI_UPDATE}.
5854
5855\b \cw{interpret_move()} responds to some other button \dash either
5856\cw{CURSOR_SELECT} or some more specific thing like a number key \dash
5857by actually performing a move based on the current cursor location.
5858
5859\b You might want an additional \c{game_ui} field stating whether
5860the cursor is currently visible, and having it disappear when a
5861mouse action occurs (so that it doesn't clutter the display when not
5862actually in use).
5863
5864\b You might also want to automatically hide the cursor in
5865\cw{changed_state()} when the current game state changes to one in
5866which there is no move to make (which is the case in some types of
5867completed game).
5868
5869\b \cw{redraw()} draws the cursor using the technique described in
5870\k{writing-howto-cursor}.
5871
5872\S{writing-howto-dragging} Implementing draggable sprites
5873
5874Some games have a user interface which involves dragging some sort
5875of game element around using the mouse. If you need to show a
5876graphic moving smoothly over the top of other graphics, use a
5877blitter (see \k{drawing-blitter} for the blitter API) to save the
5878background underneath it. The typical scenario goes:
5879
5880\b Have a blitter field in the \c{game_drawstate}.
5881
5882\b Set the blitter field to \cw{NULL} in the game's
5883\cw{new_drawstate()} function, since you don't yet know how big the
5884piece of saved background needs to be.
5885
5886\b In the game's \cw{set_size()} function, once you know the size of
5887the object you'll be dragging around the display and hence the
5888required size of the blitter, actually allocate the blitter.
5889
5890\b In \cw{free_drawstate()}, free the blitter if it's not \cw{NULL}.
5891
5892\b In \cw{interpret_move()}, respond to mouse-down and mouse-drag
5893events by updating some fields in the \cw{game_ui} which indicate
5894that a drag is in progress.
5895
5896\b At the \e{very end} of \cw{redraw()}, after all other drawing has
5897been done, draw the moving object if there is one. First save the
5898background under the object in the blitter; then set a clip
5899rectangle covering precisely the area you just saved (just in case
5900anti-aliasing or some other error causes your drawing to go beyond
5901the area you saved). Then draw the object, and call \cw{unclip()}.
5902Finally, set a flag in the \cw{game_drawstate} that indicates that
5903the blitter needs restoring.
5904
5905\b At the very start of \cw{redraw()}, before doing anything else at
5906all, check the flag in the \cw{game_drawstate}, and if it says the
5907blitter needs restoring then restore it. (Then clear the flag, so
5908that this won't happen again in the next redraw if no moving object
5909is drawn this time.)
5910
5911This way, you will be able to write the rest of the redraw function
5912completely ignoring the dragged object, as if it were floating above
5913your bitmap and being completely separate.
5914
5915\S{writing-ref-counting} Sharing large invariant data between all
5916game states
5917
5918In some puzzles, there is a large amount of data which never changes
5919between game states. The array of numbers in Dominosa is a good
5920example.
5921
5922You \e{could} dynamically allocate a copy of that array in every
5923\c{game_state}, and have \cw{dup_game()} make a fresh copy of it for
5924every new \c{game_state}; but it would waste memory and time. A
5925more efficient way is to use a reference-counted structure.
5926
5927\b Define a structure type containing the data in question, and also
5928containing an integer reference count.
5929
5930\b Have a field in \c{game_state} which is a pointer to this
5931structure.
5932
5933\b In \cw{new_game()}, when creating a fresh game state at the start
5934of a new game, create an instance of this structure, initialise it
5935with the invariant data, and set its reference count to 1.
5936
5937\b In \cw{dup_game()}, rather than making a copy of the structure
5938for the new game state, simply set the new game state to point at
5939the same copy of the structure, and increment its reference count.
5940
5941\b In \cw{free_game()}, decrement the reference count in the
5942structure pointed to by the game state; if the count reaches zero,
5943free the structure.
5944
5945This way, the invariant data will persist for only as long as it's
5946genuinely needed; \e{as soon} as the last game state for a
5947particular puzzle instance is freed, the invariant data for that
5948puzzle will vanish as well. Reference counting is a very efficient
5949form of garbage collection, when it works at all. (Which it does in
5950this instance, of course, because there's no possibility of circular
5951references.)
5952
5953\S{writing-flash-types} Implementing multiple types of flash
5954
5955In some games you need to flash in more than one different way.
5956Mines, for example, flashes white when you win, and flashes red when
5957you tread on a mine and die.
5958
5959The simple way to do this is:
5960
5961\b Have a field in the \c{game_ui} which describes the type of flash.
5962
5963\b In \cw{flash_length()}, examine the old and new game states to
5964decide whether a flash is required and what type. Write the type of
5965flash to the \c{game_ui} field whenever you return non-zero.
5966
5967\b In \cw{redraw()}, when you detect that \c{flash_time} is
5968non-zero, examine the field in \c{game_ui} to decide which type of
5969flash to draw.
5970
5971\cw{redraw()} will never be called with \c{flash_time} non-zero
5972unless \cw{flash_length()} was first called to tell the mid-end that
5973a flash was required; so whenever \cw{redraw()} notices that
5974\c{flash_time} is non-zero, you can be sure that the field in
5975\c{game_ui} is correctly set.
5976
5977\S{writing-move-anim} Animating game moves
5978
5979A number of puzzle types benefit from a quick animation of each move
5980you make.
5981
5982For some games, such as Fifteen, this is particularly easy. Whenever
5983\cw{redraw()} is called with \c{oldstate} non-\cw{NULL}, Fifteen
5984simply compares the position of each tile in the two game states,
5985and if the tile is not in the same place then it draws it some
5986fraction of the way from its old position to its new position. This
5987method copes automatically with undo.
5988
5989Other games are less obvious. In Sixteen, for example, you can't
5990just draw each tile a fraction of the way from its old to its new
5991position: if you did that, the end tile would zip very rapidly past
5992all the others to get to the other end and that would look silly.
5993(Worse, it would look inconsistent if the end tile was drawn on top
5994going one way and on the bottom going the other way.)
5995
5996A useful trick here is to define a field or two in the game state
5997that indicates what the last move was.
5998
5999\b Add a \q{last move} field to the \c{game_state} (or two or more
6000fields if the move is complex enough to need them).
6001
6002\b \cw{new_game()} initialises this field to a null value for a new
6003game state.
6004
6005\b \cw{execute_move()} sets up the field to reflect the move it just
6006performed.
6007
6008\b \cw{redraw()} now needs to examine its \c{dir} parameter. If
6009\c{dir} is positive, it determines the move being animated by
6010looking at the last-move field in \c{newstate}; but if \c{dir} is
6011negative, it has to look at the last-move field in \c{oldstate}, and
6012invert whatever move it finds there.
6013
6014Note also that Sixteen needs to store the \e{direction} of the move,
6015because you can't quite determine it by examining the row or column
6016in question. You can in almost all cases, but when the row is
6017precisely two squares long it doesn't work since a move in either
6018direction looks the same. (You could argue that since moving a
60192-element row left and right has the same effect, it doesn't matter
6020which one you animate; but in fact it's very disorienting to click
6021the arrow left and find the row moving right, and almost as bad to
6022undo a move to the right and find the game animating \e{another}
6023move to the right.)
6024
6025\S{writing-conditional-anim} Animating drag operations
6026
6027In Untangle, moves are made by dragging a node from an old position
6028to a new position. Therefore, at the time when the move is initially
6029made, it should not be animated, because the node has already been
6030dragged to the right place and doesn't need moving there. However,
6031it's nice to animate the same move if it's later undone or redone.
6032This requires a bit of fiddling.
6033
6034The obvious approach is to have a flag in the \c{game_ui} which
6035inhibits move animation, and to set that flag in
6036\cw{interpret_move()}. The question is, when would the flag be reset
6037again? The obvious place to do so is \cw{changed_state()}, which
6038will be called once per move. But it will be called \e{before}
6039\cw{anim_length()}, so if it resets the flag then \cw{anim_length()}
6040will never see the flag set at all.
6041
6042The solution is to have \e{two} flags in a queue.
6043
6044\b Define two flags in \c{game_ui}; let's call them \q{current} and
6045\q{next}.
6046
6047\b Set both to \cw{false} in \c{new_ui()}.
6048
6049\b When a drag operation completes in \cw{interpret_move()}, set the
6050\q{next} flag to \cw{true}.
6051
6052\b Every time \cw{changed_state()} is called, set the value of
6053\q{current} to the value in \q{next}, and then set the value of
6054\q{next} to \cw{false}.
6055
6056\b That way, \q{current} will be \cw{true} \e{after} a call to
6057\cw{changed_state()} if and only if that call to
6058\cw{changed_state()} was the result of a drag operation processed by
6059\cw{interpret_move()}. Any other call to \cw{changed_state()}, due
6060to an Undo or a Redo or a Restart or a Solve, will leave \q{current}
6061\cw{false}.
6062
6063\b So now \cw{anim_length()} can request a move animation if and
6064only if the \q{current} flag is \e{not} set.
6065
6066\S{writing-cheating} Inhibiting the victory flash when Solve is used
6067
6068Many games flash when you complete them, as a visual congratulation
6069for having got to the end of the puzzle. It often seems like a good
6070idea to disable that flash when the puzzle is brought to a solved
6071state by means of the Solve operation.
6072
6073This is easily done:
6074
6075\b Add a \q{cheated} flag to the \c{game_state}.
6076
6077\b Set this flag to \cw{false} in \cw{new_game()}.
6078
6079\b Have \cw{solve()} return a move description string which clearly
6080identifies the move as a solve operation.
6081
6082\b Have \cw{execute_move()} respond to that clear identification by
6083setting the \q{cheated} flag in the returned \c{game_state}. The
6084flag will then be propagated to all subsequent game states, even if
6085the user continues fiddling with the game after it is solved.
6086
6087\b \cw{flash_length()} now returns non-zero if \c{oldstate} is not
6088completed and \c{newstate} is, \e{and} neither state has the
6089\q{cheated} flag set.
6090
6091\H{writing-testing} Things to test once your puzzle is written
6092
6093Puzzle implementations written in this framework are self-testing as
6094far as I could make them.
6095
6096Textual game and move descriptions, for example, are generated and
6097parsed as part of the normal process of play. Therefore, if you can
6098make moves in the game \e{at all} you can be reasonably confident
6099that the mid-end serialisation interface will function correctly and
6100you will be able to save your game. (By contrast, if I'd stuck with
6101a single \cw{make_move()} function performing the jobs of both
6102\cw{interpret_move()} and \cw{execute_move()}, and had separate
6103functions to encode and decode a game state in string form, then
6104those functions would not be used during normal play; so they could
6105have been completely broken, and you'd never know it until you tried
6106to save the game \dash which would have meant you'd have to test
6107game saving \e{extensively} and make sure to test every possible
6108type of game state. As an added bonus, doing it the way I did leads
6109to smaller save files.)
6110
6111There is one exception to this, which is the string encoding of the
6112\c{game_ui}. Most games do not store anything permanent in the
6113\c{game_ui}, and hence do not need to put anything in its encode and
6114decode functions; but if there is anything in there, you do need to
6115test game loading and saving to ensure those functions work
6116properly.
6117
6118It's also worth testing undo and redo of all operations, to ensure
6119that the redraw and the animations (if any) work properly. Failing
6120to animate undo properly seems to be a common error.
6121
6122Other than that, just use your common sense.