1 Developer documentation for Simon Tatham's puzzle collection
2 ============================================================
4 This is a guide to the internal structure of Simon Tatham's Portable
5 Puzzle Collection (henceforth referred to simply as `Puzzles'), for
6 use by anyone attempting to implement a new puzzle or port to a new
9 This guide is believed correct as of r6190. Hopefully it will be updated
10 along with the code in future, but if not, I've at least left this
11 version number in here so you can figure out what's changed by tracking
12 commit comments from there onwards.
17 The Puzzles code base is divided into four parts: a set of
18 interchangeable front ends, a set of interchangeable back ends, a
19 universal `middle end' which acts as a buffer between the two, and a
20 bunch of miscellaneous utility functions. In the following sections I
21 give some general discussion of each of these parts.
26 The front end is the non-portable part of the code: it's the bit that
27 you replace completely when you port to a different platform. So it's
28 responsible for all system calls, all GUI interaction, and anything else
31 The current front ends in the main code base are for Windows, GTK and
32 MacOS X; I also know of a third-party front end for PalmOS.
34 The front end contains main() or the local platform's equivalent. Top-
35 level control over the application's execution flow belongs to the front
36 end (it isn't, for example, a set of functions called by a universal
37 main() somewhere else).
39 The front end has complete freedom to design the GUI for any given
40 port of Puzzles. There is no centralised mechanism for maintaining the
41 menu layout, for example. This has a cost in consistency (when I _do_
42 want the same menu layout on more than one platform, I have to edit
43 two pieces of code in parallel every time I make a change), but the
44 advantage is that local GUI conventions can be conformed to and local
45 constraints adapted to. For example, MacOS X has strict human interface
46 guidelines which specify a different menu layout from the one I've used
47 on Windows and GTK; there's nothing stopping the OS X front end from
48 providing a menu layout consistent with those guidelines.
50 Although the front end is mostly caller rather than the callee in its
51 interactions with other parts of the code, it is required to implement
52 a small API for other modules to call, mostly of drawing functions for
53 games to use when drawing their graphics. The drawing API is documented
54 in chapter 3; the other miscellaneous front end API functions are
55 documented in section 4.34.
60 A `back end', in this collection, is synonymous with a `puzzle'. Each
61 back end implements a different game.
63 At the top level, a back end is simply a data structure, containing a
64 few constants (flag words, preferred pixel size) and a large number of
65 function pointers. Back ends are almost invariably callee rather than
66 caller, which means there's a limitation on what a back end can do on
69 The persistent state in a back end is divided into a number of data
70 structures, which are used for different purposes and therefore likely
71 to be switched around, changed without notice, and otherwise updated by
72 the rest of the code. It is important when designing a back end to put
73 the right pieces of data into the right structures, or standard midend-
74 provided features (such as Undo) may fail to work.
76 The functions and variables provided in the back end data structure are
77 documented in chapter 2.
82 Puzzles has a single and universal `middle end'. This code is common to
83 all platforms and all games; it sits in between the front end and the
84 back end and provides standard functionality everywhere.
86 People adding new back ends or new front ends should generally not need
87 to edit the middle end. On rare occasions there might be a change that
88 can be made to the middle end to permit a new game to do something not
89 currently anticipated by the middle end's present design; however, this
90 is terribly easy to get wrong and should probably not be undertaken
91 without consulting the primary maintainer (me). Patch submissions
92 containing unannounced mid-end changes will be treated on their merits
93 like any other patch; this is just a friendly warning that mid-end
94 changes will need quite a lot of merits to make them acceptable.
96 Functionality provided by the mid-end includes:
98 - Maintaining a list of game state structures and moving back and
99 forth along that list to provide Undo and Redo.
101 - Handling timers (for move animations, flashes on completion, and in
102 some cases actually timing the game).
104 - Handling the container format of game IDs: receiving them, picking
105 them apart into parameters, description and/or random seed, and
106 so on. The game back end need only handle the individual parts
107 of a game ID (encoded parameters and encoded game description);
108 everything else is handled centrally by the mid-end.
110 - Handling standard keystrokes and menu commands, such as `New Game',
111 `Restart Game' and `Quit'.
113 - Pre-processing mouse events so that the game back ends can rely on
114 them arriving in a sensible order (no missing button-release events,
115 no sudden changes of which button is currently pressed, etc).
117 - Handling the dialog boxes which ask the user for a game ID.
119 - Handling serialisation of entire games (for loading and saving a
120 half-finished game to a disk file, or for handling application
121 shutdown and restart on platforms such as PalmOS where state is
122 expected to be saved).
124 Thus, there's a lot of work done once by the mid-end so that individual
125 back ends don't have to worry about it. All the back end has to do is
126 cooperate in ensuring the mid-end can do its work properly.
128 The API of functions provided by the mid-end to be called by the front
129 end is documented in chapter 4.
131 1.4. Miscellaneous utilities
132 ----------------------------
134 In addition to these three major structural components, the Puzzles code
135 also contains a variety of utility modules usable by all of the above
136 components. There is a set of functions to provide platform-independent
137 random number generation; functions to make memory allocation easier;
138 functions which implement a balanced tree structure to be used as
139 necessary in complex algorithms; and a few other miscellaneous
140 functions. All of these are documented in chapter 5.
142 1.5. Structure of this guide
143 ----------------------------
145 There are a number of function call interfaces within Puzzles, and this
146 guide will discuss each one in a chapter of its own. After that, chapter
147 6 discusses how to design new games, with some general design thoughts
150 2. Interface to the back end
151 ----------------------------
153 This chapter gives a detailed discussion of the interface that each back
156 At the top level, each back end source file exports a single global
157 symbol, which is a `const struct game' containing a large number of
158 function pointers and a small amount of constant data. This structure is
159 called by different names depending on what kind of platform the puzzle
160 set is being compiled on:
162 - On platforms such as Windows and GTK, which build a separate binary
163 for each puzzle, the game structure in every back end has the same
164 name, `thegame'; the front end refers directly to this name, so that
165 compiling the same front end module against a different back end
166 module builds a different puzzle.
168 - On platforms such as MacOS X and PalmOS, which build all the puzzles
169 into a single monolithic binary, the game structure in each back end
170 must have a different name, and there's a helper module `list.c'
171 (constructed automatically by the same Perl script that builds the
172 Makefiles) which contains a complete list of those game structures.
174 On the latter type of platform, source files may assume that the
175 preprocessor symbol `COMBINED' has been defined. Thus, the usual code to
176 declare the game structure looks something like this:
179 #define thegame net /* or whatever this game is called */
182 const struct game thegame = {
183 /* lots of structure initialisation in here */
186 Game back ends must also internally define a number of data structures,
187 for storing their various persistent state. This chapter will first
188 discuss the nature and use of those structures, and then go on to give
189 details of every element of the game structure.
194 Each game is required to define four separate data structures. This
195 section discusses each one and suggests what sorts of things need to be
201 The `game_params' structure contains anything which affects the
202 automatic generation of new puzzles. So if puzzle generation is
203 parametrised in any way, those parameters need to be stored in
206 Most puzzles currently in this collection are played on a grid of
207 squares, meaning that the most obvious parameter is the grid size. Many
208 puzzles have additional parameters; for example, Mines allows you to
209 control the number of mines in the grid independently of its size, Net
210 can be wrapping or non-wrapping, Solo has difficulty levels and symmetry
213 A simple rule for deciding whether a data item needs to go in
214 `game_params' is: would the user expect to be able to control this data
215 item from either the preset-game-types menu or the `Custom' game type
216 configuration? If so, it's part of `game_params'.
218 `game_params' structures are permitted to contain pointers to subsidiary
219 data if they need to. The back end is required to provide functions to
220 create and destroy `game_params', and those functions can allocate and
221 free additional memory if necessary. (It has not yet been necessary to
222 do this in any puzzle so far, but the capability is there just in case.)
224 `game_params' is also the only structure which the game's compute_size()
225 function may refer to; this means that any aspect of the game which
226 affects the size of the window it needs to be drawn in must be stored in
227 `game_params'. In particular, this imposes the fundamental limitation
228 that random game generation may not have a random effect on the window
229 size: game generation algorithms are constrained to work by starting
230 from the grid size rather than generating it as an emergent phenomenon.
231 (Although this is a restriction in theory, it has not yet seemed to be a
237 While the user is actually playing a puzzle, the `game_state' structure
238 stores all the data corresponding to the current state of play.
240 The mid-end keeps `game_state's in a list, and adds to the list every
241 time the player makes a move; the Undo and Redo functions step back and
242 forth through that list.
244 Therefore, a good means of deciding whether a data item needs to go in
245 `game_state' is: would a player expect that data item to be restored on
246 undo? If so, put it in `game_state', and this will automatically happen
247 without you having to lift a finger. If not - for example, the deaths
248 counter in Mines is precisely something that does _not_ want to be reset
249 to its previous state on an undo - then you might have found a data item
250 that needs to go in `game_ui' instead.
252 During play, `game_state's are often passed around without an
253 accompanying `game_params' structure. Therefore, any information in
254 `game_params' which is important during play (such as the grid size)
255 must be duplicated within the `game_state'. One simple method of doing
256 this is to have the `game_state' structure _contain_ a `game_params'
257 structure as one of its members, although this isn't obligatory if you
258 prefer to do it another way.
260 2.1.3. `game_drawstate'
261 -----------------------
263 `game_drawstate' carries persistent state relating to the current
264 graphical contents of the puzzle window. The same `game_drawstate'
265 is passed to every call to the game redraw function, so that it can
266 remember what it has already drawn and what needs redrawing.
268 A typical use for a `game_drawstate' is to have an array mirroring the
269 array of grid squares in the `game_state'; then every time the redraw
270 function was passed a `game_state', it would loop over all the squares,
271 and physically redraw any whose description in the `game_state' (i.e.
272 what the square needs to look like when the redraw is completed) did
273 not match its description in the `game_drawstate' (i.e. what the square
274 currently looks like).
276 `game_drawstate' is occasionally completely torn down and reconstructed
277 by the mid-end, if the user somehow forces a full redraw. Therefore, no
278 data should be stored in `game_drawstate' which is _not_ related to the
279 state of the puzzle window, because it might be unexpectedly destroyed.
281 The back end provides functions to create and destroy `game_drawstate',
282 which means it can contain pointers to subsidiary allocated data if it
283 needs to. A common thing to want to allocate in a `game_drawstate' is a
284 `blitter'; see section 3.1.13 for more on this subject.
289 `game_ui' contains whatever doesn't fit into the above three structures!
291 A new `game_ui' is created when the user begins playing a new instance
292 of a puzzle (i.e. during `New Game' or after entering a game ID etc). It
293 persists until the user finishes playing that game and begins another
294 one (or closes the window); in particular, `Restart Game' does _not_
295 destroy the `game_ui'.
297 `game_ui' is useful for implementing user-interface state which is not
298 part of `game_state'. Common examples are keyboard control (you wouldn't
299 want to have to separately Undo through every cursor motion) and mouse
300 dragging. See section 6.3.2 and section 6.3.3, respectively, for more
303 Another use for `game_ui' is to store highly persistent data such as
304 the Mines death counter. This is conceptually rather different: where
305 the Net cursor position was _not important enough_ to preserve for the
306 player to restore by Undo, the Mines death counter is _too important_ to
307 permit the player to revert by Undo!
309 A final use for `game_ui' is to pass information to the redraw function
310 about recent changes to the game state. This is used in Mines, for
311 example, to indicate whether a requested `flash' should be a white flash
312 for victory or a red flash for defeat; see section 6.3.5.
314 2.2. Simple data in the back end
315 --------------------------------
317 In this section I begin to discuss each individual element in the back
318 end structure. To begin with, here are some simple self-contained data
326 This is a simple ASCII string giving the name of the puzzle. This name
327 will be used in window titles, in game selection menus on monolithic
328 platforms, and anywhere else that the front end needs to know the name
331 2.2.2. `winhelp_topic'
332 ----------------------
334 const char *winhelp_topic;
336 This member is used on Windows only, to provide online help. Although
337 the Windows front end provides a separate binary for each puzzle, it has
338 a single monolithic help file; so when a user selects `Help' from the
339 menu, the program needs to open the help file and jump to the chapter
340 describing that particular puzzle.
342 Therefore, each chapter in `puzzles.but' is labelled with a _help topic_
343 name, similar to this:
345 \cfg{winhelp-topic}{games.net}
347 And then the corresponding game back end encodes the topic string (here
348 `games.net') in the `winhelp_topic' element of the game structure.
350 2.3. Handling game parameter sets
351 ---------------------------------
353 In this section I present the various functions which handle the
354 `game_params' structure.
356 2.3.1. default_params()
357 -----------------------
359 game_params *(*default_params)(void);
361 This function allocates a new `game_params' structure, fills it with the
362 default values, and returns a pointer to it.
364 2.3.2. fetch_preset()
365 ---------------------
367 int (*fetch_preset)(int i, char **name, game_params **params);
369 This function is one of the two APIs a back end can provide to populate
370 the `Type' menu, which provides a list of conveniently accessible preset
371 parameters for most games.
373 The function is called with `i' equal to the index of the preset
374 required (numbering from zero). It returns FALSE if that preset does
375 not exist (if `i' is less than zero or greater than the largest preset
376 index). Otherwise, it sets `*params' to point at a newly allocated
377 `game_params' structure containing the preset information, sets `*name'
378 to point at a newly allocated C string containing the preset title (to
379 go on the `Type' menu), and returns TRUE.
381 If the game does not wish to support any presets at all, this function
382 is permitted to return FALSE always.
384 If the game wants to return presets in the form of a hierarchical menu
385 instead of a flat list (and, indeed, even if it doesn't), then it may
386 set this function pointer to NULL, and instead fill in the alternative
387 function pointer preset_menu (section 2.3.3).
392 struct preset_menu *(*preset_menu)(void);
394 This function is the more flexible of the two APIs by which a back end
395 can define a collection of preset game parameters.
397 This function simply returns a complete menu hierarchy, in the form
398 of a `struct preset_menu' (see section 4.15) and further submenus (if
399 it wishes) dangling off it. There are utility functions described in
400 section 5.2 to make it easy for the back end to construct this menu.
402 If the game has no need to return a hierarchy of menus, it may instead
403 opt to implement the fetch_preset() function (see section 2.3.2).
405 The game need not fill in the `id' fields in the preset menu structures.
406 The mid-end will do that after it receives the structure from the game,
407 and before passing it on to the front end.
409 2.3.4. encode_params()
410 ----------------------
412 char *(*encode_params)(const game_params *params, int full);
414 The job of this function is to take a `game_params', and encode it in
415 a string form for use in game IDs. The return value must be a newly
416 allocated C string, and _must_ not contain a colon or a hash (since
417 those characters are used to mark the end of the parameter section in a
420 Ideally, it should also not contain any other potentially controversial
421 punctuation; bear in mind when designing a string parameter format
422 that it will probably be used on both Windows and Unix command lines
423 under a variety of exciting shell quoting and metacharacter rules.
424 Sticking entirely to alphanumerics is the safest thing; if you really
425 need punctuation, you can probably get away with commas, periods or
426 underscores without causing anybody any major inconvenience. If you
427 venture far beyond that, you're likely to irritate _somebody_.
429 (At the time of writing this, all existing games have purely
430 alphanumeric string parameter formats. Usually these involve a letter
431 denoting a parameter, followed optionally by a number giving the value
432 of that parameter, with a few mandatory parts at the beginning such as
433 numeric width and height separated by `x'.)
435 If the `full' parameter is TRUE, this function should encode absolutely
436 everything in the `game_params', such that a subsequent call to
437 decode_params() (section 2.3.5) will yield an identical structure.
438 If `full' is FALSE, however, you should leave out anything which
439 is not necessary to describe a _specific puzzle instance_, i.e.
440 anything which only takes effect when a new puzzle is _generated_.
441 For example, the Solo `game_params' includes a difficulty rating used
442 when constructing new puzzles; but a Solo game ID need not explicitly
443 include the difficulty, since to describe a puzzle once generated it's
444 sufficient to give the grid dimensions and the location and contents
445 of the clue squares. (Indeed, one might very easily type in a puzzle
446 out of a newspaper without _knowing_ what its difficulty level is in
447 Solo's terminology.) Therefore, Solo's encode_params() only encodes the
448 difficulty level if `full' is set.
450 2.3.5. decode_params()
451 ----------------------
453 void (*decode_params)(game_params *params, char const *string);
455 This function is the inverse of encode_params() (section 2.3.4). It
456 parses the supplied string and fills in the supplied `game_params'
457 structure. Note that the structure will _already_ have been allocated:
458 this function is not expected to create a _new_ `game_params', but to
459 modify an existing one.
461 This function can receive a string which only encodes a subset of the
462 parameters. The most obvious way in which this can happen is if the
463 string was constructed by encode_params() with its `full' parameter set
464 to FALSE; however, it could also happen if the user typed in a parameter
465 set manually and missed something out. Be prepared to deal with a wide
466 range of possibilities.
468 When dealing with a parameter which is not specified in the input
469 string, what to do requires a judgment call on the part of the
470 programmer. Sometimes it makes sense to adjust other parameters to bring
471 them into line with the new ones. In Mines, for example, you would
472 probably not want to keep the same mine count if the user dropped the
473 grid size and didn't specify one, since you might easily end up with
474 more mines than would actually fit in the grid! On the other hand,
475 sometimes it makes sense to leave the parameter alone: a Solo player
476 might reasonably expect to be able to configure size and difficulty
477 independently of one another.
479 This function currently has no direct means of returning an error if the
480 string cannot be parsed at all. However, the returned `game_params' is
481 almost always subsequently passed to validate_params() (section 2.3.11),
482 so if you really want to signal parse errors, you could always have a
483 `char *' in your parameters structure which stored an error message, and
484 have validate_params() return it if it is non-NULL.
489 void (*free_params)(game_params *params);
491 This function frees a `game_params' structure, and any subsidiary
492 allocations contained within it.
497 game_params *(*dup_params)(const game_params *params);
499 This function allocates a new `game_params' structure and initialises it
500 with an exact copy of the information in the one provided as input. It
501 returns a pointer to the new duplicate.
503 2.3.8. `can_configure'
504 ----------------------
508 This boolean data element is set to TRUE if the back end supports
509 custom parameter configuration via a dialog box. If it is TRUE, then
510 the functions configure() and custom_params() are expected to work. See
511 section 2.3.9 and section 2.3.10 for more details.
516 config_item *(*configure)(const game_params *params);
518 This function is called when the user requests a dialog box for
519 custom parameter configuration. It returns a newly allocated array of
520 config_item structures, describing the GUI elements required in the
521 dialog box. The array should have one more element than the number of
522 controls, since it is terminated with a C_END marker (see below). Each
523 array element describes the control together with its initial value; the
524 front end will modify the value fields and return the updated array to
525 custom_params() (see section 2.3.10).
527 The config_item structure contains the following elements:
534 `name' is an ASCII string giving the textual label for a GUI control. It
535 is _not_ expected to be dynamically allocated.
537 `type' contains one of a small number of `enum' values defining what
538 type of control is being described. The meaning of the `sval' and `ival'
539 fields depends on the value in `type'. The valid values are:
543 Describes a text input box. (This is also used for numeric input.
544 The back end does not bother informing the front end that the box is
545 numeric rather than textual; some front ends do have the capacity
546 to take this into account, but I decided it wasn't worth the extra
547 complexity in the interface.) For this type, `ival' is unused, and
548 `sval' contains a dynamically allocated string representing the
549 contents of the input box.
553 Describes a simple checkbox. For this type, `sval' is unused, and
554 `ival' is TRUE or FALSE.
558 Describes a drop-down list presenting one of a small number of
559 fixed choices. For this type, `sval' contains a list of strings
560 describing the choices; the very first character of `sval' is
561 used as a delimiter when processing the rest (so that the strings
562 `:zero:one:two', `!zero!one!two' and `xzeroxonextwo' all define
563 a three-element list containing `zero', `one' and `two'). `ival'
564 contains the index of the currently selected element, numbering from
565 zero (so that in the above example, 0 would mean `zero' and 2 would
568 Note that for this control type, `sval' is _not_ dynamically
569 allocated, whereas it was for `C_STRING'.
573 Marks the end of the array of `config_item's. All other fields are
576 The array returned from this function is expected to have filled in the
577 initial values of all the controls according to the input `game_params'
580 If the game's `can_configure' flag is set to FALSE, this function is
581 never called and need not do anything at all.
583 2.3.10. custom_params()
584 -----------------------
586 game_params *(*custom_params)(const config_item *cfg);
588 This function is the counterpart to configure() (section 2.3.9). It
589 receives as input an array of `config_item's which was originally
590 created by configure(), but in which the control values have since been
591 changed in accordance with user input. Its function is to read the new
592 values out of the controls and return a newly allocated `game_params'
593 structure representing the user's chosen parameter set.
595 (The front end will have modified the controls' _values_, but there will
596 still always be the same set of controls, in the same order, as provided
597 by configure(). It is not necessary to check the `name' and `type'
598 fields, although you could use assert() if you were feeling energetic.)
600 This function is not expected to (and indeed _must not_) free the input
601 `config_item' array. (If the parameters fail to validate, the dialog box
604 If the game's `can_configure' flag is set to FALSE, this function is
605 never called and need not do anything at all.
607 2.3.11. validate_params()
608 -------------------------
610 char *(*validate_params)(const game_params *params, int full);
612 This function takes a `game_params' structure as input, and checks that
613 the parameters described in it fall within sensible limits. (At the very
614 least, grid dimensions should almost certainly be strictly positive, for
617 Return value is NULL if no problems were found, or alternatively a (non-
618 dynamically-allocated) ASCII string describing the error in human-
621 If the `full' parameter is set, full validation should be performed: any
622 set of parameters which would not permit generation of a sensible puzzle
623 should be faulted. If `full' is _not_ set, the implication is that
624 these parameters are not going to be used for _generating_ a puzzle; so
625 parameters which can't even sensibly _describe_ a valid puzzle should
626 still be faulted, but parameters which only affect puzzle generation
629 (The `full' option makes a difference when parameter combinations are
630 non-orthogonal. For example, Net has a boolean option controlling
631 whether it enforces a unique solution; it turns out that it's impossible
632 to generate a uniquely soluble puzzle with wrapping walls and width
633 2, so validate_params() will complain if you ask for one. However,
634 if the user had just been playing a unique wrapping puzzle of a more
635 sensible width, and then pastes in a game ID acquired from somebody else
636 which happens to describe a _non_-unique wrapping width-2 puzzle, then
637 validate_params() will be passed a `game_params' containing the width
638 and wrapping settings from the new game ID and the uniqueness setting
639 from the old one. This would be faulted, if it weren't for the fact that
640 `full' is not set during this call, so Net ignores the inconsistency.
641 The resulting `game_params' is never subsequently used to generate a
642 puzzle; this is a promise made by the mid-end when it asks for a non-
645 2.4. Handling game descriptions
646 -------------------------------
648 In this section I present the functions that deal with a textual
649 description of a puzzle, i.e. the part that comes after the colon in a
650 descriptive-format game ID.
655 char *(*new_desc)(const game_params *params, random_state *rs,
656 char **aux, int interactive);
658 This function is where all the really hard work gets done. This is
659 the function whose job is to randomly generate a new puzzle, ensuring
660 solubility and uniqueness as appropriate.
662 As input it is given a `game_params' structure and a random state
663 (see section 5.1 for the random number API). It must invent a puzzle
664 instance, encode it in string form, and return a dynamically allocated C
665 string containing that encoding.
667 Additionally, it may return a second dynamically allocated string
668 in `*aux'. (If it doesn't want to, then it can leave that parameter
669 completely alone; it isn't required to set it to NULL, although doing
670 so is harmless.) That string, if present, will be passed to solve()
671 (section 2.7.4) later on; so if the puzzle is generated in such a way
672 that a solution is known, then information about that solution can be
673 saved in `*aux' for solve() to use.
675 The `interactive' parameter should be ignored by almost all puzzles.
676 Its purpose is to distinguish between generating a puzzle within a GUI
677 context for immediate play, and generating a puzzle in a command-line
678 context for saving to be played later. The only puzzle that currently
679 uses this distinction (and, I fervently hope, the only one which will
680 _ever_ need to use it) is Mines, which chooses a random first-click
681 location when generating puzzles non-interactively, but which waits
682 for the user to place the first click when interactive. If you think
683 you have come up with another puzzle which needs to make use of this
684 parameter, please think for at least ten minutes about whether there is
687 Note that game description strings are not required to contain an
688 encoding of parameters such as grid size; a game description is
689 never separated from the `game_params' it was generated with, so any
690 information contained in that structure need not be encoded again in the
693 2.4.2. validate_desc()
694 ----------------------
696 char *(*validate_desc)(const game_params *params, const char *desc);
698 This function is given a game description, and its job is to validate
699 that it describes a puzzle which makes sense.
701 To some extent it's up to the user exactly how far they take the phrase
702 `makes sense'; there are no particularly strict rules about how hard the
703 user is permitted to shoot themself in the foot when typing in a bogus
704 game description by hand. (For example, Rectangles will not verify that
705 the sum of all the numbers in the grid equals the grid's area. So a user
706 could enter a puzzle which was provably not soluble, and the program
707 wouldn't complain; there just wouldn't happen to be any sequence of
708 moves which solved it.)
710 The one non-negotiable criterion is that any game description which
711 makes it through validate_desc() _must not_ subsequently cause a crash
712 or an assertion failure when fed to new_game() and thence to the rest of
715 The return value is NULL on success, or a non-dynamically-allocated C
716 string containing an error message.
721 game_state *(*new_game)(midend *me, const game_params *params,
724 This function takes a game description as input, together with its
725 accompanying `game_params', and constructs a `game_state' describing the
726 initial state of the puzzle. It returns a newly allocated `game_state'
729 Almost all puzzles should ignore the `me' parameter. It is required by
730 Mines, which needs it for later passing to midend_supersede_game_desc()
731 (see section 2.11.2) once the user has placed the first click. I
732 fervently hope that no other puzzle will be awkward enough to require
733 it, so everybody else should ignore it. As with the `interactive'
734 parameter in new_desc() (section 2.4.1), if you think you have a reason
735 to need this parameter, please try very hard to think of an alternative
738 2.5. Handling game states
739 -------------------------
741 This section describes the functions which create and destroy
742 `game_state' structures.
744 (Well, except new_game(), which is in section 2.4.3 instead of under
745 here; but it deals with game descriptions _and_ game states and it had
746 to go in one section or the other.)
751 game_state *(*dup_game)(const game_state *state);
753 This function allocates a new `game_state' structure and initialises it
754 with an exact copy of the information in the one provided as input. It
755 returns a pointer to the new duplicate.
760 void (*free_game)(game_state *state);
762 This function frees a `game_state' structure, and any subsidiary
763 allocations contained within it.
765 2.6. Handling `game_ui'
766 -----------------------
771 game_ui *(*new_ui)(const game_state *state);
773 This function allocates and returns a new `game_ui' structure for
774 playing a particular puzzle. It is passed a pointer to the initial
775 `game_state', in case it needs to refer to that when setting up the
776 initial values for the new game.
781 void (*free_ui)(game_ui *ui);
783 This function frees a `game_ui' structure, and any subsidiary
784 allocations contained within it.
789 char *(*encode_ui)(const game_ui *ui);
791 This function encodes any _important_ data in a `game_ui' structure in
792 string form. It is only called when saving a half-finished game to a
795 It should be used sparingly. Almost all data in a `game_ui' is not
796 important enough to save. The location of the keyboard-controlled
797 cursor, for example, can be reset to a default position on reloading
798 the game without impacting the user experience. If the user should
799 somehow manage to save a game while a mouse drag was in progress, then
800 discarding that mouse drag would be an outright _feature_.
802 A typical thing that _would_ be worth encoding in this function is the
803 Mines death counter: it's in the `game_ui' rather than the `game_state'
804 because it's too important to allow the user to revert it by using Undo,
805 and therefore it's also too important to allow the user to revert it by
806 saving and reloading. (Of course, the user could edit the save file by
807 hand... But if the user is _that_ determined to cheat, they could just
808 as easily modify the game's source.)
813 void (*decode_ui)(game_ui *ui, const char *encoding);
815 This function parses a string previously output by encode_ui(), and
816 writes the decoded data back into the provided `game_ui' structure.
818 2.6.5. changed_state()
819 ----------------------
821 void (*changed_state)(game_ui *ui, const game_state *oldstate,
822 const game_state *newstate);
824 This function is called by the mid-end whenever the current game state
825 changes, for any reason. Those reasons include:
827 - a fresh move being made by interpret_move() and execute_move()
829 - a solve operation being performed by solve() and execute_move()
831 - the user moving back and forth along the undo list by means of the
832 Undo and Redo operations
834 - the user selecting Restart to go back to the initial game state.
836 The job of changed_state() is to update the `game_ui' for consistency
837 with the new game state, if any update is necessary. For example,
838 Same Game stores data about the currently selected tile group in its
839 `game_ui', and this data is intrinsically related to the game state it
840 was derived from. So it's very likely to become invalid when the game
841 state changes; thus, Same Game's changed_state() function clears the
842 current selection whenever it is called.
844 When anim_length() or flash_length() are called, you can be sure that
845 there has been a previous call to changed_state(). So changed_state()
846 can set up data in the `game_ui' which will be read by anim_length() and
847 flash_length(), and those functions will not have to worry about being
848 called without the data having been initialised.
853 This section describes the functions which actually make moves in
854 the game: that is, the functions which process user input and end up
855 producing new `game_state's.
857 2.7.1. interpret_move()
858 -----------------------
860 char *(*interpret_move)(const game_state *state, game_ui *ui,
861 const game_drawstate *ds,
862 int x, int y, int button);
864 This function receives user input and processes it. Its input parameters
865 are the current `game_state', the current `game_ui' and the current
866 `game_drawstate', plus details of the input event. `button' is either
867 an ASCII value or a special code (listed below) indicating an arrow or
868 function key or a mouse event; when `button' is a mouse event, `x' and
869 `y' contain the pixel coordinates of the mouse pointer relative to the
870 top left of the puzzle's drawing area.
872 (The pointer to the `game_drawstate' is marked `const', because
873 `interpret_move' should not write to it. The normal use of that pointer
874 will be to read the game's tile size parameter in order to divide mouse
877 interpret_move() may return in three different ways:
879 - Returning NULL indicates that no action whatsoever occurred in
880 response to the input event; the puzzle was not interested in it at
883 - Returning the empty string ("") indicates that the input event has
884 resulted in a change being made to the `game_ui' which will require
885 a redraw of the game window, but that no actual _move_ was made
886 (i.e. no new `game_state' needs to be created).
888 - Returning anything else indicates that a move was made and that
889 a new `game_state' must be created. However, instead of actually
890 constructing a new `game_state' itself, this function is required to
891 return a string description of the details of the move. This string
892 will be passed to execute_move() (section 2.7.2) to actually create
893 the new `game_state'. (Encoding moves as strings in this way means
894 that the mid-end can keep the strings as well as the game states,
895 and the strings can be written to disk when saving the game and fed
896 to execute_move() again on reloading.)
898 The return value from interpret_move() is expected to be dynamically
899 allocated if and only if it is not either NULL _or_ the empty string.
901 After this function is called, the back end is permitted to rely on some
902 subsequent operations happening in sequence:
904 - execute_move() will be called to convert this move description into
907 - changed_state() will be called with the new `game_state'.
909 This means that if interpret_move() needs to do updates to the `game_ui'
910 which are easier to perform by referring to the new `game_state', it can
911 safely leave them to be done in changed_state() and not worry about them
914 (Note, however, that execute_move() may _also_ be called in other
915 circumstances. It is only interpret_move() which can rely on a
916 subsequent call to changed_state().)
918 The special key codes supported by this function are:
920 LEFT_BUTTON, MIDDLE_BUTTON, RIGHT_BUTTON
922 Indicate that one of the mouse buttons was pressed down.
924 LEFT_DRAG, MIDDLE_DRAG, RIGHT_DRAG
926 Indicate that the mouse was moved while one of the mouse buttons was
927 still down. The mid-end guarantees that when one of these events is
928 received, it will always have been preceded by a button-down event
929 (and possibly other drag events) for the same mouse button, and no
930 event involving another mouse button will have appeared in between.
932 LEFT_RELEASE, MIDDLE_RELEASE, RIGHT_RELEASE
934 Indicate that a mouse button was released. The mid-end guarantees
935 that when one of these events is received, it will always have been
936 preceded by a button-down event (and possibly some drag events) for
937 the same mouse button, and no event involving another mouse button
938 will have appeared in between.
940 CURSOR_UP, CURSOR_DOWN, CURSOR_LEFT, CURSOR_RIGHT
942 Indicate that an arrow key was pressed.
946 On platforms which have a prominent `select' button alongside their
947 cursor keys, indicates that that button was pressed.
949 In addition, there are some modifiers which can be bitwise-ORed into the
954 These indicate that the Control or Shift key was pressed alongside
955 the key. They only apply to the cursor keys, not to mouse buttons or
960 This applies to some ASCII values, and indicates that the key code
961 was input via the numeric keypad rather than the main keyboard. Some
962 puzzles may wish to treat this differently (for example, a puzzle
963 might want to use the numeric keypad as an eight-way directional
964 pad), whereas others might not (a game involving numeric input
965 probably just wants to treat the numeric keypad as numbers).
969 This mask is the bitwise OR of all the available modifiers; you can
970 bitwise-AND with ~MOD_MASK to strip all the modifiers off any input
973 2.7.2. execute_move()
974 ---------------------
976 game_state *(*execute_move)(const game_state *state, char *move);
978 This function takes an input `game_state' and a move string as output
979 from interpret_move(). It returns a newly allocated `game_state' which
980 contains the result of applying the specified move to the input game
983 This function may return NULL if it cannot parse the move string (and
984 this is definitely preferable to crashing or failing an assertion, since
985 one way this can happen is if loading a corrupt save file). However, it
986 must not return NULL for any move string that really was output from
987 interpret_move(): this is punishable by assertion failure in the mid-
995 This boolean field is set to TRUE if the game's solve() function does
996 something. If it's set to FALSE, the game will not even offer the
1002 char *(*solve)(const game_state *orig, const game_state *curr,
1003 const char *aux, char **error);
1005 This function is called when the user selects the `Solve' option from
1008 It is passed two input game states: `orig' is the game state from the
1009 very start of the puzzle, and `curr' is the current one. (Different
1010 games find one or other or both of these convenient.) It is also passed
1011 the `aux' string saved by new_desc() (section 2.4.1), in case that
1012 encodes important information needed to provide the solution.
1014 If this function is unable to produce a solution (perhaps, for example,
1015 the game has no in-built solver so it can only solve puzzles it invented
1016 internally and has an `aux' string for) then it may return NULL. If it
1017 does this, it must also set `*error' to an error message to be presented
1018 to the user (such as `Solution not known for this puzzle'); that error
1019 message is not expected to be dynamically allocated.
1021 If this function _does_ produce a solution, it returns a move string
1022 suitable for feeding to execute_move() (section 2.7.2). Like a (non-
1023 empty) string returned from interpret_move(), the returned string should
1024 be dynamically allocated.
1026 2.8. Drawing the game graphics
1027 ------------------------------
1029 This section discusses the back end functions that deal with drawing.
1031 2.8.1. new_drawstate()
1032 ----------------------
1034 game_drawstate *(*new_drawstate)(drawing *dr,
1035 const game_state *state);
1037 This function allocates and returns a new `game_drawstate' structure for
1038 drawing a particular puzzle. It is passed a pointer to a `game_state',
1039 in case it needs to refer to that when setting up any initial data.
1041 This function may not rely on the puzzle having been newly started; a
1042 new draw state can be constructed at any time if the front end requests
1043 a forced redraw. For games like Pattern, in which initial game states
1044 are much simpler than general ones, this might be important to keep in
1047 The parameter `dr' is a drawing object (see chapter 3) which the
1048 function might need to use to allocate blitters. (However, this isn't
1049 recommended; it's usually more sensible to wait to allocate a blitter
1050 until set_size() is called, because that way you can tailor it to the
1051 scale at which the puzzle is being drawn.)
1053 2.8.2. free_drawstate()
1054 -----------------------
1056 void (*free_drawstate)(drawing *dr, game_drawstate *ds);
1058 This function frees a `game_drawstate' structure, and any subsidiary
1059 allocations contained within it.
1061 The parameter `dr' is a drawing object (see chapter 3), which might be
1062 required if you are freeing a blitter.
1064 2.8.3. `preferred_tilesize'
1065 ---------------------------
1067 int preferred_tilesize;
1069 Each game is required to define a single integer parameter which
1070 expresses, in some sense, the scale at which it is drawn. This is
1071 described in the APIs as `tilesize', since most puzzles are on a
1072 square (or possibly triangular or hexagonal) grid and hence a sensible
1073 interpretation of this parameter is to define it as the size of one grid
1074 tile in pixels; however, there's no actual requirement that the `tile
1075 size' be proportional to the game window size. Window size is required
1076 to increase monotonically with `tile size', however.
1078 The data element `preferred_tilesize' indicates the tile size which
1079 should be used in the absence of a good reason to do otherwise (such as
1080 the screen being too small, or the user explicitly requesting a resize
1081 if that ever gets implemented).
1083 2.8.4. compute_size()
1084 ---------------------
1086 void (*compute_size)(const game_params *params, int tilesize,
1089 This function is passed a `game_params' structure and a tile size. It
1090 returns, in `*x' and `*y', the size in pixels of the drawing area that
1091 would be required to render a puzzle with those parameters at that tile
1097 void (*set_size)(drawing *dr, game_drawstate *ds,
1098 const game_params *params, int tilesize);
1100 This function is responsible for setting up a `game_drawstate' to draw
1101 at a given tile size. Typically this will simply involve copying the
1102 supplied `tilesize' parameter into a `tilesize' field inside the draw
1103 state; for some more complex games it might also involve setting up
1104 other dimension fields, or possibly allocating a blitter (see section
1107 The parameter `dr' is a drawing object (see chapter 3), which is
1108 required if a blitter needs to be allocated.
1110 Back ends may assume (and may enforce by assertion) that this function
1111 will be called at most once for any `game_drawstate'. If a puzzle needs
1112 to be redrawn at a different size, the mid-end will create a fresh
1118 float *(*colours)(frontend *fe, int *ncolours);
1120 This function is responsible for telling the front end what colours the
1121 puzzle will need to draw itself.
1123 It returns the number of colours required in `*ncolours', and the return
1124 value from the function itself is a dynamically allocated array of three
1125 times that many `float's, containing the red, green and blue components
1126 of each colour respectively as numbers in the range [0,1].
1128 The second parameter passed to this function is a front end handle.
1129 The only things it is permitted to do with this handle are to call the
1130 front-end function called frontend_default_colour() (see section 4.39)
1131 or the utility function called game_mkhighlight() (see section 5.5.7).
1132 (The latter is a wrapper on the former, so front end implementors only
1133 need to provide frontend_default_colour().) This allows colours() to
1134 take local configuration into account when deciding on its own colour
1135 allocations. Most games use the front end's default colour as their
1136 background, apart from a few which depend on drawing relief highlights
1137 so they adjust the background colour if it's too light for highlights to
1140 Note that the colours returned from this function are for _drawing_,
1141 not for printing. Printing has an entirely different colour allocation
1144 2.8.7. anim_length()
1145 --------------------
1147 float (*anim_length)(const game_state *oldstate,
1148 const game_state *newstate,
1149 int dir, game_ui *ui);
1151 This function is called when a move is made, undone or redone. It is
1152 given the old and the new `game_state', and its job is to decide whether
1153 the transition between the two needs to be animated or can be instant.
1155 `oldstate' is the state that was current until this call; `newstate'
1156 is the state that will be current after it. `dir' specifies the
1157 chronological order of those states: if it is positive, then the
1158 transition is the result of a move or a redo (and so `newstate' is the
1159 later of the two moves), whereas if it is negative then the transition
1160 is the result of an undo (so that `newstate' is the _earlier_ move).
1162 If this function decides the transition should be animated, it returns
1163 the desired length of the animation in seconds. If not, it returns zero.
1165 State changes as a result of a Restart operation are never animated; the
1166 mid-end will handle them internally and never consult this function at
1167 all. State changes as a result of Solve operations are also not animated
1168 by default, although you can change this for a particular game by
1169 setting a flag in `flags' (section 2.10.7).
1171 The function is also passed a pointer to the local `game_ui'. It may
1172 refer to information in here to help with its decision (see section
1173 6.3.7 for an example of this), and/or it may _write_ information about
1174 the nature of the animation which will be read later by redraw().
1176 When this function is called, it may rely on changed_state() having been
1177 called previously, so if anim_length() needs to refer to information in
1178 the `game_ui', then changed_state() is a reliable place to have set that
1181 Move animations do not inhibit further input events. If the user
1182 continues playing before a move animation is complete, the animation
1183 will be abandoned and the display will jump straight to the final state.
1185 2.8.8. flash_length()
1186 ---------------------
1188 float (*flash_length)(const game_state *oldstate,
1189 const game_state *newstate,
1190 int dir, game_ui *ui);
1192 This function is called when a move is completed. (`Completed'
1193 means that not only has the move been made, but any animation which
1194 accompanied it has finished.) It decides whether the transition from
1195 `oldstate' to `newstate' merits a `flash'.
1197 A flash is much like a move animation, but it is _not_ interrupted by
1198 further user interface activity; it runs to completion in parallel with
1199 whatever else might be going on on the display. The only thing which
1200 will rush a flash to completion is another flash.
1202 The purpose of flashes is to indicate that the game has been completed.
1203 They were introduced as a separate concept from move animations because
1204 of Net: the habit of most Net players (and certainly me) is to rotate a
1205 tile into place and immediately lock it, then move on to another tile.
1206 When you make your last move, at the instant the final tile is rotated
1207 into place the screen starts to flash to indicate victory - but if you
1208 then press the lock button out of habit, then the move animation is
1209 cancelled, and the victory flash does not complete. (And if you _don't_
1210 press the lock button, the completed grid will look untidy because there
1211 will be one unlocked square.) Therefore, I introduced a specific concept
1212 of a `flash' which is separate from a move animation and can proceed in
1213 parallel with move animations and any other display activity, so that
1214 the victory flash in Net is not cancelled by that final locking move.
1216 The input parameters to flash_length() are exactly the same as the ones
1219 Just like anim_length(), when this function is called, it may rely on
1220 changed_state() having been called previously, so if it needs to refer
1221 to information in the `game_ui' then changed_state() is a reliable place
1222 to have set that information up.
1224 (Some games use flashes to indicate defeat as well as victory; Mines,
1225 for example, flashes in a different colour when you tread on a mine from
1226 the colour it uses when you complete the game. In order to achieve this,
1227 its flash_length() function has to store a flag in the `game_ui' to
1228 indicate which flash type is required.)
1233 int (*status)(const game_state *state);
1235 This function returns a status value indicating whether the current game
1236 is still in play, or has been won, or has been conclusively lost. The
1237 mid-end uses this to implement midend_status() (section 4.26).
1239 The return value should be +1 if the game has been successfully solved.
1240 If the game has been lost in a situation where further play is unlikely,
1241 the return value should be -1. If neither is true (so play is still
1242 ongoing), return zero.
1244 Front ends may wish to use a non-zero status as a cue to proactively
1245 offer the option of starting a new game. Therefore, back ends should
1246 not return -1 if the game has been _technically_ lost but undoing and
1247 continuing is still a realistic possibility.
1249 (For instance, games with hidden information such as Guess or Mines
1250 might well return a non-zero status whenever they reveal the solution,
1251 whether or not the player guessed it correctly, on the grounds that a
1252 player would be unlikely to hide the solution and continue playing after
1253 the answer was spoiled. On the other hand, games where you can merely
1254 get into a dead end such as Same Game or Inertia might choose to return
1255 0 in that situation, on the grounds that the player would quite likely
1256 press Undo and carry on playing.)
1261 void (*redraw)(drawing *dr, game_drawstate *ds,
1262 const game_state *oldstate,
1263 const game_state *newstate,
1264 int dir, const game_ui *ui,
1265 float anim_time, float flash_time);
1267 This function is responsible for actually drawing the contents of
1268 the game window, and for redrawing every time the game state or the
1271 The parameter `dr' is a drawing object which may be passed to the
1272 drawing API functions (see chapter 3 for documentation of the drawing
1273 API). This function may not save `dr' and use it elsewhere; it must only
1274 use it for calling back to the drawing API functions within its own
1277 `ds' is the local `game_drawstate', of course, and `ui' is the local
1280 `newstate' is the semantically-current game state, and is always non-
1281 NULL. If `oldstate' is also non-NULL, it means that a move has recently
1282 been made and the game is still in the process of displaying an
1283 animation linking the old and new states; in this situation, `anim_time'
1284 will give the length of time (in seconds) that the animation has already
1285 been running. If `oldstate' is NULL, then `anim_time' is unused (and
1286 will hopefully be set to zero to avoid confusion).
1288 `flash_time', if it is is non-zero, denotes that the game is in the
1289 middle of a flash, and gives the time since the start of the flash. See
1290 section 2.8.8 for general discussion of flashes.
1292 The very first time this function is called for a new `game_drawstate',
1293 it is expected to redraw the _entire_ drawing area. Since this often
1294 involves drawing visual furniture which is never subsequently altered,
1295 it is often simplest to arrange this by having a special `first time'
1296 flag in the draw state, and resetting it after the first redraw.
1298 When this function (or any subfunction) calls the drawing API, it is
1299 expected to pass colour indices which were previously defined by the
1302 2.9. Printing functions
1303 -----------------------
1305 This section discusses the back end functions that deal with printing
1306 puzzles out on paper.
1313 This flag is set to TRUE if the puzzle is capable of printing itself
1314 on paper. (This makes sense for some puzzles, such as Solo, which can
1315 be filled in with a pencil. Other puzzles, such as Twiddle, inherently
1316 involve moving things around and so would not make sense to print.)
1318 If this flag is FALSE, then the functions print_size() and print() will
1321 2.9.2. `can_print_in_colour'
1322 ----------------------------
1324 int can_print_in_colour;
1326 This flag is set to TRUE if the puzzle is capable of printing itself
1327 differently when colour is available. For example, Map can actually
1328 print coloured regions in different _colours_ rather than resorting to
1331 If the `can_print' flag is FALSE, then this flag will be ignored.
1336 void (*print_size)(const game_params *params, float *x, float *y);
1338 This function is passed a `game_params' structure and a tile size. It
1339 returns, in `*x' and `*y', the preferred size in _millimetres_ of that
1340 puzzle if it were to be printed out on paper.
1342 If the `can_print' flag is FALSE, this function will never be called.
1347 void (*print)(drawing *dr, const game_state *state, int tilesize);
1349 This function is called when a puzzle is to be printed out on paper. It
1350 should use the drawing API functions (see chapter 3) to print itself.
1352 This function is separate from redraw() because it is often very
1355 - The printing function may not depend on pixel accuracy, since
1356 printer resolution is variable. Draw as if your canvas had infinite
1359 - The printing function sometimes needs to display things in a
1360 completely different style. Net, for example, is very different as
1361 an on-screen puzzle and as a printed one.
1363 - The printing function is often much simpler since it has no need to
1364 deal with repeated partial redraws.
1366 However, there's no reason the printing and redraw functions can't share
1367 some code if they want to.
1369 When this function (or any subfunction) calls the drawing API, the
1370 colour indices it passes should be colours which have been allocated by
1371 the print_*_colour() functions within this execution of print(). This is
1372 very different from the fixed small number of colours used in redraw(),
1373 because printers do not have a limitation on the total number of colours
1374 that may be used. Some puzzles' printing functions might wish to
1375 allocate only one `ink' colour and use it for all drawing; others might
1376 wish to allocate _more_ colours than are used on screen.
1378 One possible colour policy worth mentioning specifically is that a
1379 puzzle's printing function might want to allocate the _same_ colour
1380 indices as are used by the redraw function, so that code shared between
1381 drawing and printing does not have to keep switching its colour indices.
1382 In order to do this, the simplest thing is to make use of the fact that
1383 colour indices returned from print_*_colour() are guaranteed to be in
1384 increasing order from zero. So if you have declared an `enum' defining
1385 three colours COL_BACKGROUND, COL_THIS and COL_THAT, you might then
1389 c = print_mono_colour(dr, 1); assert(c == COL_BACKGROUND);
1390 c = print_mono_colour(dr, 0); assert(c == COL_THIS);
1391 c = print_mono_colour(dr, 0); assert(c == COL_THAT);
1393 If the `can_print' flag is FALSE, this function will never be called.
1398 2.10.1. `can_format_as_text_ever'
1399 ---------------------------------
1401 int can_format_as_text_ever;
1403 This boolean field is TRUE if the game supports formatting a game state
1404 as ASCII text (typically ASCII art) for copying to the clipboard and
1405 pasting into other applications. If it is FALSE, front ends will not
1406 offer the `Copy' command at all.
1408 If this field is TRUE, the game does not necessarily have to support
1409 text formatting for _all_ games: e.g. a game which can be played on
1410 a square grid or a triangular one might only support copy and paste
1411 for the former, because triangular grids in ASCII art are just too
1414 If this field is FALSE, the functions can_format_as_text_now() (section
1415 2.10.2) and text_format() (section 2.10.3) are never called.
1417 2.10.2. `can_format_as_text_now()'
1418 ----------------------------------
1420 int (*can_format_as_text_now)(const game_params *params);
1422 This function is passed a `game_params' and returns a boolean, which is
1423 TRUE if the game can support ASCII text output for this particular game
1424 type. If it returns FALSE, front ends will grey out or otherwise disable
1427 Games may enable and disable the copy-and-paste function for different
1428 game _parameters_, but are currently constrained to return the same
1429 answer from this function for all game _states_ sharing the same
1430 parameters. In other words, the `Copy' function may enable or disable
1431 itself when the player changes game preset, but will never change during
1432 play of a single game or when another game of exactly the same type is
1435 This function should not take into account aspects of the game
1436 parameters which are not encoded by encode_params() (section 2.3.4)
1437 when the `full' parameter is set to FALSE. Such parameters will not
1438 necessarily match up between a call to this function and a subsequent
1439 call to text_format() itself. (For instance, game _difficulty_ should
1440 not affect whether the game can be copied to the clipboard. Only the
1441 actual visible _shape_ of the game can affect that.)
1443 2.10.3. text_format()
1444 ---------------------
1446 char *(*text_format)(const game_state *state);
1448 This function is passed a `game_state', and returns a newly allocated C
1449 string containing an ASCII representation of that game state. It is used
1450 to implement the `Copy' operation in many front ends.
1452 This function will only ever be called if the back end field
1453 `can_format_as_text_ever' (section 2.10.1) is TRUE _and_ the function
1454 can_format_as_text_now() (section 2.10.2) has returned TRUE for the
1455 currently selected game parameters.
1457 The returned string may contain line endings (and will probably want
1458 to), using the normal C internal `\n' convention. For consistency
1459 between puzzles, all multi-line textual puzzle representations should
1460 _end_ with a newline as well as containing them internally. (There are
1461 currently no puzzles which have a one-line ASCII representation, so
1462 there's no precedent yet for whether that should come with a newline or
1465 2.10.4. wants_statusbar
1466 -----------------------
1468 int wants_statusbar;
1470 This boolean field is set to TRUE if the puzzle has a use for a textual
1471 status line (to display score, completion status, currently active
1479 This boolean field is TRUE if the puzzle is time-critical. If so, the
1480 mid-end will maintain a game timer while the user plays.
1482 If this field is FALSE, then timing_state() will never be called and
1483 need not do anything.
1485 2.10.6. timing_state()
1486 ----------------------
1488 int (*timing_state)(const game_state *state, game_ui *ui);
1490 This function is passed the current `game_state' and the local
1491 `game_ui'; it returns TRUE if the game timer should currently be
1494 A typical use for the `game_ui' in this function is to note when the
1495 game was first completed (by setting a flag in changed_state() - see
1496 section 2.6.5), and freeze the timer thereafter so that the user can
1497 undo back through their solution process without altering their time.
1504 This field contains miscellaneous per-backend flags. It consists of the
1505 bitwise OR of some combination of the following:
1509 Given any x and y from the set {LEFT_BUTTON, MIDDLE_BUTTON,
1510 RIGHT_BUTTON}, this macro evaluates to a bit flag which indicates
1511 that when buttons x and y are both pressed simultaneously, the mid-
1512 end should consider x to have priority. (In the absence of any such
1513 flags, the mid-end will always consider the most recently pressed
1514 button to have priority.)
1518 This flag indicates that moves generated by solve() (section 2.7.4)
1519 are candidates for animation just like any other move. For most
1520 games, solve moves should not be animated, so the mid-end doesn't
1521 even bother calling anim_length() (section 2.8.7), thus saving some
1522 special-case code in each game. On the rare occasion that animated
1523 solve moves are actually required, you can set this flag.
1527 This flag indicates that the puzzle cannot be usefully played
1528 without the use of mouse buttons other than the left one. On some
1529 PDA platforms, this flag is used by the front end to enable right-
1530 button emulation through an appropriate gesture. Note that a puzzle
1531 is not required to set this just because it _uses_ the right button,
1532 but only if its use of the right button is critical to playing the
1533 game. (Slant, for example, uses the right button to cycle through
1534 the three square states in the opposite order from the left button,
1535 and hence can manage fine without it.)
1539 This flag indicates that the puzzle cannot be usefully played
1540 without the use of number-key input. On some PDA platforms it
1541 causes an emulated number pad to appear on the screen. Similarly to
1542 REQUIRE_RBUTTON, a puzzle need not specify this simply if its use of
1543 the number keys is not critical.
1545 2.11. Things a back end may do on its own initiative
1546 ----------------------------------------------------
1548 This section describes a couple of things that a back end may choose
1549 to do by calling functions elsewhere in the program, which would not
1550 otherwise be obvious.
1552 2.11.1. Create a random state
1553 -----------------------------
1555 If a back end needs random numbers at some point during normal play, it
1556 can create a fresh `random_state' by first calling `get_random_seed'
1557 (section 4.35) and then passing the returned seed data to random_new().
1559 This is likely not to be what you want. If a puzzle needs randomness in
1560 the middle of play, it's likely to be more sensible to store some sort
1561 of random state within the `game_state', so that the random numbers are
1562 tied to the particular game state and hence the player can't simply keep
1563 undoing their move until they get numbers they like better.
1565 This facility is currently used only in Net, to implement the `jumble'
1566 command, which sets every unlocked tile to a new random orientation.
1567 This randomness _is_ a reasonable use of the feature, because it's non-
1568 adversarial - there's no advantage to the user in getting different
1571 2.11.2. Supersede its own game description
1572 ------------------------------------------
1574 In response to a move, a back end is (reluctantly) permitted to call
1575 midend_supersede_game_desc():
1577 void midend_supersede_game_desc(midend *me,
1578 char *desc, char *privdesc);
1580 When the user selects `New Game', the mid-end calls new_desc()
1581 (section 2.4.1) to get a new game description, and (as well as using
1582 that to generate an initial game state) stores it for the save file
1583 and for telling to the user. The function above overwrites that
1584 game description, and also splits it in two. `desc' becomes the new
1585 game description which is provided to the user on request, and is
1586 also the one used to construct a new initial game state if the user
1587 selects `Restart'. `privdesc' is a `private' game description, used to
1588 reconstruct the game's initial state when reloading.
1590 The distinction between the two, as well as the need for this function
1591 at all, comes from Mines. Mines begins with a blank grid and no
1592 idea of where the mines actually are; new_desc() does almost no
1593 work in interactive mode, and simply returns a string encoding the
1594 `random_state'. When the user first clicks to open a tile, _then_ Mines
1595 generates the mine positions, in such a way that the game is soluble
1596 from that starting point. Then it uses this function to supersede the
1597 random-state game description with a proper one. But it needs two: one
1598 containing the initial click location (because that's what you want to
1599 happen if you restart the game, and also what you want to send to a
1600 friend so that they play _the same game_ as you), and one without the
1601 initial click location (because when you save and reload the game, you
1602 expect to see the same blank initial state as you had before saving).
1604 I should stress again that this function is a horrid hack. Nobody should
1605 use it if they're not Mines; if you think you need to use it, think
1606 again repeatedly in the hope of finding a better way to do whatever it
1607 was you needed to do.
1612 The back end function redraw() (section 2.8.10) is required to draw
1613 the puzzle's graphics on the window's drawing area, or on paper if the
1614 puzzle is printable. To do this portably, it is provided with a drawing
1615 API allowing it to talk directly to the front end. In this chapter I
1616 document that API, both for the benefit of back end authors trying to
1617 use it and for front end authors trying to implement it.
1619 The drawing API as seen by the back end is a collection of global
1620 functions, each of which takes a pointer to a `drawing' structure (a
1621 `drawing object'). These objects are supplied as parameters to the back
1622 end's redraw() and print() functions.
1624 In fact these global functions are not implemented directly by the front
1625 end; instead, they are implemented centrally in `drawing.c' and form a
1626 small piece of middleware. The drawing API as supplied by the front end
1627 is a structure containing a set of function pointers, plus a `void *'
1628 handle which is passed to each of those functions. This enables a single
1629 front end to switch between multiple implementations of the drawing API
1630 if necessary. For example, the Windows API supplies a printing mechanism
1631 integrated into the same GDI which deals with drawing in windows, and
1632 therefore the same API implementation can handle both drawing and
1633 printing; but on Unix, the most common way for applications to print
1634 is by producing PostScript output directly, and although it would be
1635 _possible_ to write a single (say) draw_rect() function which checked
1636 a global flag to decide whether to do GTK drawing operations or output
1637 PostScript to a file, it's much nicer to have two separate functions and
1638 switch between them as appropriate.
1640 When drawing, the puzzle window is indexed by pixel coordinates, with
1641 the top left pixel defined as (0,0) and the bottom right pixel (w-1,h-
1642 1), where `w' and `h' are the width and height values returned by the
1643 back end function compute_size() (section 2.8.4).
1645 When printing, the puzzle's print area is indexed in exactly the same
1646 way (with an arbitrary tile size provided by the printing module
1647 `printing.c'), to facilitate sharing of code between the drawing and
1648 printing routines. However, when printing, puzzles may no longer assume
1649 that the coordinate unit has any relationship to a pixel; the printer's
1650 actual resolution might very well not even be known at print time, so
1651 the coordinate unit might be smaller or larger than a pixel. Puzzles'
1652 print functions should restrict themselves to drawing geometric shapes
1653 rather than fiddly pixel manipulation.
1655 _Puzzles' redraw functions may assume that the surface they draw on is
1656 persistent_. It is the responsibility of every front end to preserve
1657 the puzzle's window contents in the face of GUI window expose issues
1658 and similar. It is not permissible to request that the back end redraw
1659 any part of a window that it has already drawn, unless something has
1660 actually changed as a result of making moves in the puzzle.
1662 Most front ends accomplish this by having the drawing routines draw on a
1663 stored bitmap rather than directly on the window, and copying the bitmap
1664 to the window every time a part of the window needs to be redrawn.
1665 Therefore, it is vitally important that whenever the back end does any
1666 drawing it informs the front end of which parts of the window it has
1667 accessed, and hence which parts need repainting. This is done by calling
1668 draw_update() (section 3.1.11).
1670 Persistence of old drawing is convenient. However, a puzzle should be
1671 very careful about how it updates its drawing area. The problem is that
1672 some front ends do anti-aliased drawing: rather than simply choosing
1673 between leaving each pixel untouched or painting it a specified colour,
1674 an antialiased drawing function will _blend_ the original and new
1675 colours in pixels at a figure's boundary according to the proportion of
1676 the pixel occupied by the figure (probably modified by some heuristic
1677 fudge factors). All of this produces a smoother appearance for curves
1680 An unfortunate effect of drawing an anti-aliased figure repeatedly
1681 is that the pixels around the figure's boundary come steadily more
1682 saturated with `ink' and the boundary appears to `spread out'. Worse,
1683 redrawing a figure in a different colour won't fully paint over the old
1684 boundary pixels, so the end result is a rather ugly smudge.
1686 A good strategy to avoid unpleasant anti-aliasing artifacts is to
1687 identify a number of rectangular areas which need to be redrawn, clear
1688 them to the background colour, and then redraw their contents from
1689 scratch, being careful all the while not to stray beyond the boundaries
1690 of the original rectangles. The clip() function (section 3.1.9) comes in
1691 very handy here. Games based on a square grid can often do this fairly
1692 easily. Other games may need to be somewhat more careful. For example,
1693 Loopy's redraw function first identifies portions of the display which
1694 need to be updated. Then, if the changes are fairly well localised, it
1695 clears and redraws a rectangle containing each changed area. Otherwise,
1696 it gives up and redraws the entire grid from scratch.
1698 It is possible to avoid clearing to background and redrawing from
1699 scratch if one is very careful about which drawing functions one
1700 uses: if a function is documented as not anti-aliasing under some
1701 circumstances, you can rely on each pixel in a drawing either being left
1702 entirely alone or being set to the requested colour, with no blending
1705 In the following sections I first discuss the drawing API as seen by the
1706 back end, and then the _almost_ identical function-pointer form seen by
1709 3.1. Drawing API as seen by the back end
1710 ----------------------------------------
1712 This section documents the back-end drawing API, in the form of
1713 functions which take a `drawing' object as an argument.
1718 void draw_rect(drawing *dr, int x, int y, int w, int h,
1721 Draws a filled rectangle in the puzzle window.
1723 `x' and `y' give the coordinates of the top left pixel of the rectangle.
1724 `w' and `h' give its width and height. Thus, the horizontal extent of
1725 the rectangle runs from `x' to `x+w-1' inclusive, and the vertical
1726 extent from `y' to `y+h-1' inclusive.
1728 `colour' is an integer index into the colours array returned by the back
1729 end function colours() (section 2.8.6).
1731 There is no separate pixel-plotting function. If you want to plot a
1732 single pixel, the approved method is to use draw_rect() with width and
1735 Unlike many of the other drawing functions, this function is guaranteed
1736 to be pixel-perfect: the rectangle will be sharply defined and not anti-
1737 aliased or anything like that.
1739 This function may be used for both drawing and printing.
1741 3.1.2. draw_rect_outline()
1742 --------------------------
1744 void draw_rect_outline(drawing *dr, int x, int y, int w, int h,
1747 Draws an outline rectangle in the puzzle window.
1749 `x' and `y' give the coordinates of the top left pixel of the rectangle.
1750 `w' and `h' give its width and height. Thus, the horizontal extent of
1751 the rectangle runs from `x' to `x+w-1' inclusive, and the vertical
1752 extent from `y' to `y+h-1' inclusive.
1754 `colour' is an integer index into the colours array returned by the back
1755 end function colours() (section 2.8.6).
1757 From a back end perspective, this function may be considered to be part
1758 of the drawing API. However, front ends are not required to implement
1759 it, since it is actually implemented centrally (in misc.c) as a wrapper
1762 This function may be used for both drawing and printing.
1767 void draw_line(drawing *dr, int x1, int y1, int x2, int y2,
1770 Draws a straight line in the puzzle window.
1772 `x1' and `y1' give the coordinates of one end of the line. `x2' and `y2'
1773 give the coordinates of the other end. The line drawn includes both
1776 `colour' is an integer index into the colours array returned by the back
1777 end function colours() (section 2.8.6).
1779 Some platforms may perform anti-aliasing on this function. Therefore,
1780 do not assume that you can erase a line by drawing the same line over
1781 it in the background colour; anti-aliasing might lead to perceptible
1782 ghost artefacts around the vanished line. Horizontal and vertical lines,
1783 however, are pixel-perfect and not anti-aliased.
1785 This function may be used for both drawing and printing.
1787 3.1.4. draw_polygon()
1788 ---------------------
1790 void draw_polygon(drawing *dr, int *coords, int npoints,
1791 int fillcolour, int outlinecolour);
1793 Draws an outlined or filled polygon in the puzzle window.
1795 `coords' is an array of (2*npoints) integers, containing the `x' and `y'
1796 coordinates of `npoints' vertices.
1798 `fillcolour' and `outlinecolour' are integer indices into the colours
1799 array returned by the back end function colours() (section 2.8.6).
1800 `fillcolour' may also be -1 to indicate that the polygon should be
1803 The polygon defined by the specified list of vertices is first filled in
1804 `fillcolour', if specified, and then outlined in `outlinecolour'.
1806 `outlinecolour' may _not_ be -1; it must be a valid colour (and front
1807 ends are permitted to enforce this by assertion). This is because
1808 different platforms disagree on whether a filled polygon should include
1809 its boundary line or not, so drawing _only_ a filled polygon would
1810 have non-portable effects. If you want your filled polygon not to
1811 have a visible outline, you must set `outlinecolour' to the same as
1814 Some platforms may perform anti-aliasing on this function. Therefore, do
1815 not assume that you can erase a polygon by drawing the same polygon over
1816 it in the background colour. Also, be prepared for the polygon to extend
1817 a pixel beyond its obvious bounding box as a result of this; if you
1818 really need it not to do this to avoid interfering with other delicate
1819 graphics, you should probably use clip() (section 3.1.9). You can rely
1820 on horizontal and vertical lines not being anti-aliased.
1822 This function may be used for both drawing and printing.
1824 3.1.5. draw_circle()
1825 --------------------
1827 void draw_circle(drawing *dr, int cx, int cy, int radius,
1828 int fillcolour, int outlinecolour);
1830 Draws an outlined or filled circle in the puzzle window.
1832 `cx' and `cy' give the coordinates of the centre of the circle. `radius'
1833 gives its radius. The total horizontal pixel extent of the circle is
1834 from `cx-radius+1' to `cx+radius-1' inclusive, and the vertical extent
1835 similarly around `cy'.
1837 `fillcolour' and `outlinecolour' are integer indices into the colours
1838 array returned by the back end function colours() (section 2.8.6).
1839 `fillcolour' may also be -1 to indicate that the circle should be
1842 The circle is first filled in `fillcolour', if specified, and then
1843 outlined in `outlinecolour'.
1845 `outlinecolour' may _not_ be -1; it must be a valid colour (and front
1846 ends are permitted to enforce this by assertion). This is because
1847 different platforms disagree on whether a filled circle should include
1848 its boundary line or not, so drawing _only_ a filled circle would
1849 have non-portable effects. If you want your filled circle not to
1850 have a visible outline, you must set `outlinecolour' to the same as
1853 Some platforms may perform anti-aliasing on this function. Therefore, do
1854 not assume that you can erase a circle by drawing the same circle over
1855 it in the background colour. Also, be prepared for the circle to extend
1856 a pixel beyond its obvious bounding box as a result of this; if you
1857 really need it not to do this to avoid interfering with other delicate
1858 graphics, you should probably use clip() (section 3.1.9).
1860 This function may be used for both drawing and printing.
1862 3.1.6. draw_thick_line()
1863 ------------------------
1865 void draw_thick_line(drawing *dr, float thickness,
1866 float x1, float y1, float x2, float y2,
1869 Draws a line in the puzzle window, giving control over the line's
1872 `x1' and `y1' give the coordinates of one end of the line. `x2' and `y2'
1873 give the coordinates of the other end. `thickness' gives the thickness
1874 of the line, in pixels.
1876 Note that the coordinates and thickness are floating-point: the
1877 continuous coordinate system is in effect here. It's important to be
1878 able to address points with better-than-pixel precision in this case,
1879 because one can't otherwise properly express the endpoints of lines with
1880 both odd and even thicknesses.
1882 Some platforms may perform anti-aliasing on this function. The precise
1883 pixels affected by a thick-line drawing operation may vary between
1884 platforms, and no particular guarantees are provided. Indeed, even
1885 horizontal or vertical lines may be anti-aliased.
1887 This function may be used for both drawing and printing.
1892 void draw_text(drawing *dr, int x, int y, int fonttype,
1893 int fontsize, int align, int colour, char *text);
1895 Draws text in the puzzle window.
1897 `x' and `y' give the coordinates of a point. The relation of this point
1898 to the location of the text is specified by `align', which is a bitwise
1899 OR of horizontal and vertical alignment flags:
1903 Indicates that `y' is aligned with the baseline of the text.
1907 Indicates that `y' is aligned with the vertical centre of the
1908 text. (In fact, it's aligned with the vertical centre of normal
1909 _capitalised_ text: displaying two pieces of text with ALIGN_VCENTRE
1910 at the same y-coordinate will cause their baselines to be aligned
1911 with one another, even if one is an ascender and the other a
1916 Indicates that `x' is aligned with the left-hand end of the text.
1920 Indicates that `x' is aligned with the horizontal centre of the
1925 Indicates that `x' is aligned with the right-hand end of the text.
1927 `fonttype' is either FONT_FIXED or FONT_VARIABLE, for a monospaced
1928 or proportional font respectively. (No more detail than that may be
1929 specified; it would only lead to portability issues between different
1932 `fontsize' is the desired size, in pixels, of the text. This size
1933 corresponds to the overall point size of the text, not to any internal
1934 dimension such as the cap-height.
1936 `colour' is an integer index into the colours array returned by the back
1937 end function colours() (section 2.8.6).
1939 This function may be used for both drawing and printing.
1941 The character set used to encode the text passed to this function is
1942 specified _by the drawing object_, although it must be a superset of
1943 ASCII. If a puzzle wants to display text that is not contained in ASCII,
1944 it should use the text_fallback() function (section 3.1.8) to query the
1945 drawing object for an appropriate representation of the characters it
1948 3.1.8. text_fallback()
1949 ----------------------
1951 char *text_fallback(drawing *dr, const char *const *strings,
1954 This function is used to request a translation of UTF-8 text into
1955 whatever character encoding is expected by the drawing object's
1956 implementation of draw_text().
1958 The input is a list of strings encoded in UTF-8: nstrings gives the
1959 number of strings in the list, and strings[0], strings[1], ...,
1960 strings[nstrings-1] are the strings themselves.
1962 The returned string (which is dynamically allocated and must be freed
1963 when finished with) is derived from the first string in the list that
1964 the drawing object expects to be able to display reliably; it will
1965 consist of that string translated into the character set expected by
1968 Drawing implementations are not required to handle anything outside
1969 ASCII, but are permitted to assume that _some_ string will be
1970 successfully translated. So every call to this function must include
1971 a string somewhere in the list (presumably the last element) which
1972 consists of nothing but ASCII, to be used by any front end which cannot
1973 handle anything else.
1975 For example, if a puzzle wished to display a string including a
1976 multiplication sign (U+00D7 in Unicode, represented by the bytes C3 97
1977 in UTF-8), it might do something like this:
1979 static const char *const times_signs[] = { "\xC3\x97", "x" };
1980 char *times_sign = text_fallback(dr, times_signs, 2);
1981 sprintf(buffer, "%d%s%d", width, times_sign, height);
1982 draw_text(dr, x, y, font, size, align, colour, buffer);
1985 which would draw a string with a times sign in the middle on platforms
1986 that support it, and fall back to a simple ASCII `x' where there was no
1992 void clip(drawing *dr, int x, int y, int w, int h);
1994 Establishes a clipping rectangle in the puzzle window.
1996 `x' and `y' give the coordinates of the top left pixel of the clipping
1997 rectangle. `w' and `h' give its width and height. Thus, the horizontal
1998 extent of the rectangle runs from `x' to `x+w-1' inclusive, and the
1999 vertical extent from `y' to `y+h-1' inclusive. (These are exactly the
2000 same semantics as draw_rect().)
2002 After this call, no drawing operation will affect anything outside the
2003 specified rectangle. The effect can be reversed by calling unclip()
2004 (section 3.1.10). The clipping rectangle is pixel-perfect: pixels within
2005 the rectangle are affected as usual by drawing functions; pixels outside
2006 are completely untouched.
2008 Back ends should not assume that a clipping rectangle will be
2009 automatically cleared up by the front end if it's left lying around;
2010 that might work on current front ends, but shouldn't be relied upon.
2011 Always explicitly call unclip().
2013 This function may be used for both drawing and printing.
2018 void unclip(drawing *dr);
2020 Reverts the effect of a previous call to clip(). After this call, all
2021 drawing operations will be able to affect the entire puzzle window
2024 This function may be used for both drawing and printing.
2026 3.1.11. draw_update()
2027 ---------------------
2029 void draw_update(drawing *dr, int x, int y, int w, int h);
2031 Informs the front end that a rectangular portion of the puzzle window
2032 has been drawn on and needs to be updated.
2034 `x' and `y' give the coordinates of the top left pixel of the update
2035 rectangle. `w' and `h' give its width and height. Thus, the horizontal
2036 extent of the rectangle runs from `x' to `x+w-1' inclusive, and the
2037 vertical extent from `y' to `y+h-1' inclusive. (These are exactly the
2038 same semantics as draw_rect().)
2040 The back end redraw function _must_ call this function to report any
2041 changes it has made to the window. Otherwise, those changes may not
2042 become immediately visible, and may then appear at an unpredictable
2043 subsequent time such as the next time the window is covered and re-
2046 This function is only important when drawing. It may be called when
2047 printing as well, but doing so is not compulsory, and has no effect.
2048 (So if you have a shared piece of code between the drawing and printing
2049 routines, that code may safely call draw_update().)
2051 3.1.12. status_bar()
2052 --------------------
2054 void status_bar(drawing *dr, char *text);
2056 Sets the text in the game's status bar to `text'. The text is copied
2057 from the supplied buffer, so the caller is free to deallocate or modify
2058 the buffer after use.
2060 (This function is not exactly a _drawing_ function, but it shares with
2061 the drawing API the property that it may only be called from within the
2062 back end redraw function, so this is as good a place as any to document
2065 The supplied text is filtered through the mid-end for optional rewriting
2066 before being passed on to the front end; the mid-end will prepend the
2067 current game time if the game is timed (and may in future perform other
2068 rewriting if it seems like a good idea).
2070 This function is for drawing only; it must never be called during
2073 3.1.13. Blitter functions
2074 -------------------------
2076 This section describes a group of related functions which save and
2077 restore a section of the puzzle window. This is most commonly used to
2078 implement user interfaces involving dragging a puzzle element around the
2079 window: at the end of each call to redraw(), if an object is currently
2080 being dragged, the back end saves the window contents under that
2081 location and then draws the dragged object, and at the start of the next
2082 redraw() the first thing it does is to restore the background.
2084 The front end defines an opaque type called a `blitter', which is
2085 capable of storing a rectangular area of a specified size.
2087 Blitter functions are for drawing only; they must never be called during
2090 3.1.13.1. blitter_new()
2091 -----------------------
2093 blitter *blitter_new(drawing *dr, int w, int h);
2095 Creates a new blitter object which stores a rectangle of size `w' by `h'
2096 pixels. Returns a pointer to the blitter object.
2098 Blitter objects are best stored in the `game_drawstate'. A good time to
2099 create them is in the set_size() function (section 2.8.5), since it is
2100 at this point that you first know how big a rectangle they will need to
2103 3.1.13.2. blitter_free()
2104 ------------------------
2106 void blitter_free(drawing *dr, blitter *bl);
2108 Disposes of a blitter object. Best called in free_drawstate(). (However,
2109 check that the blitter object is not NULL before attempting to free it;
2110 it is possible that a draw state might be created and freed without ever
2111 having set_size() called on it in between.)
2113 3.1.13.3. blitter_save()
2114 ------------------------
2116 void blitter_save(drawing *dr, blitter *bl, int x, int y);
2118 This is a true drawing API function, in that it may only be called from
2119 within the game redraw routine. It saves a rectangular portion of the
2120 puzzle window into the specified blitter object.
2122 `x' and `y' give the coordinates of the top left corner of the saved
2123 rectangle. The rectangle's width and height are the ones specified when
2124 the blitter object was created.
2126 This function is required to cope and do the right thing if `x' and `y'
2127 are out of range. (The right thing probably means saving whatever part
2128 of the blitter rectangle overlaps with the visible area of the puzzle
2131 3.1.13.4. blitter_load()
2132 ------------------------
2134 void blitter_load(drawing *dr, blitter *bl, int x, int y);
2136 This is a true drawing API function, in that it may only be called from
2137 within the game redraw routine. It restores a rectangular portion of the
2138 puzzle window from the specified blitter object.
2140 `x' and `y' give the coordinates of the top left corner of the rectangle
2141 to be restored. The rectangle's width and height are the ones specified
2142 when the blitter object was created.
2144 Alternatively, you can specify both `x' and `y' as the special value
2145 BLITTER_FROMSAVED, in which case the rectangle will be restored to
2146 exactly where it was saved from. (This is probably what you want to do
2147 almost all the time, if you're using blitters to implement draggable
2150 This function is required to cope and do the right thing if `x' and
2151 `y' (or the equivalent ones saved in the blitter) are out of range.
2152 (The right thing probably means restoring whatever part of the blitter
2153 rectangle overlaps with the visible area of the puzzle window.)
2155 If this function is called on a blitter which had previously been saved
2156 from a partially out-of-range rectangle, then the parts of the saved
2157 bitmap which were not visible at save time are undefined. If the blitter
2158 is restored to a different position so as to make those parts visible,
2159 the effect on the drawing area is undefined.
2161 3.1.14. print_mono_colour()
2162 ---------------------------
2164 int print_mono_colour(drawing *dr, int grey);
2166 This function allocates a colour index for a simple monochrome colour
2169 `grey' must be 0 or 1. If `grey' is 0, the colour returned is black; if
2170 `grey' is 1, the colour is white.
2172 3.1.15. print_grey_colour()
2173 ---------------------------
2175 int print_grey_colour(drawing *dr, float grey);
2177 This function allocates a colour index for a grey-scale colour during
2180 `grey' may be any number between 0 (black) and 1 (white); for example,
2181 0.5 indicates a medium grey.
2183 The chosen colour will be rendered to the limits of the printer's
2184 halftoning capability.
2186 3.1.16. print_hatched_colour()
2187 ------------------------------
2189 int print_hatched_colour(drawing *dr, int hatch);
2191 This function allocates a colour index which does not represent a
2192 literal _colour_. Instead, regions shaded in this colour will be hatched
2193 with parallel lines. The `hatch' parameter defines what type of hatching
2194 should be used in place of this colour:
2198 This colour will be hatched by lines slanting to the right at 45
2203 This colour will be hatched by lines slanting to the left at 45
2208 This colour will be hatched by horizontal lines.
2212 This colour will be hatched by vertical lines.
2216 This colour will be hatched by criss-crossing horizontal and
2221 This colour will be hatched by criss-crossing diagonal lines.
2223 Colours defined to use hatching may not be used for drawing lines or
2224 text; they may only be used for filling areas. That is, they may be
2225 used as the `fillcolour' parameter to draw_circle() and draw_polygon(),
2226 and as the colour parameter to draw_rect(), but may not be used as the
2227 `outlinecolour' parameter to draw_circle() or draw_polygon(), or with
2228 draw_line() or draw_text().
2230 3.1.17. print_rgb_mono_colour()
2231 -------------------------------
2233 int print_rgb_mono_colour(drawing *dr, float r, float g,
2234 float b, float grey);
2236 This function allocates a colour index for a fully specified RGB colour
2239 `r', `g' and `b' may each be anywhere in the range from 0 to 1.
2241 If printing in black and white only, these values will be ignored, and
2242 either pure black or pure white will be used instead, according to the
2243 `grey' parameter. (The fallback colour is the same as the one which
2244 would be allocated by print_mono_colour(grey).)
2246 3.1.18. print_rgb_grey_colour()
2247 -------------------------------
2249 int print_rgb_grey_colour(drawing *dr, float r, float g,
2250 float b, float grey);
2252 This function allocates a colour index for a fully specified RGB colour
2255 `r', `g' and `b' may each be anywhere in the range from 0 to 1.
2257 If printing in black and white only, these values will be ignored, and
2258 a shade of grey given by the `grey' parameter will be used instead.
2259 (The fallback colour is the same as the one which would be allocated by
2260 print_grey_colour(grey).)
2262 3.1.19. print_rgb_hatched_colour()
2263 ----------------------------------
2265 int print_rgb_hatched_colour(drawing *dr, float r, float g,
2266 float b, float hatched);
2268 This function allocates a colour index for a fully specified RGB colour
2271 `r', `g' and `b' may each be anywhere in the range from 0 to 1.
2273 If printing in black and white only, these values will be ignored, and
2274 a form of cross-hatching given by the `hatch' parameter will be used
2275 instead; see section 3.1.16 for the possible values of this parameter.
2276 (The fallback colour is the same as the one which would be allocated by
2277 print_hatched_colour(hatch).)
2279 3.1.20. print_line_width()
2280 --------------------------
2282 void print_line_width(drawing *dr, int width);
2284 This function is called to set the thickness of lines drawn during
2285 printing. It is meaningless in drawing: all lines drawn by draw_line(),
2286 draw_circle and draw_polygon() are one pixel in thickness. However, in
2287 printing there is no clear definition of a pixel and so line widths must
2288 be explicitly specified.
2290 The line width is specified in the usual coordinate system. Note,
2291 however, that it is a hint only: the central printing system may choose
2292 to vary line thicknesses at user request or due to printer capabilities.
2294 3.1.21. print_line_dotted()
2295 ---------------------------
2297 void print_line_dotted(drawing *dr, int dotted);
2299 This function is called to toggle the drawing of dotted lines during
2300 printing. It is not supported during drawing.
2302 The parameter `dotted' is a boolean; TRUE means that future lines drawn
2303 by draw_line(), draw_circle and draw_polygon() will be dotted, and FALSE
2304 means that they will be solid.
2306 Some front ends may impose restrictions on the width of dotted lines.
2307 Asking for a dotted line via this front end will override any line width
2308 request if the front end requires it.
2310 3.2. The drawing API as implemented by the front end
2311 ----------------------------------------------------
2313 This section describes the drawing API in the function-pointer form in
2314 which it is implemented by a front end.
2316 (It isn't only platform-specific front ends which implement this API;
2317 the platform-independent module `ps.c' also provides an implementation
2318 of it which outputs PostScript. Thus, any platform which wants to do PS
2319 printing can do so with minimum fuss.)
2321 The following entries all describe function pointer fields in a
2322 structure called `drawing_api'. Each of the functions takes a `void *'
2323 context pointer, which it should internally cast back to a more useful
2324 type. Thus, a drawing _object_ (`drawing *)' suitable for passing to
2325 the back end redraw or printing functions is constructed by passing a
2326 `drawing_api' and a `void *' to the function drawing_new() (see section
2332 void (*draw_text)(void *handle, int x, int y, int fonttype,
2333 int fontsize, int align, int colour, char *text);
2335 This function behaves exactly like the back end draw_text() function;
2341 void (*draw_rect)(void *handle, int x, int y, int w, int h,
2344 This function behaves exactly like the back end draw_rect() function;
2350 void (*draw_line)(void *handle, int x1, int y1, int x2, int y2,
2353 This function behaves exactly like the back end draw_line() function;
2356 3.2.4. draw_polygon()
2357 ---------------------
2359 void (*draw_polygon)(void *handle, int *coords, int npoints,
2360 int fillcolour, int outlinecolour);
2362 This function behaves exactly like the back end draw_polygon() function;
2365 3.2.5. draw_circle()
2366 --------------------
2368 void (*draw_circle)(void *handle, int cx, int cy, int radius,
2369 int fillcolour, int outlinecolour);
2371 This function behaves exactly like the back end draw_circle() function;
2374 3.2.6. draw_thick_line()
2375 ------------------------
2377 void draw_thick_line(drawing *dr, float thickness,
2378 float x1, float y1, float x2, float y2,
2381 This function behaves exactly like the back end draw_thick_line()
2382 function; see section 3.1.6.
2384 An implementation of this API which doesn't provide high-quality
2385 rendering of thick lines is permitted to define this function pointer
2386 to be NULL. The middleware in drawing.c will notice and provide a low-
2387 quality alternative using draw_polygon().
2389 3.2.7. draw_update()
2390 --------------------
2392 void (*draw_update)(void *handle, int x, int y, int w, int h);
2394 This function behaves exactly like the back end draw_update() function;
2397 An implementation of this API which only supports printing is permitted
2398 to define this function pointer to be NULL rather than bothering to
2399 define an empty function. The middleware in drawing.c will notice and
2405 void (*clip)(void *handle, int x, int y, int w, int h);
2407 This function behaves exactly like the back end clip() function; see
2413 void (*unclip)(void *handle);
2415 This function behaves exactly like the back end unclip() function; see
2418 3.2.10. start_draw()
2419 --------------------
2421 void (*start_draw)(void *handle);
2423 This function is called at the start of drawing. It allows the front end
2424 to initialise any temporary data required to draw with, such as device
2427 Implementations of this API which do not provide drawing services may
2428 define this function pointer to be NULL; it will never be called unless
2429 drawing is attempted.
2434 void (*end_draw)(void *handle);
2436 This function is called at the end of drawing. It allows the front end
2437 to do cleanup tasks such as deallocating device contexts and scheduling
2438 appropriate GUI redraw events.
2440 Implementations of this API which do not provide drawing services may
2441 define this function pointer to be NULL; it will never be called unless
2442 drawing is attempted.
2444 3.2.12. status_bar()
2445 --------------------
2447 void (*status_bar)(void *handle, char *text);
2449 This function behaves exactly like the back end status_bar() function;
2452 Front ends implementing this function need not worry about it
2453 being called repeatedly with the same text; the middleware code in
2454 status_bar() will take care of this.
2456 Implementations of this API which do not provide drawing services may
2457 define this function pointer to be NULL; it will never be called unless
2458 drawing is attempted.
2460 3.2.13. blitter_new()
2461 ---------------------
2463 blitter *(*blitter_new)(void *handle, int w, int h);
2465 This function behaves exactly like the back end blitter_new() function;
2466 see section 3.1.13.1.
2468 Implementations of this API which do not provide drawing services may
2469 define this function pointer to be NULL; it will never be called unless
2470 drawing is attempted.
2472 3.2.14. blitter_free()
2473 ----------------------
2475 void (*blitter_free)(void *handle, blitter *bl);
2477 This function behaves exactly like the back end blitter_free() function;
2478 see section 3.1.13.2.
2480 Implementations of this API which do not provide drawing services may
2481 define this function pointer to be NULL; it will never be called unless
2482 drawing is attempted.
2484 3.2.15. blitter_save()
2485 ----------------------
2487 void (*blitter_save)(void *handle, blitter *bl, int x, int y);
2489 This function behaves exactly like the back end blitter_save() function;
2490 see section 3.1.13.3.
2492 Implementations of this API which do not provide drawing services may
2493 define this function pointer to be NULL; it will never be called unless
2494 drawing is attempted.
2496 3.2.16. blitter_load()
2497 ----------------------
2499 void (*blitter_load)(void *handle, blitter *bl, int x, int y);
2501 This function behaves exactly like the back end blitter_load() function;
2502 see section 3.1.13.4.
2504 Implementations of this API which do not provide drawing services may
2505 define this function pointer to be NULL; it will never be called unless
2506 drawing is attempted.
2511 void (*begin_doc)(void *handle, int pages);
2513 This function is called at the beginning of a printing run. It gives the
2514 front end an opportunity to initialise any required printing subsystem.
2515 It also provides the number of pages in advance.
2517 Implementations of this API which do not provide printing services may
2518 define this function pointer to be NULL; it will never be called unless
2519 printing is attempted.
2521 3.2.18. begin_page()
2522 --------------------
2524 void (*begin_page)(void *handle, int number);
2526 This function is called during printing, at the beginning of each page.
2527 It gives the page number (numbered from 1 rather than 0, so suitable for
2528 use in user-visible contexts).
2530 Implementations of this API which do not provide printing services may
2531 define this function pointer to be NULL; it will never be called unless
2532 printing is attempted.
2534 3.2.19. begin_puzzle()
2535 ----------------------
2537 void (*begin_puzzle)(void *handle, float xm, float xc,
2538 float ym, float yc, int pw, int ph, float wmm);
2540 This function is called during printing, just before printing a single
2541 puzzle on a page. It specifies the size and location of the puzzle on
2544 `xm' and `xc' specify the horizontal position of the puzzle on the page,
2545 as a linear function of the page width. The front end is expected to
2546 multiply the page width by `xm', add `xc' (measured in millimetres), and
2547 use the resulting x-coordinate as the left edge of the puzzle.
2549 Similarly, `ym' and `yc' specify the vertical position of the puzzle as
2550 a function of the page height: the page height times `ym', plus `yc'
2551 millimetres, equals the desired distance from the top of the page to the
2554 (This unwieldy mechanism is required because not all printing systems
2555 can communicate the page size back to the software. The PostScript back
2556 end, for example, writes out PS which determines the page size at print
2557 time by means of calling `clippath', and centres the puzzles within
2558 that. Thus, exactly the same PS file works on A4 or on US Letter paper
2559 without needing local configuration, which simplifies matters.)
2561 pw and ph give the size of the puzzle in drawing API coordinates. The
2562 printing system will subsequently call the puzzle's own print function,
2563 which will in turn call drawing API functions in the expectation that an
2564 area pw by ph units is available to draw the puzzle on.
2566 Finally, wmm gives the desired width of the puzzle in millimetres. (The
2567 aspect ratio is expected to be preserved, so if the desired puzzle
2568 height is also needed then it can be computed as wmm*ph/pw.)
2570 Implementations of this API which do not provide printing services may
2571 define this function pointer to be NULL; it will never be called unless
2572 printing is attempted.
2574 3.2.20. end_puzzle()
2575 --------------------
2577 void (*end_puzzle)(void *handle);
2579 This function is called after the printing of a specific puzzle is
2582 Implementations of this API which do not provide printing services may
2583 define this function pointer to be NULL; it will never be called unless
2584 printing is attempted.
2589 void (*end_page)(void *handle, int number);
2591 This function is called after the printing of a page is finished.
2593 Implementations of this API which do not provide printing services may
2594 define this function pointer to be NULL; it will never be called unless
2595 printing is attempted.
2600 void (*end_doc)(void *handle);
2602 This function is called after the printing of the entire document is
2603 finished. This is the moment to close files, send things to the print
2604 spooler, or whatever the local convention is.
2606 Implementations of this API which do not provide printing services may
2607 define this function pointer to be NULL; it will never be called unless
2608 printing is attempted.
2610 3.2.23. line_width()
2611 --------------------
2613 void (*line_width)(void *handle, float width);
2615 This function is called to set the line thickness, during printing only.
2616 Note that the width is a float here, where it was an int as seen by the
2617 back end. This is because drawing.c may have scaled it on the way past.
2619 However, the width is still specified in the same coordinate system as
2620 the rest of the drawing.
2622 Implementations of this API which do not provide printing services may
2623 define this function pointer to be NULL; it will never be called unless
2624 printing is attempted.
2626 3.2.24. text_fallback()
2627 -----------------------
2629 char *(*text_fallback)(void *handle, const char *const *strings,
2632 This function behaves exactly like the back end text_fallback()
2633 function; see section 3.1.8.
2635 Implementations of this API which do not support any characters outside
2636 ASCII may define this function pointer to be NULL, in which case the
2637 central code in drawing.c will provide a default implementation.
2639 3.3. The drawing API as called by the front end
2640 -----------------------------------------------
2642 There are a small number of functions provided in drawing.c which the
2643 front end needs to _call_, rather than helping to implement. They are
2644 described in this section.
2646 3.3.1. drawing_new()
2647 --------------------
2649 drawing *drawing_new(const drawing_api *api, midend *me,
2652 This function creates a drawing object. It is passed a `drawing_api',
2653 which is a structure containing nothing but function pointers; and also
2654 a `void *' handle. The handle is passed back to each function pointer
2657 The `midend' parameter is used for rewriting the status bar contents:
2658 status_bar() (see section 3.1.12) has to call a function in the mid-
2659 end which might rewrite the status bar text. If the drawing object
2660 is to be used only for printing, or if the game is known not to call
2661 status_bar(), this parameter may be NULL.
2663 3.3.2. drawing_free()
2664 ---------------------
2666 void drawing_free(drawing *dr);
2668 This function frees a drawing object. Note that the `void *' handle is
2669 not freed; if that needs cleaning up it must be done by the front end.
2671 3.3.3. print_get_colour()
2672 -------------------------
2674 void print_get_colour(drawing *dr, int colour, int printincolour,
2675 int *hatch, float *r, float *g, float *b)
2677 This function is called by the implementations of the drawing API
2678 functions when they are called in a printing context. It takes a colour
2679 index as input, and returns the description of the colour as requested
2682 `printincolour' is TRUE iff the implementation is printing in colour.
2683 This will alter the results returned if the colour in question was
2684 specified with a black-and-white fallback value.
2686 If the colour should be rendered by hatching, `*hatch' is filled with
2687 the type of hatching desired. See section 3.1.15 for details of the
2688 values this integer can take.
2690 If the colour should be rendered as solid colour, `*hatch' is given a
2691 negative value, and `*r', `*g' and `*b' are filled with the RGB values
2692 of the desired colour (if printing in colour), or all filled with the
2693 grey-scale value (if printing in black and white).
2695 4. The API provided by the mid-end
2696 ----------------------------------
2698 This chapter documents the API provided by the mid-end to be called by
2699 the front end. You probably only need to read this if you are a front
2700 end implementor, i.e. you are porting Puzzles to a new platform. If
2701 you're only interested in writing new puzzles, you can safely skip this
2704 All the persistent state in the mid-end is encapsulated within a
2705 `midend' structure, to facilitate having multiple mid-ends in any
2706 port which supports multiple puzzle windows open simultaneously. Each
2707 `midend' is intended to handle the contents of a single puzzle window.
2712 midend *midend_new(frontend *fe, const game *ourgame,
2713 const drawing_api *drapi, void *drhandle)
2715 Allocates and returns a new mid-end structure.
2717 The `fe' argument is stored in the mid-end. It will be used when calling
2718 back to functions such as activate_timer() (section 4.36), and will be
2719 passed on to the back end function colours() (section 2.8.6).
2721 The parameters `drapi' and `drhandle' are passed to drawing_new()
2722 (section 3.3.1) to construct a drawing object which will be passed to
2723 the back end function redraw() (section 2.8.10). Hence, all drawing-
2724 related function pointers defined in `drapi' can expect to be called
2725 with `drhandle' as their first argument.
2727 The `ourgame' argument points to a container structure describing a game
2728 back end. The mid-end thus created will only be capable of handling that
2729 one game. (So even in a monolithic front end containing all the games,
2730 this imposes the constraint that any individual puzzle window is tied to
2731 a single game. Unless, of course, you feel brave enough to change the
2732 mid-end for the window without closing the window...)
2737 void midend_free(midend *me);
2739 Frees a mid-end structure and all its associated data.
2741 4.3. midend_tilesize()
2742 ----------------------
2744 int midend_tilesize(midend *me);
2746 Returns the `tilesize' parameter being used to display the current
2747 puzzle (section 2.8.3).
2749 4.4. midend_set_params()
2750 ------------------------
2752 void midend_set_params(midend *me, game_params *params);
2754 Sets the current game parameters for a mid-end. Subsequent games
2755 generated by midend_new_game() (section 4.8) will use these parameters
2756 until further notice.
2758 The usual way in which the front end will have an actual `game_params'
2759 structure to pass to this function is if it had previously got it from
2760 midend_get_presets() (section 4.15). Thus, this function is usually
2761 called in response to the user making a selection from the presets menu.
2763 4.5. midend_get_params()
2764 ------------------------
2766 game_params *midend_get_params(midend *me);
2768 Returns the current game parameters stored in this mid-end.
2770 The returned value is dynamically allocated, and should be freed when
2771 finished with by passing it to the game's own free_params() function
2772 (see section 2.3.6).
2777 void midend_size(midend *me, int *x, int *y, int user_size);
2779 Tells the mid-end to figure out its window size.
2781 On input, `*x' and `*y' should contain the maximum or requested size
2782 for the window. (Typically this will be the size of the screen that the
2783 window has to fit on, or similar.) The mid-end will repeatedly call the
2784 back end function compute_size() (section 2.8.4), searching for a tile
2785 size that best satisfies the requirements. On exit, `*x' and `*y' will
2786 contain the size needed for the puzzle window's drawing area. (It is
2787 of course up to the front end to adjust this for any additional window
2788 furniture such as menu bars and window borders, if necessary. The status
2789 bar is also not included in this size.)
2791 Use `user_size' to indicate whether `*x' and `*y' are a requested size,
2792 or just a maximum size.
2794 If `user_size' is set to TRUE, the mid-end will treat the input size as
2795 a request, and will pick a tile size which approximates it _as closely
2796 as possible_, going over the game's preferred tile size if necessary to
2797 achieve this. The mid-end will also use the resulting tile size as its
2798 preferred one until further notice, on the assumption that this size was
2799 explicitly requested by the user. Use this option if you want your front
2800 end to support dynamic resizing of the puzzle window with automatic
2801 scaling of the puzzle to fit.
2803 If `user_size' is set to FALSE, then the game's tile size will never go
2804 over its preferred one, although it may go under in order to fit within
2805 the maximum bounds specified by `*x' and `*y'. This is the recommended
2806 approach when opening a new window at default size: the game will use
2807 its preferred size unless it has to use a smaller one to fit on the
2808 screen. If the tile size is shrunk for this reason, the change will not
2809 persist; if a smaller grid is subsequently chosen, the tile size will
2812 The mid-end will try as hard as it can to return a size which is
2813 less than or equal to the input size, in both dimensions. In extreme
2814 circumstances it may fail (if even the lowest possible tile size gives
2815 window dimensions greater than the input), in which case it will return
2816 a size greater than the input size. Front ends should be prepared
2817 for this to happen (i.e. don't crash or fail an assertion), but may
2818 handle it in any way they see fit: by rejecting the game parameters
2819 which caused the problem, by opening a window larger than the screen
2820 regardless of inconvenience, by introducing scroll bars on the window,
2821 by drawing on a large bitmap and scaling it into a smaller window, or by
2822 any other means you can think of. It is likely that when the tile size
2823 is that small the game will be unplayable anyway, so don't put _too_
2824 much effort into handling it creatively.
2826 If your platform has no limit on window size (or if you're planning to
2827 use scroll bars for large puzzles), you can pass dimensions of INT_MAX
2828 as input to this function. You should probably not do that _and_ set the
2829 `user_size' flag, though!
2831 The midend relies on the frontend calling midend_new_game() (section
2832 4.8) before calling midend_size().
2834 4.7. midend_reset_tilesize()
2835 ----------------------------
2837 void midend_reset_tilesize(midend *me);
2839 This function resets the midend's preferred tile size to that of the
2842 As discussed in section 4.6, puzzle resizes are typically 'sticky',
2843 in that once the user has dragged the puzzle to a different window
2844 size, the resulting tile size will be remembered and used when the
2845 puzzle configuration changes. If you _don't_ want that, e.g. if you
2846 want to provide a command to explicitly reset the puzzle size back to
2847 its default, then you can call this just before calling midend_size()
2848 (which, in turn, you would probably call with `user_size' set to FALSE).
2850 4.8. midend_new_game()
2851 ----------------------
2853 void midend_new_game(midend *me);
2855 Causes the mid-end to begin a new game. Normally the game will be a
2856 new randomly generated puzzle. However, if you have previously called
2857 midend_game_id() or midend_set_config(), the game generated might be
2858 dictated by the results of those functions. (In particular, you _must_
2859 call midend_new_game() after calling either of those functions, or else
2860 no immediate effect will be visible.)
2862 You will probably need to call midend_size() after calling this
2863 function, because if the game parameters have been changed since the
2864 last new game then the window size might need to change. (If you know
2865 the parameters _haven't_ changed, you don't need to do this.)
2867 This function will create a new `game_drawstate', but does not actually
2868 perform a redraw (since you often need to call midend_size() before
2869 the redraw can be done). So after calling this function and after
2870 calling midend_size(), you should then call midend_redraw(). (It is not
2871 necessary to call midend_force_redraw(); that will discard the draw
2872 state and create a fresh one, which is unnecessary in this case since
2873 there's a fresh one already. It would work, but it's usually excessive.)
2875 4.9. midend_restart_game()
2876 --------------------------
2878 void midend_restart_game(midend *me);
2880 This function causes the current game to be restarted. This is done by
2881 placing a new copy of the original game state on the end of the undo
2882 list (so that an accidental restart can be undone).
2884 This function automatically causes a redraw, i.e. the front end can
2885 expect its drawing API to be called from _within_ a call to this
2886 function. Some back ends require that midend_size() (section 4.6) is
2887 called before midend_restart_game().
2889 4.10. midend_force_redraw()
2890 ---------------------------
2892 void midend_force_redraw(midend *me);
2894 Forces a complete redraw of the puzzle window, by means of discarding
2895 the current `game_drawstate' and creating a new one from scratch before
2896 calling the game's redraw() function.
2898 The front end can expect its drawing API to be called from within a call
2899 to this function. Some back ends require that midend_size() (section
2900 4.6) is called before midend_force_redraw().
2902 4.11. midend_redraw()
2903 ---------------------
2905 void midend_redraw(midend *me);
2907 Causes a partial redraw of the puzzle window, by means of simply calling
2908 the game's redraw() function. (That is, the only things redrawn will be
2909 things that have changed since the last redraw.)
2911 The front end can expect its drawing API to be called from within a call
2912 to this function. Some back ends require that midend_size() (section
2913 4.6) is called before midend_redraw().
2915 4.12. midend_process_key()
2916 --------------------------
2918 int midend_process_key(midend *me, int x, int y, int button);
2920 The front end calls this function to report a mouse or keyboard event.
2921 The parameters `x', `y' and `button' are almost identical to the ones
2922 passed to the back end function interpret_move() (section 2.7.1), except
2923 that the front end is _not_ required to provide the guarantees about
2924 mouse event ordering. The mid-end will sort out multiple simultaneous
2925 button presses and changes of button; the front end's responsibility
2926 is simply to pass on the mouse events it receives as accurately as
2929 (Some platforms may need to emulate absent mouse buttons by means of
2930 using a modifier key such as Shift with another mouse button. This tends
2931 to mean that if Shift is pressed or released in the middle of a mouse
2932 drag, the mid-end will suddenly stop receiving, say, LEFT_DRAG events
2933 and start receiving RIGHT_DRAGs, with no intervening button release or
2934 press events. This too is something which the mid-end will sort out for
2935 you; the front end has no obligation to maintain sanity in this area.)
2937 The front end _should_, however, always eventually send some kind of
2938 button release. On some platforms this requires special effort: Windows,
2939 for example, requires a call to the system API function SetCapture() in
2940 order to ensure that your window receives a mouse-up event even if the
2941 pointer has left the window by the time the mouse button is released.
2942 On any platform that requires this sort of thing, the front end _is_
2943 responsible for doing it.
2945 Calling this function is very likely to result in calls back to the
2946 front end's drawing API and/or activate_timer() (section 4.36).
2948 The return value from midend_process_key() is non-zero, unless the
2949 effect of the keypress was to request termination of the program. A
2950 front end should shut down the puzzle in response to a zero return.
2952 4.13. midend_colours()
2953 ----------------------
2955 float *midend_colours(midend *me, int *ncolours);
2957 Returns an array of the colours required by the game, in exactly
2958 the same format as that returned by the back end function colours()
2959 (section 2.8.6). Front ends should call this function rather than
2960 calling the back end's version directly, since the mid-end adds standard
2961 customisation facilities. (At the time of writing, those customisation
2962 facilities are implemented hackily by means of environment variables,
2963 but it's not impossible that they may become more full and formal in
2966 4.14. midend_timer()
2967 --------------------
2969 void midend_timer(midend *me, float tplus);
2971 If the mid-end has called activate_timer() (section 4.36) to request
2972 regular callbacks for purposes of animation or timing, this is the
2973 function the front end should call on a regular basis. The argument
2974 `tplus' gives the time, in seconds, since the last time either this
2975 function was called or activate_timer() was invoked.
2977 One of the major purposes of timing in the mid-end is to perform move
2978 animation. Therefore, calling this function is very likely to result in
2979 calls back to the front end's drawing API.
2981 4.15. midend_get_presets()
2982 --------------------------
2984 struct preset_menu *midend_get_presets(midend *me, int *id_limit);
2986 Returns a data structure describing this game's collection of preset
2987 game parameters, organised into a hierarchical structure of menus and
2990 The return value is a pointer to a data structure containing the
2991 following fields (among others, which are not intended for front end
2994 struct preset_menu {
2996 struct preset_menu_entry *entries;
2997 /* and other things */
3000 Those fields describe the intended contents of one particular menu in
3001 the hierarchy. `entries' points to an array of `n_entries' items, each
3002 of which is a structure containing the following fields:
3004 struct preset_menu_entry {
3006 game_params *params;
3007 struct preset_menu *submenu;
3011 Of these fields, `title' and `id' are present in every entry, giving
3012 (respectively) the textual name of the menu item and an integer
3013 identifier for it. The integer id will correspond to the one returned
3014 by `midend_which_preset' (section 4.16), when that preset is the one
3017 The other two fields are mutually exclusive. Each
3018 `struct preset_menu_entry' will have one of those fields NULL and the
3019 other one non-null. If the menu item is an actual preset, then `params'
3020 will point to the set of game parameters that go with the name; if it's
3021 a submenu, then `submenu' instead will be non-null, and will point at a
3022 subsidiary `struct preset_menu'.
3024 The complete hierarchy of these structures is owned by the mid-end,
3025 and will be freed when the mid-end is freed. The front end should not
3026 attempt to free any of it.
3028 The integer identifiers will be allocated densely from 0 upwards, so
3029 that it's reasonable for the front end to allocate an array which uses
3030 them as indices, if it needs to store information per preset menu item.
3031 For this purpose, the front end may pass the second parameter `id_limit'
3032 to midend_get_presets as the address of an `int' variable, into which
3033 midend_get_presets will write an integer one larger than the largest id
3034 number actually used (i.e. the number of elements the front end would
3037 Submenu-type entries also have integer identifiers.
3039 4.16. midend_which_preset()
3040 ---------------------------
3042 int midend_which_preset(midend *me);
3044 Returns the numeric index of the preset game parameter structure which
3045 matches the current game parameters, or a negative number if no preset
3046 matches. Front ends could use this to maintain a tick beside one of the
3047 items in the menu (or tick the `Custom' option if the return value is
3050 The returned index value (if non-negative) will match the `id'
3051 field of the corresponding struct preset_menu_entry returned by
3052 `midend_get_presets()' (section 4.15).
3054 4.17. midend_wants_statusbar()
3055 ------------------------------
3057 int midend_wants_statusbar(midend *me);
3059 This function returns TRUE if the puzzle has a use for a textual status
3060 line (to display score, completion status, currently active tiles, time,
3063 Front ends should call this function rather than talking directly to the
3066 4.18. midend_get_config()
3067 -------------------------
3069 config_item *midend_get_config(midend *me, int which,
3072 Returns a dialog box description for user configuration.
3074 On input, which should be set to one of three values, which select which
3075 of the various dialog box descriptions is returned:
3079 Requests the GUI parameter configuration box generated by the puzzle
3080 itself. This should be used when the user selects `Custom' from the
3081 game types menu (or equivalent). The mid-end passes this request on
3082 to the back end function configure() (section 2.3.9).
3086 Requests a box suitable for entering a descriptive game ID (and
3087 viewing the existing one). The mid-end generates this dialog box
3088 description itself. This should be used when the user selects
3089 `Specific' from the game menu (or equivalent).
3093 Requests a box suitable for entering a random-seed game ID (and
3094 viewing the existing one). The mid-end generates this dialog box
3095 description itself. This should be used when the user selects
3096 `Random Seed' from the game menu (or equivalent).
3098 The returned value is an array of config_items, exactly as described
3099 in section 2.3.9. Another returned value is an ASCII string giving a
3100 suitable title for the configuration window, in `*wintitle'.
3102 Both returned values are dynamically allocated and will need to be
3103 freed. The window title can be freed in the obvious way; the config_item
3104 array is a slightly complex structure, so a utility function free_cfg()
3105 is provided to free it for you. See section 5.3.6.
3107 (Of course, you will probably not want to free the config_item array
3108 until the dialog box is dismissed, because before then you will probably
3109 need to pass it to midend_set_config.)
3111 4.19. midend_set_config()
3112 -------------------------
3114 char *midend_set_config(midend *me, int which,
3117 Passes the mid-end the results of a configuration dialog box. `which'
3118 should have the same value which it had when midend_get_config() was
3119 called; `cfg' should be the array of `config_item's returned from
3120 midend_get_config(), modified to contain the results of the user's
3123 This function returns NULL on success, or otherwise (if the
3124 configuration data was in some way invalid) an ASCII string containing
3125 an error message suitable for showing to the user.
3127 If the function succeeds, it is likely that the game parameters will
3128 have been changed and it is certain that a new game will be requested.
3129 The front end should therefore call midend_new_game(), and probably also
3130 re-think the window size using midend_size() and eventually perform a
3131 refresh using midend_redraw().
3133 4.20. midend_game_id()
3134 ----------------------
3136 char *midend_game_id(midend *me, char *id);
3138 Passes the mid-end a string game ID (of any of the valid forms `params',
3139 `params:description' or `params#seed') which the mid-end will process
3140 and use for the next generated game.
3142 This function returns NULL on success, or otherwise (if the
3143 configuration data was in some way invalid) an ASCII string containing
3144 an error message (not dynamically allocated) suitable for showing to the
3145 user. In the event of an error, the mid-end's internal state will be
3146 left exactly as it was before the call.
3148 If the function succeeds, it is likely that the game parameters will
3149 have been changed and it is certain that a new game will be requested.
3150 The front end should therefore call midend_new_game(), and probably
3151 also re-think the window size using midend_size() and eventually case a
3152 refresh using midend_redraw().
3154 4.21. midend_get_game_id()
3155 --------------------------
3157 char *midend_get_game_id(midend *me)
3159 Returns a descriptive game ID (i.e. one in the form
3160 `params:description') describing the game currently active in the mid-
3161 end. The returned string is dynamically allocated.
3163 4.22. midend_get_random_seed()
3164 ------------------------------
3166 char *midend_get_random_seed(midend *me)
3168 Returns a random game ID (i.e. one in the form `params#seedstring')
3169 describing the game currently active in the mid-end, if there is one.
3170 If the game was created by entering a description, no random seed will
3171 currently exist and this function will return NULL.
3173 The returned string, if it is non-NULL, is dynamically allocated.
3175 4.23. midend_can_format_as_text_now()
3176 -------------------------------------
3178 int midend_can_format_as_text_now(midend *me);
3180 Returns TRUE if the game code is capable of formatting puzzles of the
3181 currently selected game type as ASCII.
3183 If this returns FALSE, then midend_text_format() (section 4.24) will
3186 4.24. midend_text_format()
3187 --------------------------
3189 char *midend_text_format(midend *me);
3191 Formats the current game's current state as ASCII text suitable for
3192 copying to the clipboard. The returned string is dynamically allocated.
3194 If the game's `can_format_as_text_ever' flag is FALSE, or if its
3195 can_format_as_text_now() function returns FALSE, then this function will
3198 If the returned string contains multiple lines (which is likely), it
3199 will use the normal C line ending convention (\n only). On platforms
3200 which use a different line ending convention for data in the clipboard,
3201 it is the front end's responsibility to perform the conversion.
3203 4.25. midend_solve()
3204 --------------------
3206 char *midend_solve(midend *me);
3208 Requests the mid-end to perform a Solve operation.
3210 On success, NULL is returned. On failure, an error message (not
3211 dynamically allocated) is returned, suitable for showing to the user.
3213 The front end can expect its drawing API and/or activate_timer() to be
3214 called from within a call to this function. Some back ends require that
3215 midend_size() (section 4.6) is called before midend_solve().
3217 4.26. midend_status()
3218 ---------------------
3220 int midend_status(midend *me);
3222 This function returns +1 if the midend is currently displaying a game
3223 in a solved state, -1 if the game is in a permanently lost state, or 0
3224 otherwise. This function just calls the back end's status() function.
3225 Front ends may wish to use this as a cue to proactively offer the option
3226 of starting a new game.
3228 (See section 2.8.9 for more detail about the back end's status()
3229 function and discussion of what should count as which status code.)
3231 4.27. midend_can_undo()
3232 -----------------------
3234 int midend_can_undo(midend *me);
3236 Returns TRUE if the midend is currently in a state where the undo
3237 operation is meaningful (i.e. at least one position exists on the undo
3238 chain before the present one). Front ends may wish to use this to
3239 visually activate and deactivate an undo button.
3241 4.28. midend_can_redo()
3242 -----------------------
3244 int midend_can_redo(midend *me);
3246 Returns TRUE if the midend is currently in a state where the redo
3247 operation is meaningful (i.e. at least one position exists on the
3248 redo chain after the present one). Front ends may wish to use this to
3249 visually activate and deactivate a redo button.
3251 4.29. midend_serialise()
3252 ------------------------
3254 void midend_serialise(midend *me,
3255 void (*write)(void *ctx, void *buf, int len),
3258 Calling this function causes the mid-end to convert its entire internal
3259 state into a long ASCII text string, and to pass that string (piece by
3260 piece) to the supplied `write' function.
3262 Desktop implementations can use this function to save a game in any
3263 state (including half-finished) to a disk file, by supplying a `write'
3264 function which is a wrapper on fwrite() (or local equivalent). Other
3265 implementations may find other uses for it, such as compressing the
3266 large and sprawling mid-end state into a manageable amount of memory
3267 when a palmtop application is suspended so that another one can run; in
3268 this case write might want to write to a memory buffer rather than a
3269 file. There may be other uses for it as well.
3271 This function will call back to the supplied `write' function a number
3272 of times, with the first parameter (`ctx') equal to `wctx', and the
3273 other two parameters pointing at a piece of the output string.
3275 4.30. midend_deserialise()
3276 --------------------------
3278 char *midend_deserialise(midend *me,
3279 int (*read)(void *ctx, void *buf, int len),
3282 This function is the counterpart to midend_serialise(). It calls the
3283 supplied read function repeatedly to read a quantity of data, and
3284 attempts to interpret that data as a serialised mid-end as output by
3287 The read function is called with the first parameter (`ctx') equal
3288 to `rctx', and should attempt to read `len' bytes of data into the
3289 buffer pointed to by `buf'. It should return FALSE on failure or TRUE
3290 on success. It should not report success unless it has filled the
3291 entire buffer; on platforms which might be reading from a pipe or other
3292 blocking data source, `read' is responsible for looping until the whole
3293 buffer has been filled.
3295 If the de-serialisation operation is successful, the mid-end's internal
3296 data structures will be replaced by the results of the load, and NULL
3297 will be returned. Otherwise, the mid-end's state will be completely
3298 unchanged and an error message (typically some variation on `save file
3299 is corrupt') will be returned. As usual, the error message string is not
3300 dynamically allocated.
3302 If this function succeeds, it is likely that the game parameters will
3303 have been changed. The front end should therefore probably re-think the
3304 window size using midend_size(), and probably cause a refresh using
3307 Because each mid-end is tied to a specific game back end, this function
3308 will fail if you attempt to read in a save file generated by a different
3309 game from the one configured in this mid-end, even if your application
3310 is a monolithic one containing all the puzzles. See section 4.31 for a
3311 helper function which will allow you to identify a save file before you
3312 instantiate your mid-end in the first place.
3314 4.31. identify_game()
3315 ---------------------
3317 char *identify_game(char **name,
3318 int (*read)(void *ctx, void *buf, int len),
3321 This function examines a serialised midend stream, of the same kind used
3322 by midend_serialise() and midend_deserialise(), and returns the name
3323 field of the game back end from which it was saved.
3325 You might want this if your front end was a monolithic one containing
3326 all the puzzles, and you wanted to be able to load an arbitrary save
3327 file and automatically switch to the right game. Probably your next step
3328 would be to iterate through gamelist (section 4.33) looking for a game
3329 structure whose name field matched the returned string, and give an
3330 error if you didn't find one.
3332 On success, the return value of this function is NULL, and the game name
3333 string is written into *name. The caller should free that string after
3336 On failure, *name is NULL, and the return value is an error message
3337 (which does not need freeing at all).
3339 (This isn't strictly speaking a midend function, since it doesn't accept
3340 or return a pointer to a midend. You'd probably call it just _before_
3341 deciding what kind of midend you wanted to instantiate.)
3343 4.32. midend_request_id_changes()
3344 ---------------------------------
3346 void midend_request_id_changes(midend *me,
3347 void (*notify)(void *), void *ctx);
3349 This function is called by the front end to request notification by the
3350 mid-end when the current game IDs (either descriptive or random-seed)
3351 change. This can occur as a result of keypresses ('n' for New Game, for
3352 example) or when a puzzle supersedes its game description (see section
3353 2.11.2). After this function is called, any change of the game ids will
3354 cause the mid-end to call notify(ctx) after the change.
3356 This is for use by puzzles which want to present the game description to
3357 the user constantly (e.g. as an HTML hyperlink) instead of only showing
3358 it when the user explicitly requests it.
3360 This is a function I anticipate few front ends needing to implement, so
3361 I make it a callback rather than a static function in order to relieve
3362 most front ends of the need to provide an empty implementation.
3364 4.33. Direct reference to the back end structure by the front end
3365 -----------------------------------------------------------------
3367 Although _most_ things the front end needs done should be done by
3368 calling the mid-end, there are a few situations in which the front end
3369 needs to refer directly to the game back end structure.
3371 The most obvious of these is
3373 - passing the game back end as a parameter to midend_new().
3375 There are a few other back end features which are not wrapped by the
3376 mid-end because there didn't seem much point in doing so:
3378 - fetching the `name' field to use in window titles and similar
3380 - reading the `can_configure', `can_solve' and
3381 `can_format_as_text_ever' fields to decide whether to add those
3382 items to the menu bar or equivalent
3384 - reading the `winhelp_topic' field (Windows only)
3386 - the GTK front end provides a `--generate' command-line option which
3387 directly calls the back end to do most of its work. This is not
3388 really part of the main front end code, though, and I'm not sure it
3391 In order to find the game back end structure, the front end does one of
3394 - If the particular front end is compiling a separate binary per game,
3395 then the back end structure is a global variable with the standard
3398 extern const game thegame;
3400 - If the front end is compiled as a monolithic application containing
3401 all the puzzles together (in which case the preprocessor symbol
3402 COMBINED must be defined when compiling most of the code base), then
3403 there will be two global variables defined:
3405 extern const game *gamelist[];
3406 extern const int gamecount;
3408 `gamelist' will be an array of `gamecount' game structures, declared
3409 in the automatically constructed source module `list.c'. The
3410 application should search that array for the game it wants, probably
3411 by reaching into each game structure and looking at its `name'
3414 4.34. Mid-end to front-end calls
3415 --------------------------------
3417 This section describes the small number of functions which a front end
3418 must provide to be called by the mid-end or other standard utility
3421 4.35. get_random_seed()
3422 -----------------------
3424 void get_random_seed(void **randseed, int *randseedsize);
3426 This function is called by a new mid-end, and also occasionally by game
3427 back ends. Its job is to return a piece of data suitable for using as a
3428 seed for initialisation of a new `random_state'.
3430 On exit, `*randseed' should be set to point at a newly allocated piece
3431 of memory containing some seed data, and `*randseedsize' should be set
3432 to the length of that data.
3434 A simple and entirely adequate implementation is to return a piece of
3435 data containing the current system time at the highest conveniently
3436 available resolution.
3438 4.36. activate_timer()
3439 ----------------------
3441 void activate_timer(frontend *fe);
3443 This is called by the mid-end to request that the front end begin
3444 calling it back at regular intervals.
3446 The timeout interval is left up to the front end; the finer it is, the
3447 smoother move animations will be, but the more CPU time will be used.
3448 Current front ends use values around 20ms (i.e. 50Hz).
3450 After this function is called, the mid-end will expect to receive calls
3451 to midend_timer() on a regular basis.
3453 4.37. deactivate_timer()
3454 ------------------------
3456 void deactivate_timer(frontend *fe);
3458 This is called by the mid-end to request that the front end stop calling
3464 void fatal(char *fmt, ...);
3466 This is called by some utility functions if they encounter a genuinely
3467 fatal error such as running out of memory. It is a variadic function
3468 in the style of printf(), and is expected to show the formatted error
3469 message to the user any way it can and then terminate the application.
3472 4.39. frontend_default_colour()
3473 -------------------------------
3475 void frontend_default_colour(frontend *fe, float *output);
3477 This function expects to be passed a pointer to an array of three
3478 floats. It returns the platform's local preferred background colour
3479 in those three floats, as red, green and blue values (in that order)
3480 ranging from 0.0 to 1.0.
3482 This function should only ever be called by the back end function
3483 colours() (section 2.8.6). (Thus, it isn't a _midend_-to-frontend
3484 function as such, but there didn't seem to be anywhere else particularly
3485 good to put it. Sorry.)
3490 This chapter documents a variety of utility APIs provided for the
3491 general use of the rest of the Puzzles code.
3493 5.1. Random number generation
3494 -----------------------------
3496 Platforms' local random number generators vary widely in quality and
3497 seed size. Puzzles therefore supplies its own high-quality random number
3498 generator, with the additional advantage of giving the same results if
3499 fed the same seed data on different platforms. This allows game random
3500 seeds to be exchanged between different ports of Puzzles and still
3501 generate the same games.
3503 Unlike the ANSI C rand() function, the Puzzles random number generator
3504 has an _explicit_ state object called a `random_state'. One of these
3505 is managed by each mid-end, for example, and passed to the back end to
3506 generate a game with.
3511 random_state *random_new(char *seed, int len);
3513 Allocates, initialises and returns a new `random_state'. The input data
3514 is used as the seed for the random number stream (i.e. using the same
3515 seed at a later time will generate the same stream).
3517 The seed data can be any data at all; there is no requirement to use
3518 printable ASCII, or NUL-terminated strings, or anything like that.
3520 5.1.2. random_copy()
3521 --------------------
3523 random_state *random_copy(random_state *tocopy);
3525 Allocates a new `random_state', copies the contents of another
3526 `random_state' into it, and returns the new state. If exactly the
3527 same sequence of functions is subseqently called on both the copy and
3528 the original, the results will be identical. This may be useful for
3529 speculatively performing some operation using a given random state, and
3530 later replaying that operation precisely.
3532 5.1.3. random_free()
3533 --------------------
3535 void random_free(random_state *state);
3537 Frees a `random_state'.
3539 5.1.4. random_bits()
3540 --------------------
3542 unsigned long random_bits(random_state *state, int bits);
3544 Returns a random number from 0 to 2^bits-1 inclusive. `bits' should be
3545 between 1 and 32 inclusive.
3547 5.1.5. random_upto()
3548 --------------------
3550 unsigned long random_upto(random_state *state, unsigned long limit);
3552 Returns a random number from 0 to limit-1 inclusive.
3554 5.1.6. random_state_encode()
3555 ----------------------------
3557 char *random_state_encode(random_state *state);
3559 Encodes the entire contents of a `random_state' in printable ASCII.
3560 Returns a dynamically allocated string containing that encoding. This
3561 can subsequently be passed to random_state_decode() to reconstruct the
3562 same `random_state'.
3564 5.1.7. random_state_decode()
3565 ----------------------------
3567 random_state *random_state_decode(char *input);
3569 Decodes a string generated by random_state_encode() and reconstructs an
3570 equivalent `random_state' to the one encoded, i.e. it should produce the
3571 same stream of random numbers.
3573 This function has no error reporting; if you pass it an invalid string
3574 it will simply generate an arbitrary random state, which may turn out to
3575 be noticeably non-random.
3580 void shuffle(void *array, int nelts, int eltsize, random_state *rs);
3582 Shuffles an array into a random order. The interface is much like ANSI C
3583 qsort(), except that there's no need for a compare function.
3585 `array' is a pointer to the first element of the array. `nelts' is the
3586 number of elements in the array; `eltsize' is the size of a single
3587 element (typically measured using `sizeof'). `rs' is a `random_state'
3588 used to generate all the random numbers for the shuffling process.
3590 5.2. Presets menu management
3591 ----------------------------
3593 The function `midend_get_presets()' (section 4.15) returns a data
3594 structure describing a menu hierarchy. Back ends can also choose to
3595 provide such a structure to the mid-end, if they want to group their
3596 presets hierarchically. To make this easy, there are a few utility
3597 functions to construct preset menu structures, and also one intended for
3600 5.2.1. preset_menu_new()
3601 ------------------------
3603 struct preset_menu *preset_menu_new(void);
3605 Allocates a new `struct preset_menu', and initialises it to hold no menu
3608 5.2.2. preset_menu_add_submenu()
3609 --------------------------------
3611 struct preset_menu *preset_menu_add_submenu
3612 (struct preset_menu *parent, char *title);
3614 Adds a new submenu to the end of an existing preset menu, and returns
3615 a pointer to a newly allocated `struct preset_menu' describing the
3618 The string parameter `title' must be dynamically allocated by the
3619 caller. The preset-menu structure will take ownership of it, so the
3620 caller must not free it.
3622 5.2.3. preset_menu_add_preset()
3623 -------------------------------
3625 void preset_menu_add_preset
3626 (struct preset_menu *menu, char *title, game_params *params);
3628 Adds a preset game configuration to the end of a preset menu.
3630 Both the string parameter `title' and the game parameter structure
3631 `params' itself must be dynamically allocated by the caller. The preset-
3632 menu structure will take ownership of it, so the caller must not free
3635 5.2.4. preset_menu_lookup_by_id()
3636 ---------------------------------
3638 game_params *preset_menu_lookup_by_id
3639 (struct preset_menu *menu, int id);
3641 Given a numeric index, searches recursively through a preset menu
3642 hierarchy to find the corresponding menu entry, and returns a pointer to
3643 its existing `game_params' structure.
3645 This function is intended for front end use (but front ends need not use
3646 it if they prefer to do things another way). If a front end finds it
3647 inconvenient to store anything more than a numeric index alongside each
3648 menu item, then this function provides an easy way for the front end to
3649 get back the actual game parameters corresponding to a menu item that
3650 the user has selected.
3652 5.3. Memory allocation
3653 ----------------------
3655 Puzzles has some central wrappers on the standard memory allocation
3656 functions, which provide compile-time type checking, and run-time error
3657 checking by means of quitting the application if it runs out of memory.
3658 This doesn't provide the best possible recovery from memory shortage,
3659 but on the other hand it greatly simplifies the rest of the code,
3660 because nothing else anywhere needs to worry about NULL returns from
3668 This macro takes a single argument which is a _type name_. It allocates
3669 space for one object of that type. If allocation fails it will call
3670 fatal() and not return; so if it does return, you can be confident that
3671 its return value is non-NULL.
3673 The return value is cast to the specified type, so that the compiler
3674 will type-check it against the variable you assign it into. Thus, this
3675 ensures you don't accidentally allocate memory the size of the wrong
3676 type and assign it into a variable of the right one (or vice versa!).
3681 var = snewn(n, type);
3683 This macro is the array form of snew(). It takes two arguments; the
3684 first is a number, and the second is a type name. It allocates space
3685 for that many objects of that type, and returns a type-checked non-NULL
3686 pointer just as snew() does.
3691 var = sresize(var, n, type);
3693 This macro is a type-checked form of realloc(). It takes three
3694 arguments: an input memory block, a new size in elements, and a type.
3695 It re-sizes the input memory block to a size sufficient to contain that
3696 many elements of that type. It returns a type-checked non-NULL pointer,
3697 like snew() and snewn().
3699 The input memory block can be NULL, in which case this function will
3700 behave exactly like snewn(). (In principle any ANSI-compliant realloc()
3701 implementation ought to cope with this, but I've never quite trusted it
3702 to work everywhere.)
3707 void sfree(void *p);
3709 This function is pretty much equivalent to free(). It is provided with a
3710 dynamically allocated block, and frees it.
3712 The input memory block can be NULL, in which case this function will do
3713 nothing. (In principle any ANSI-compliant free() implementation ought to
3714 cope with this, but I've never quite trusted it to work everywhere.)
3719 char *dupstr(const char *s);
3721 This function dynamically allocates a duplicate of a C string. Like the
3722 snew() functions, it guarantees to return non-NULL or not return at all.
3724 (Many platforms provide the function strdup(). As well as guaranteeing
3725 never to return NULL, my version has the advantage of being defined
3726 _everywhere_, rather than inconveniently not quite everywhere.)
3731 void free_cfg(config_item *cfg);
3733 This function correctly frees an array of `config_item's, including
3734 walking the array until it gets to the end and freeing precisely those
3735 `sval' fields which are expected to be dynamically allocated.
3737 (See section 2.3.9 for details of the `config_item' structure.)
3739 5.4. Sorted and counted tree functions
3740 --------------------------------------
3742 Many games require complex algorithms for generating random puzzles, and
3743 some require moderately complex algorithms even during play. A common
3744 requirement during these algorithms is for a means of maintaining sorted
3745 or unsorted lists of items, such that items can be removed and added
3748 For general use, Puzzles provides the following set of functions which
3749 maintain 2-3-4 trees in memory. (A 2-3-4 tree is a balanced tree
3750 structure, with the property that all lookups, insertions, deletions,
3751 splits and joins can be done in O(log N) time.)
3753 All these functions expect you to be storing a tree of `void *'
3754 pointers. You can put anything you like in those pointers.
3756 By the use of per-node element counts, these tree structures have the
3757 slightly unusual ability to look elements up by their numeric index
3758 within the list represented by the tree. This means that they can be
3759 used to store an unsorted list (in which case, every time you insert a
3760 new element, you must explicitly specify the position where you wish to
3761 insert it). They can also do numeric lookups in a sorted tree, which
3762 might be useful for (for example) tracking the median of a changing data
3765 As well as storing sorted lists, these functions can be used for storing
3766 `maps' (associative arrays), by defining each element of a tree to be a
3772 tree234 *newtree234(cmpfn234 cmp);
3774 Creates a new empty tree, and returns a pointer to it.
3776 The parameter `cmp' determines the sorting criterion on the tree. Its
3779 typedef int (*cmpfn234)(void *, void *);
3781 If you want a sorted tree, you should provide a function matching this
3782 prototype, which returns like strcmp() does (negative if the first
3783 argument is smaller than the second, positive if it is bigger, zero if
3784 they compare equal). In this case, the function addpos234() will not be
3785 usable on your tree (because all insertions must respect the sorting
3788 If you want an unsorted tree, pass NULL. In this case you will not be
3789 able to use either add234() or del234(), or any other function such
3790 as find234() which depends on a sorting order. Your tree will become
3791 something more like an array, except that it will efficiently support
3792 insertion and deletion as well as lookups by numeric index.
3794 5.4.2. freetree234()
3795 --------------------
3797 void freetree234(tree234 *t);
3799 Frees a tree. This function will not free the _elements_ of the tree
3800 (because they might not be dynamically allocated, or you might be
3801 storing the same set of elements in more than one tree); it will just
3802 free the tree structure itself. If you want to free all the elements of
3803 a tree, you should empty it before passing it to freetree234(), by means
3804 of code along the lines of
3806 while ((element = delpos234(tree, 0)) != NULL)
3807 sfree(element); /* or some more complicated free function */
3812 void *add234(tree234 *t, void *e);
3814 Inserts a new element `e' into the tree `t'. This function expects the
3815 tree to be sorted; the new element is inserted according to the sort
3818 If an element comparing equal to `e' is already in the tree, then the
3819 insertion will fail, and the return value will be the existing element.
3820 Otherwise, the insertion succeeds, and `e' is returned.
3825 void *addpos234(tree234 *t, void *e, int index);
3827 Inserts a new element into an unsorted tree. Since there is no sorting
3828 order to dictate where the new element goes, you must specify where you
3829 want it to go. Setting `index' to zero puts the new element right at the
3830 start of the list; setting `index' to the current number of elements in
3831 the tree puts the new element at the end.
3833 Return value is `e', in line with add234() (although this function
3834 cannot fail except by running out of memory, in which case it will bomb
3835 out and die rather than returning an error indication).
3840 void *index234(tree234 *t, int index);
3842 Returns a pointer to the `index'th element of the tree, or NULL if
3843 `index' is out of range. Elements of the tree are numbered from zero.
3848 void *find234(tree234 *t, void *e, cmpfn234 cmp);
3850 Searches for an element comparing equal to `e' in a sorted tree.
3852 If `cmp' is NULL, the tree's ordinary comparison function will be used
3853 to perform the search. However, sometimes you don't want that; suppose,
3854 for example, each of your elements is a big structure containing a
3855 `char *' name field, and you want to find the element with a given name.
3856 You _could_ achieve this by constructing a fake element structure,
3857 setting its name field appropriately, and passing it to find234(),
3858 but you might find it more convenient to pass _just_ a name string to
3859 find234(), supplying an alternative comparison function which expects
3860 one of its arguments to be a bare name and the other to be a large
3861 structure containing a name field.
3863 Therefore, if `cmp' is not NULL, then it will be used to compare `e' to
3864 elements of the tree. The first argument passed to `cmp' will always be
3865 `e'; the second will be an element of the tree.
3867 (See section 5.4.1 for the definition of the `cmpfn234' function pointer
3870 The returned value is the element found, or NULL if the search is
3876 void *findrel234(tree234 *t, void *e, cmpfn234 cmp, int relation);
3878 This function is like find234(), but has the additional ability to do a
3879 _relative_ search. The additional parameter `relation' can be one of the
3884 Find only an element that compares equal to `e'. This is exactly the
3885 behaviour of find234().
3889 Find the greatest element that compares strictly less than `e'. `e'
3890 may be NULL, in which case it finds the greatest element in the
3891 whole tree (which could also be done by index234(t, count234(t)-1)).
3895 Find the greatest element that compares less than or equal to `e'.
3896 (That is, find an element that compares equal to `e' if possible,
3897 but failing that settle for something just less than it.)
3901 Find the smallest element that compares strictly greater than `e'.
3902 `e' may be NULL, in which case it finds the smallest element in the
3903 whole tree (which could also be done by index234(t, 0)).
3907 Find the smallest element that compares greater than or equal
3908 to `e'. (That is, find an element that compares equal to `e' if
3909 possible, but failing that settle for something just bigger than
3912 Return value, as before, is the element found or NULL if no element
3913 satisfied the search criterion.
3918 void *findpos234(tree234 *t, void *e, cmpfn234 cmp, int *index);
3920 This function is like find234(), but has the additional feature of
3921 returning the index of the element found in the tree; that index is
3922 written to `*index' in the event of a successful search (a non-NULL
3925 `index' may be NULL, in which case this function behaves exactly like
3928 5.4.9. findrelpos234()
3929 ----------------------
3931 void *findrelpos234(tree234 *t, void *e, cmpfn234 cmp, int relation,
3934 This function combines all the features of findrel234() and
3940 void *del234(tree234 *t, void *e);
3942 Finds an element comparing equal to `e' in the tree, deletes it, and
3945 The input tree must be sorted.
3947 The element found might be `e' itself, or might merely compare equal to
3950 Return value is NULL if no such element is found.
3955 void *delpos234(tree234 *t, int index);
3957 Deletes the element at position `index' in the tree, and returns it.
3959 Return value is NULL if the index is out of range.
3964 int count234(tree234 *t);
3966 Returns the number of elements currently in the tree.
3968 5.4.13. splitpos234()
3969 ---------------------
3971 tree234 *splitpos234(tree234 *t, int index, int before);
3973 Splits the input tree into two pieces at a given position, and creates a
3974 new tree containing all the elements on one side of that position.
3976 If `before' is TRUE, then all the items at or after position `index' are
3977 left in the input tree, and the items before that point are returned in
3978 the new tree. Otherwise, the reverse happens: all the items at or after
3979 `index' are moved into the new tree, and those before that point are
3980 left in the old one.
3982 If `index' is equal to 0 or to the number of elements in the input tree,
3983 then one of the two trees will end up empty (and this is not an error
3984 condition). If `index' is further out of range in either direction, the
3985 operation will fail completely and return NULL.
3987 This operation completes in O(log N) time, no matter how large the tree
3988 or how balanced or unbalanced the split.
3993 tree234 *split234(tree234 *t, void *e, cmpfn234 cmp, int rel);
3995 Splits a sorted tree according to its sort order.
3997 `rel' can be any of the relation constants described in section 5.4.7,
3998 _except_ for REL234_EQ. All the elements having that relation to `e'
3999 will be transferred into the new tree; the rest will be left in the old
4002 The parameter `cmp' has the same semantics as it does in find234(): if
4003 it is not NULL, it will be used in place of the tree's own comparison
4004 function when comparing elements to `e', in such a way that `e' itself
4005 is always the first of its two operands.
4007 Again, this operation completes in O(log N) time, no matter how large
4008 the tree or how balanced or unbalanced the split.
4013 tree234 *join234(tree234 *t1, tree234 *t2);
4015 Joins two trees together by concatenating the lists they represent. All
4016 the elements of `t2' are moved into `t1', in such a way that they appear
4017 _after_ the elements of `t1'. The tree `t2' is freed; the return value
4020 If you apply this function to a sorted tree and it violates the sort
4021 order (i.e. the smallest element in `t2' is smaller than or equal to the
4022 largest element in `t1'), the operation will fail and return NULL.
4024 This operation completes in O(log N) time, no matter how large the trees
4025 being joined together.
4030 tree234 *join234r(tree234 *t1, tree234 *t2);
4032 Joins two trees together in exactly the same way as join234(), but this
4033 time the combined tree is returned in `t2', and `t1' is destroyed. The
4034 elements in `t1' still appear before those in `t2'.
4036 Again, this operation completes in O(log N) time, no matter how large
4037 the trees being joined together.
4039 5.4.17. copytree234()
4040 ---------------------
4042 tree234 *copytree234(tree234 *t, copyfn234 copyfn,
4045 Makes a copy of an entire tree.
4047 If `copyfn' is NULL, the tree will be copied but the elements will not
4048 be; i.e. the new tree will contain pointers to exactly the same physical
4049 elements as the old one.
4051 If you want to copy each actual element during the operation, you can
4052 instead pass a function in `copyfn' which makes a copy of each element.
4053 That function has the prototype
4055 typedef void *(*copyfn234)(void *state, void *element);
4057 and every time it is called, the `state' parameter will be set to the
4058 value you passed in as `copyfnstate'.
4060 5.5. Miscellaneous utility functions and macros
4061 -----------------------------------------------
4063 This section contains all the utility functions which didn't sensibly
4066 5.5.1. TRUE and FALSE
4067 ---------------------
4069 The main Puzzles header file defines the macros TRUE and FALSE, which
4070 are used throughout the code in place of 1 and 0 (respectively) to
4071 indicate that the values are in a boolean context. For code base
4072 consistency, I'd prefer it if submissions of new code followed this
4075 5.5.2. max() and min()
4076 ----------------------
4078 The main Puzzles header file defines the pretty standard macros max()
4079 and min(), each of which is given two arguments and returns the one
4080 which compares greater or less respectively.
4082 These macros may evaluate their arguments multiple times. Avoid side
4088 The main Puzzles header file defines a macro PI which expands to a
4089 floating-point constant representing pi.
4091 (I've never understood why ANSI's <math.h> doesn't define this. It'd be
4094 5.5.4. obfuscate_bitmap()
4095 -------------------------
4097 void obfuscate_bitmap(unsigned char *bmp, int bits, int decode);
4099 This function obscures the contents of a piece of data, by cryptographic
4100 methods. It is useful for games of hidden information (such as Mines,
4101 Guess or Black Box), in which the game ID theoretically reveals all the
4102 information the player is supposed to be trying to guess. So in order
4103 that players should be able to send game IDs to one another without
4104 accidentally spoiling the resulting game by looking at them, these games
4105 obfuscate their game IDs using this function.
4107 Although the obfuscation function is cryptographic, it cannot properly
4108 be called encryption because it has no key. Therefore, anybody motivated
4109 enough can re-implement it, or hack it out of the Puzzles source,
4110 and strip the obfuscation off one of these game IDs to see what lies
4111 beneath. (Indeed, they could usually do it much more easily than that,
4112 by entering the game ID into their own copy of the puzzle and hitting
4113 Solve.) The aim is not to protect against a determined attacker; the aim
4114 is simply to protect people who wanted to play the game honestly from
4115 _accidentally_ spoiling their own fun.
4117 The input argument `bmp' points at a piece of memory to be obfuscated.
4118 `bits' gives the length of the data. Note that that length is in _bits_
4119 rather than bytes: if you ask for obfuscation of a partial number of
4120 bytes, then you will get it. Bytes are considered to be used from the
4121 top down: thus, for example, setting `bits' to 10 will cover the whole
4122 of bmp[0] and the _top two_ bits of bmp[1]. The remainder of a partially
4123 used byte is undefined (i.e. it may be corrupted by the function).
4125 The parameter `decode' is FALSE for an encoding operation, and TRUE
4126 for a decoding operation. Each is the inverse of the other. (There's
4127 no particular reason you shouldn't obfuscate by decoding and restore
4128 cleartext by encoding, if you really wanted to; it should still work.)
4130 The input bitmap is processed in place.
4135 char *bin2hex(const unsigned char *in, int inlen);
4137 This function takes an input byte array and converts it into an
4138 ASCII string encoding those bytes in (lower-case) hex. It returns a
4139 dynamically allocated string containing that encoding.
4141 This function is useful for encoding the result of obfuscate_bitmap() in
4142 printable ASCII for use in game IDs.
4147 unsigned char *hex2bin(const char *in, int outlen);
4149 This function takes an ASCII string containing hex digits, and converts
4150 it back into a byte array of length `outlen'. If there aren't enough
4151 hex digits in the string, the contents of the resulting array will be
4154 This function is the inverse of bin2hex().
4156 5.5.7. game_mkhighlight()
4157 -------------------------
4159 void game_mkhighlight(frontend *fe, float *ret,
4160 int background, int highlight, int lowlight);
4162 It's reasonably common for a puzzle game's graphics to use highlights
4163 and lowlights to indicate `raised' or `lowered' sections. Fifteen,
4164 Sixteen and Twiddle are good examples of this.
4166 Puzzles using this graphical style are running a risk if they just use
4167 whatever background colour is supplied to them by the front end, because
4168 that background colour might be too light to see any highlights on at
4169 all. (In particular, it's not unheard of for the front end to specify a
4170 default background colour of white.)
4172 Therefore, such puzzles can call this utility function from their
4173 colours() routine (section 2.8.6). You pass it your front end handle, a
4174 pointer to the start of your return array, and three colour indices. It
4177 - call frontend_default_colour() (section 4.39) to fetch the front
4178 end's default background colour
4180 - alter the brightness of that colour if it's unsuitable
4182 - define brighter and darker variants of the colour to be used as
4183 highlights and lowlights
4185 - write those results into the relevant positions in the `ret' array.
4187 Thus, ret[background*3] to ret[background*3+2] will be set to RGB values
4188 defining a sensible background colour, and similary `highlight' and
4189 `lowlight' will be set to sensible colours.
4191 6. How to write a new puzzle
4192 ----------------------------
4194 This chapter gives a guide to how to actually write a new puzzle: where
4195 to start, what to do first, how to solve common problems.
4197 The previous chapters have been largely composed of facts. This one is
4200 6.1. Choosing a puzzle
4201 ----------------------
4203 Before you start writing a puzzle, you have to choose one. Your taste
4204 in puzzle games is up to you, of course; and, in fact, you're probably
4205 reading this guide because you've _already_ thought of a game you want
4206 to write. But if you want to get it accepted into the official Puzzles
4207 distribution, then there's a criterion it has to meet.
4209 The current Puzzles editorial policy is that all games should be _fair_.
4210 A fair game is one which a player can only fail to complete through
4211 demonstrable lack of skill - that is, such that a better player in the
4212 same situation would have _known_ to do something different.
4214 For a start, that means every game presented to the user must have _at
4215 least one solution_. Giving the unsuspecting user a puzzle which is
4216 actually impossible is not acceptable. (There is an exception: if the
4217 user has selected some non-default option which is clearly labelled as
4218 potentially unfair, _then_ you're allowed to generate possibly insoluble
4219 puzzles, because the user isn't unsuspecting any more. Same Game and
4220 Mines both have options of this type.)
4222 Also, this actually _rules out_ games such as Klondike, or the normal
4223 form of Mahjong Solitaire. Those games have the property that even if
4224 there is a solution (i.e. some sequence of moves which will get from
4225 the start state to the solved state), the player doesn't necessarily
4226 have enough information to _find_ that solution. In both games, it is
4227 possible to reach a dead end because you had an arbitrary choice to make
4228 and made it the wrong way. This violates the fairness criterion, because
4229 a better player couldn't have known they needed to make the other
4232 (GNOME has a variant on Mahjong Solitaire which makes it fair: there
4233 is a Shuffle operation which randomly permutes all the remaining tiles
4234 without changing their positions, which allows you to get out of a
4235 sticky situation. Using this operation adds a 60-second penalty to your
4236 solution time, so it's to the player's advantage to try to minimise
4237 the chance of having to use it. It's still possible to render the game
4238 uncompletable if you end up with only two tiles vertically stacked,
4239 but that's easy to foresee and avoid using a shuffle operation. This
4240 form of the game _is_ fair. Implementing it in Puzzles would require
4241 an infrastructure change so that the back end could communicate time
4242 penalties to the mid-end, but that would be easy enough.)
4244 Providing a _unique_ solution is a little more negotiable; it depends
4245 on the puzzle. Solo would have been of unacceptably low quality if it
4246 didn't always have a unique solution, whereas Twiddle inherently has
4247 multiple solutions by its very nature and it would have been meaningless
4248 to even _suggest_ making it uniquely soluble. Somewhere in between, Flip
4249 could reasonably be made to have unique solutions (by enforcing a zero-
4250 dimension kernel in every generated matrix) but it doesn't seem like a
4251 serious quality problem that it doesn't.
4253 Of course, you don't _have_ to care about all this. There's nothing
4254 stopping you implementing any puzzle you want to if you're happy to
4255 maintain your puzzle yourself, distribute it from your own web site,
4256 fork the Puzzles code completely, or anything like that. It's free
4257 software; you can do what you like with it. But any game that you want
4258 to be accepted into _my_ Puzzles code base has to satisfy the fairness
4259 criterion, which means all randomly generated puzzles must have a
4260 solution (unless the user has deliberately chosen otherwise) and it must
4261 be possible _in theory_ to find that solution without having to guess.
4263 6.2. Getting started
4264 --------------------
4266 The simplest way to start writing a new puzzle is to copy `nullgame.c'.
4267 This is a template puzzle source file which does almost nothing, but
4268 which contains all the back end function prototypes and declares the
4269 back end data structure correctly. It is built every time the rest of
4270 Puzzles is built, to ensure that it doesn't get out of sync with the
4271 code and remains buildable.
4273 So start by copying `nullgame.c' into your new source file. Then you'll
4274 gradually add functionality until the very boring Null Game turns into
4277 Next you'll need to add your puzzle to the Makefiles, in order to
4278 compile it conveniently. _Do not edit the Makefiles_: they are created
4279 automatically by the script `mkfiles.pl', from the file called `Recipe'.
4280 Edit `Recipe', and then re-run `mkfiles.pl'.
4282 Also, don't forget to add your puzzle to `list.c': if you don't, then it
4283 will still run fine on platforms which build each puzzle separately, but
4284 Mac OS X and other monolithic platforms will not include your new puzzle
4285 in their single binary.
4287 Once your source file is building, you can move on to the fun bit.
4289 6.2.1. Puzzle generation
4290 ------------------------
4292 Randomly generating instances of your puzzle is almost certain to be
4293 the most difficult part of the code, and also the task with the highest
4294 chance of turning out to be completely infeasible. Therefore I strongly
4295 recommend doing it _first_, so that if it all goes horribly wrong you
4296 haven't wasted any more time than you absolutely had to. What I usually
4297 do is to take an unmodified `nullgame.c', and start adding code to
4298 new_game_desc() which tries to generate a puzzle instance and print it
4299 out using printf(). Once that's working, _then_ I start connecting it up
4300 to the return value of new_game_desc(), populating other structures like
4301 `game_params', and generally writing the rest of the source file.
4303 There are many ways to generate a puzzle which is known to be soluble.
4304 In this section I list all the methods I currently know of, in case any
4305 of them can be applied to your puzzle. (Not all of these methods will
4306 work, or in some cases even make sense, for all puzzles.)
4308 Some puzzles are mathematically tractable, meaning you can work out in
4309 advance which instances are soluble. Sixteen, for example, has a parity
4310 constraint in some settings which renders exactly half the game space
4311 unreachable, but it can be mathematically proved that any position
4312 not in that half _is_ reachable. Therefore, Sixteen's grid generation
4313 simply consists of selecting at random from a well defined subset of the
4314 game space. Cube in its default state is even easier: _every_ possible
4315 arrangement of the blue squares and the cube's starting position is
4318 Another option is to redefine what you mean by `soluble'. Black Box
4319 takes this approach. There are layouts of balls in the box which are
4320 completely indistinguishable from one another no matter how many beams
4321 you fire into the box from which angles, which would normally be grounds
4322 for declaring those layouts unfair; but fortunately, detecting that
4323 indistinguishability is computationally easy. So Black Box doesn't
4324 demand that your ball placements match its own; it merely demands
4325 that your ball placements be _indistinguishable_ from the ones it was
4326 thinking of. If you have an ambiguous puzzle, then any of the possible
4327 answers is considered to be a solution. Having redefined the rules in
4328 that way, any puzzle is soluble again.
4330 Those are the simple techniques. If they don't work, you have to get
4333 One way to generate a soluble puzzle is to start from the solved state
4334 and make inverse moves until you reach a starting state. Then you know
4335 there's a solution, because you can just list the inverse moves you made
4336 and make them in the opposite order to return to the solved state.
4338 This method can be simple and effective for puzzles where you get to
4339 decide what's a starting state and what's not. In Pegs, for example,
4340 the generator begins with one peg in the centre of the board and makes
4341 inverse moves until it gets bored; in this puzzle, valid inverse moves
4342 are easy to detect, and _any_ state that's reachable from the solved
4343 state by inverse moves is a reasonable starting position. So Pegs just
4344 continues making inverse moves until the board satisfies some criteria
4345 about extent and density, and then stops and declares itself done.
4347 For other puzzles, it can be a lot more difficult. Same Game uses
4348 this strategy too, and it's lucky to get away with it at all: valid
4349 inverse moves aren't easy to find (because although it's easy to insert
4350 additional squares in a Same Game position, it's difficult to arrange
4351 that _after_ the insertion they aren't adjacent to any other squares of
4352 the same colour), so you're constantly at risk of running out of options
4353 and having to backtrack or start again. Also, Same Game grids never
4354 start off half-empty, which means you can't just stop when you run out
4355 of moves - you have to find a way to fill the grid up _completely_.
4357 The other way to generate a puzzle that's soluble is to start from the
4358 other end, and actually write a _solver_. This tends to ensure that a
4359 puzzle has a _unique_ solution over and above having a solution at all,
4360 so it's a good technique to apply to puzzles for which that's important.
4362 One theoretical drawback of generating soluble puzzles by using a solver
4363 is that your puzzles are restricted in difficulty to those which the
4364 solver can handle. (Most solvers are not fully general: many sets of
4365 puzzle rules are NP-complete or otherwise nasty, so most solvers can
4366 only handle a subset of the theoretically soluble puzzles.) It's been
4367 my experience in practice, however, that this usually isn't a problem;
4368 computers are good at very different things from humans, and what the
4369 computer thinks is nice and easy might still be pleasantly challenging
4370 for a human. For example, when solving Dominosa puzzles I frequently
4371 find myself using a variety of reasoning techniques that my solver
4372 doesn't know about; in principle, therefore, I should be able to solve
4373 the puzzle using only those techniques it _does_ know about, but this
4374 would involve repeatedly searching the entire grid for the one simple
4375 deduction I can make. Computers are good at this sort of exhaustive
4376 search, but it's been my experience that human solvers prefer to do more
4377 complex deductions than to spend ages searching for simple ones. So in
4378 many cases I don't find my own playing experience to be limited by the
4379 restrictions on the solver.
4381 (This isn't _always_ the case. Solo is a counter-example; generating
4382 Solo puzzles using a simple solver does lead to qualitatively easier
4383 puzzles. Therefore I had to make the Solo solver rather more advanced
4386 There are several different ways to apply a solver to the problem of
4387 generating a soluble puzzle. I list a few of them below.
4389 The simplest approach is brute force: randomly generate a puzzle, use
4390 the solver to see if it's soluble, and if not, throw it away and try
4391 again until you get lucky. This is often a viable technique if all
4392 else fails, but it tends not to scale well: for many puzzle types, the
4393 probability of finding a uniquely soluble instance decreases sharply
4394 as puzzle size goes up, so this technique might work reasonably fast
4395 for small puzzles but take (almost) forever at larger sizes. Still, if
4396 there's no other alternative it can be usable: Pattern and Dominosa
4397 both use this technique. (However, Dominosa has a means of tweaking the
4398 randomly generated grids to increase the _probability_ of them being
4399 soluble, by ruling out one of the most common ambiguous cases. This
4400 improved generation speed by over a factor of 10 on the highest preset!)
4402 An approach which can be more scalable involves generating a grid and
4403 then tweaking it to make it soluble. This is the technique used by Mines
4404 and also by Net: first a random puzzle is generated, and then the solver
4405 is run to see how far it gets. Sometimes the solver will get stuck;
4406 when that happens, examine the area it's having trouble with, and make
4407 a small random change in that area to allow it to make more progress.
4408 Continue solving (possibly even without restarting the solver), tweaking
4409 as necessary, until the solver finishes. Then restart the solver from
4410 the beginning to ensure that the tweaks haven't caused new problems in
4411 the process of solving old ones (which can sometimes happen).
4413 This strategy works well in situations where the usual solver failure
4414 mode is to get stuck in an easily localised spot. Thus it works well
4415 for Net and Mines, whose most common failure mode tends to be that most
4416 of the grid is fine but there are a few widely separated ambiguous
4417 sections; but it would work less well for Dominosa, in which the way you
4418 get stuck is to have scoured the whole grid and not found anything you
4419 can deduce _anywhere_. Also, it relies on there being a low probability
4420 that tweaking the grid introduces a new problem at the same time as
4421 solving the old one; Mines and Net also have the property that most of
4422 their deductions are local, so that it's very unlikely for a tweak to
4423 affect something half way across the grid from the location where it was
4424 applied. In Dominosa, by contrast, a lot of deductions use information
4425 about half the grid (`out of all the sixes, only one is next to a
4426 three', which can depend on the values of up to 32 of the 56 squares in
4427 the default setting!), so this tweaking strategy would be rather less
4428 likely to work well.
4430 A more specialised strategy is that used in Solo and Slant. These
4431 puzzles have the property that they derive their difficulty from not
4432 presenting all the available clues. (In Solo's case, if all the possible
4433 clues were provided then the puzzle would already be solved; in Slant
4434 it would still require user action to fill in the lines, but it would
4435 present no challenge at all). Therefore, a simple generation technique
4436 is to leave the decision of which clues to provide until the last
4437 minute. In other words, first generate a random _filled_ grid with all
4438 possible clues present, and then gradually remove clues for as long as
4439 the solver reports that it's still soluble. Unlike the methods described
4440 above, this technique _cannot_ fail - once you've got a filled grid,
4441 nothing can stop you from being able to convert it into a viable puzzle.
4442 However, it wouldn't even be meaningful to apply this technique to (say)
4443 Pattern, in which clues can never be left out, so the only way to affect
4444 the set of clues is by altering the solution.
4446 (Unfortunately, Solo is complicated by the need to provide puzzles at
4447 varying difficulty levels. It's easy enough to generate a puzzle of
4448 _at most_ a given level of difficulty; you just have a solver with
4449 configurable intelligence, and you set it to a given level and apply the
4450 above technique, thus guaranteeing that the resulting grid is solvable
4451 by someone with at most that much intelligence. However, generating a
4452 puzzle of _at least_ a given level of difficulty is rather harder; if
4453 you go for _at most_ Intermediate level, you're likely to find that
4454 you've accidentally generated a Trivial grid a lot of the time, because
4455 removing just one number is sufficient to take the puzzle from Trivial
4456 straight to Ambiguous. In that situation Solo has no remaining options
4457 but to throw the puzzle away and start again.)
4459 A final strategy is to use the solver _during_ puzzle construction:
4460 lay out a bit of the grid, run the solver to see what it allows you to
4461 deduce, and then lay out a bit more to allow the solver to make more
4462 progress. There are articles on the web that recommend constructing
4463 Sudoku puzzles by this method (which is completely the opposite way
4464 round to how Solo does it); for Sudoku it has the advantage that you
4465 get to specify your clue squares in advance (so you can have them make
4468 Rectangles uses a strategy along these lines. First it generates a grid
4469 by placing the actual rectangles; then it has to decide where in each
4470 rectangle to place a number. It uses a solver to help it place the
4471 numbers in such a way as to ensure a unique solution. It does this by
4472 means of running a test solver, but it runs the solver _before_ it's
4473 placed any of the numbers - which means the solver must be capable of
4474 coping with uncertainty about exactly where the numbers are! It runs
4475 the solver as far as it can until it gets stuck; then it narrows down
4476 the possible positions of a number in order to allow the solver to make
4477 more progress, and so on. Most of the time this process terminates with
4478 the grid fully solved, at which point any remaining number-placement
4479 decisions can be made at random from the options not so far ruled out.
4480 Note that unlike the Net/Mines tweaking strategy described above, this
4481 algorithm does not require a checking run after it completes: if it
4482 finishes successfully at all, then it has definitely produced a uniquely
4485 Most of the strategies described above are not 100% reliable. Each
4486 one has a failure rate: every so often it has to throw out the whole
4487 grid and generate a fresh one from scratch. (Solo's strategy would
4488 be the exception, if it weren't for the need to provide configurable
4489 difficulty levels.) Occasional failures are not a fundamental problem in
4490 this sort of work, however: it's just a question of dividing the grid
4491 generation time by the success rate (if it takes 10ms to generate a
4492 candidate grid and 1/5 of them work, then it will take 50ms on average
4493 to generate a viable one), and seeing whether the expected time taken
4494 to _successfully_ generate a puzzle is unacceptably slow. Dominosa's
4495 generator has a very low success rate (about 1 out of 20 candidate grids
4496 turn out to be usable, and if you think _that's_ bad then go and look
4497 at the source code and find the comment showing what the figures were
4498 before the generation-time tweaks!), but the generator itself is very
4499 fast so this doesn't matter. Rectangles has a slower generator, but
4500 fails well under 50% of the time.
4502 So don't be discouraged if you have an algorithm that doesn't always
4503 work: if it _nearly_ always works, that's probably good enough. The one
4504 place where reliability is important is that your algorithm must never
4505 produce false positives: it must not claim a puzzle is soluble when it
4506 isn't. It can produce false negatives (failing to notice that a puzzle
4507 is soluble), and it can fail to generate a puzzle at all, provided it
4508 doesn't do either so often as to become slow.
4510 One last piece of advice: for grid-based puzzles, when writing and
4511 testing your generation algorithm, it's almost always a good idea _not_
4512 to test it initially on a grid that's square (i.e. w==h), because if the
4513 grid is square then you won't notice if you mistakenly write `h' instead
4514 of `w' (or vice versa) somewhere in the code. Use a rectangular grid for
4515 testing, and any size of grid will be likely to work after that.
4517 6.2.2. Designing textual description formats
4518 --------------------------------------------
4520 Another aspect of writing a puzzle which is worth putting some thought
4521 into is the design of the various text description formats: the format
4522 of the game parameter encoding, the game description encoding, and the
4525 The first two of these should be reasonably intuitive for a user to type
4526 in; so provide some flexibility where possible. Suppose, for example,
4527 your parameter format consists of two numbers separated by an `x' to
4528 specify the grid dimensions (`10x10' or `20x15'), and then has some
4529 suffixes to specify other aspects of the game type. It's almost always a
4530 good idea in this situation to arrange that decode_params() can handle
4531 the suffixes appearing in any order, even if encode_params() only ever
4532 generates them in one order.
4534 These formats will also be expected to be reasonably stable: users will
4535 expect to be able to exchange game IDs with other users who aren't
4536 running exactly the same version of your game. So make them robust and
4537 stable: don't build too many assumptions into the game ID format which
4538 will have to be changed every time something subtle changes in the
4541 6.3. Common how-to questions
4542 ----------------------------
4544 This section lists some common things people want to do when writing a
4545 puzzle, and describes how to achieve them within the Puzzles framework.
4547 6.3.1. Drawing objects at only one position
4548 -------------------------------------------
4550 A common phenomenon is to have an object described in the `game_state'
4551 or the `game_ui' which can only be at one position. A cursor - probably
4552 specified in the `game_ui' - is a good example.
4554 In the `game_ui', it would _obviously_ be silly to have an array
4555 covering the whole game grid with a boolean flag stating whether the
4556 cursor was at each position. Doing that would waste space, would make
4557 it difficult to find the cursor in order to do anything with it, and
4558 would introduce the potential for synchronisation bugs in which you
4559 ended up with two cursors or none. The obviously sensible way to store a
4560 cursor in the `game_ui' is to have fields directly encoding the cursor's
4563 However, it is a mistake to assume that the same logic applies to the
4564 `game_drawstate'. If you replicate the cursor position fields in the
4565 draw state, the redraw code will get very complicated. In the draw
4566 state, in fact, it _is_ probably the right thing to have a cursor flag
4567 for every position in the grid. You probably have an array for the whole
4568 grid in the drawstate already (stating what is currently displayed in
4569 the window at each position); the sensible approach is to add a `cursor'
4570 flag to each element of that array. Then the main redraw loop will look
4571 something like this (pseudo-code):
4573 for (y = 0; y < h; y++) {
4574 for (x = 0; x < w; x++) {
4575 int value = state->symbol_at_position[y][x];
4576 if (x == ui->cursor_x && y == ui->cursor_y)
4578 if (ds->symbol_at_position[y][x] != value) {
4579 symbol_drawing_subroutine(dr, ds, x, y, value);
4580 ds->symbol_at_position[y][x] = value;
4585 This loop is very simple, pretty hard to get wrong, and _automatically_
4586 deals both with erasing the previous cursor and drawing the new one,
4587 with no special case code required.
4589 This type of loop is generally a sensible way to write a redraw
4590 function, in fact. The best thing is to ensure that the information
4591 stored in the draw state for each position tells you _everything_ about
4592 what was drawn there. A good way to ensure that is to pass precisely
4593 the same information, and _only_ that information, to a subroutine that
4594 does the actual drawing; then you know there's no additional information
4595 which affects the drawing but which you don't notice changes in.
4597 6.3.2. Implementing a keyboard-controlled cursor
4598 ------------------------------------------------
4600 It is often useful to provide a keyboard control method in a basically
4601 mouse-controlled game. A keyboard-controlled cursor is best implemented
4602 by storing its location in the `game_ui' (since if it were in the
4603 `game_state' then the user would have to separately undo every cursor
4604 move operation). So the procedure would be:
4606 - Put cursor position fields in the `game_ui'.
4608 - interpret_move() responds to arrow keys by modifying the cursor
4609 position fields and returning "".
4611 - interpret_move() responds to some sort of fire button by actually
4612 performing a move based on the current cursor location.
4614 - You might want an additional `game_ui' field stating whether the
4615 cursor is currently visible, and having it disappear when a mouse
4616 action occurs (so that it doesn't clutter the display when not
4619 - You might also want to automatically hide the cursor in
4620 changed_state() when the current game state changes to one in
4621 which there is no move to make (which is the case in some types of
4624 - redraw() draws the cursor using the technique described in section
4627 6.3.3. Implementing draggable sprites
4628 -------------------------------------
4630 Some games have a user interface which involves dragging some sort of
4631 game element around using the mouse. If you need to show a graphic
4632 moving smoothly over the top of other graphics, use a blitter (see
4633 section 3.1.13 for the blitter API) to save the background underneath
4634 it. The typical scenario goes:
4636 - Have a blitter field in the `game_drawstate'.
4638 - Set the blitter field to NULL in the game's new_drawstate()
4639 function, since you don't yet know how big the piece of saved
4640 background needs to be.
4642 - In the game's set_size() function, once you know the size of the
4643 object you'll be dragging around the display and hence the required
4644 size of the blitter, actually allocate the blitter.
4646 - In free_drawstate(), free the blitter if it's not NULL.
4648 - In interpret_move(), respond to mouse-down and mouse-drag events by
4649 updating some fields in the game_ui which indicate that a drag is in
4652 - At the _very end_ of redraw(), after all other drawing has been
4653 done, draw the moving object if there is one. First save the
4654 background under the object in the blitter; then set a clip
4655 rectangle covering precisely the area you just saved (just in case
4656 anti-aliasing or some other error causes your drawing to go beyond
4657 the area you saved). Then draw the object, and call unclip().
4658 Finally, set a flag in the game_drawstate that indicates that the
4659 blitter needs restoring.
4661 - At the very start of redraw(), before doing anything else at all,
4662 check the flag in the game_drawstate, and if it says the blitter
4663 needs restoring then restore it. (Then clear the flag, so that this
4664 won't happen again in the next redraw if no moving object is drawn
4667 This way, you will be able to write the rest of the redraw function
4668 completely ignoring the dragged object, as if it were floating above
4669 your bitmap and being completely separate.
4671 6.3.4. Sharing large invariant data between all game states
4672 -----------------------------------------------------------
4674 In some puzzles, there is a large amount of data which never changes
4675 between game states. The array of numbers in Dominosa is a good example.
4677 You _could_ dynamically allocate a copy of that array in every
4678 `game_state', and have dup_game() make a fresh copy of it for every new
4679 `game_state'; but it would waste memory and time. A more efficient way
4680 is to use a reference-counted structure.
4682 - Define a structure type containing the data in question, and also
4683 containing an integer reference count.
4685 - Have a field in `game_state' which is a pointer to this structure.
4687 - In new_game(), when creating a fresh game state at the start of a
4688 new game, create an instance of this structure, initialise it with
4689 the invariant data, and set its reference count to 1.
4691 - In dup_game(), rather than making a copy of the structure for the
4692 new game state, simply set the new game state to point at the same
4693 copy of the structure, and increment its reference count.
4695 - In free_game(), decrement the reference count in the structure
4696 pointed to by the game state; if the count reaches zero, free the
4699 This way, the invariant data will persist for only as long as it's
4700 genuinely needed; _as soon_ as the last game state for a particular
4701 puzzle instance is freed, the invariant data for that puzzle will
4702 vanish as well. Reference counting is a very efficient form of garbage
4703 collection, when it works at all. (Which it does in this instance, of
4704 course, because there's no possibility of circular references.)
4706 6.3.5. Implementing multiple types of flash
4707 -------------------------------------------
4709 In some games you need to flash in more than one different way. Mines,
4710 for example, flashes white when you win, and flashes red when you tread
4713 The simple way to do this is:
4715 - Have a field in the `game_ui' which describes the type of flash.
4717 - In flash_length(), examine the old and new game states to decide
4718 whether a flash is required and what type. Write the type of flash
4719 to the `game_ui' field whenever you return non-zero.
4721 - In redraw(), when you detect that `flash_time' is non-zero, examine
4722 the field in `game_ui' to decide which type of flash to draw.
4724 redraw() will never be called with `flash_time' non-zero unless
4725 flash_length() was first called to tell the mid-end that a flash was
4726 required; so whenever redraw() notices that `flash_time' is non-zero,
4727 you can be sure that the field in `game_ui' is correctly set.
4729 6.3.6. Animating game moves
4730 ---------------------------
4732 A number of puzzle types benefit from a quick animation of each move you
4735 For some games, such as Fifteen, this is particularly easy. Whenever
4736 redraw() is called with `oldstate' non-NULL, Fifteen simply compares the
4737 position of each tile in the two game states, and if the tile is not in
4738 the same place then it draws it some fraction of the way from its old
4739 position to its new position. This method copes automatically with undo.
4741 Other games are less obvious. In Sixteen, for example, you can't just
4742 draw each tile a fraction of the way from its old to its new position:
4743 if you did that, the end tile would zip very rapidly past all the others
4744 to get to the other end and that would look silly. (Worse, it would look
4745 inconsistent if the end tile was drawn on top going one way and on the
4746 bottom going the other way.)
4748 A useful trick here is to define a field or two in the game state that
4749 indicates what the last move was.
4751 - Add a `last move' field to the `game_state' (or two or more fields
4752 if the move is complex enough to need them).
4754 - new_game() initialises this field to a null value for a new game
4757 - execute_move() sets up the field to reflect the move it just
4760 - redraw() now needs to examine its `dir' parameter. If `dir' is
4761 positive, it determines the move being animated by looking at the
4762 last-move field in `newstate'; but if `dir' is negative, it has to
4763 look at the last-move field in `oldstate', and invert whatever move
4766 Note also that Sixteen needs to store the _direction_ of the move,
4767 because you can't quite determine it by examining the row or column in
4768 question. You can in almost all cases, but when the row is precisely
4769 two squares long it doesn't work since a move in either direction looks
4770 the same. (You could argue that since moving a 2-element row left and
4771 right has the same effect, it doesn't matter which one you animate; but
4772 in fact it's very disorienting to click the arrow left and find the row
4773 moving right, and almost as bad to undo a move to the right and find the
4774 game animating _another_ move to the right.)
4776 6.3.7. Animating drag operations
4777 --------------------------------
4779 In Untangle, moves are made by dragging a node from an old position to a
4780 new position. Therefore, at the time when the move is initially made, it
4781 should not be animated, because the node has already been dragged to the
4782 right place and doesn't need moving there. However, it's nice to animate
4783 the same move if it's later undone or redone. This requires a bit of
4786 The obvious approach is to have a flag in the `game_ui' which inhibits
4787 move animation, and to set that flag in interpret_move(). The question
4788 is, when would the flag be reset again? The obvious place to do so
4789 is changed_state(), which will be called once per move. But it will
4790 be called _before_ anim_length(), so if it resets the flag then
4791 anim_length() will never see the flag set at all.
4793 The solution is to have _two_ flags in a queue.
4795 - Define two flags in `game_ui'; let's call them `current' and `next'.
4797 - Set both to FALSE in `new_ui()'.
4799 - When a drag operation completes in interpret_move(), set the `next'
4802 - Every time changed_state() is called, set the value of `current' to
4803 the value in `next', and then set the value of `next' to FALSE.
4805 - That way, `current' will be TRUE _after_ a call to changed_state()
4806 if and only if that call to changed_state() was the result of a
4807 drag operation processed by interpret_move(). Any other call to
4808 changed_state(), due to an Undo or a Redo or a Restart or a Solve,
4809 will leave `current' FALSE.
4811 - So now anim_length() can request a move animation if and only if the
4812 `current' flag is _not_ set.
4814 6.3.8. Inhibiting the victory flash when Solve is used
4815 ------------------------------------------------------
4817 Many games flash when you complete them, as a visual congratulation for
4818 having got to the end of the puzzle. It often seems like a good idea to
4819 disable that flash when the puzzle is brought to a solved state by means
4820 of the Solve operation.
4822 This is easily done:
4824 - Add a `cheated' flag to the `game_state'.
4826 - Set this flag to FALSE in new_game().
4828 - Have solve() return a move description string which clearly
4829 identifies the move as a solve operation.
4831 - Have execute_move() respond to that clear identification by setting
4832 the `cheated' flag in the returned `game_state'. The flag will
4833 then be propagated to all subsequent game states, even if the user
4834 continues fiddling with the game after it is solved.
4836 - flash_length() now returns non-zero if `oldstate' is not completed
4837 and `newstate' is, _and_ neither state has the `cheated' flag set.
4839 6.4. Things to test once your puzzle is written
4840 -----------------------------------------------
4842 Puzzle implementations written in this framework are self-testing as far
4843 as I could make them.
4845 Textual game and move descriptions, for example, are generated and
4846 parsed as part of the normal process of play. Therefore, if you can make
4847 moves in the game _at all_ you can be reasonably confident that the
4848 mid-end serialisation interface will function correctly and you will
4849 be able to save your game. (By contrast, if I'd stuck with a single
4850 make_move() function performing the jobs of both interpret_move() and
4851 execute_move(), and had separate functions to encode and decode a game
4852 state in string form, then those functions would not be used during
4853 normal play; so they could have been completely broken, and you'd never
4854 know it until you tried to save the game - which would have meant you'd
4855 have to test game saving _extensively_ and make sure to test every
4856 possible type of game state. As an added bonus, doing it the way I did
4857 leads to smaller save files.)
4859 There is one exception to this, which is the string encoding of the
4860 `game_ui'. Most games do not store anything permanent in the `game_ui',
4861 and hence do not need to put anything in its encode and decode
4862 functions; but if there is anything in there, you do need to test game
4863 loading and saving to ensure those functions work properly.
4865 It's also worth testing undo and redo of all operations, to ensure that
4866 the redraw and the animations (if any) work properly. Failing to animate
4867 undo properly seems to be a common error.
4869 Other than that, just use your common sense.