chiark / gitweb /
Solve function for Inertia, using what's essentially an approximate
[sgt-puzzles.git] / inertia.c
1 /*
2  * inertia.c: Game involving navigating round a grid picking up
3  * gems.
4  * 
5  * Game rules and basic generator design by Ben Olmstead.
6  * This re-implementation was written by Simon Tatham.
7  */
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <assert.h>
13 #include <ctype.h>
14 #include <math.h>
15
16 #include "puzzles.h"
17
18 /* Used in the game_state */
19 #define BLANK   'b'
20 #define GEM     'g'
21 #define MINE    'm'
22 #define STOP    's'
23 #define WALL    'w'
24
25 /* Used in the game IDs */
26 #define START   'S'
27
28 /* Used in the game generation */
29 #define POSSGEM 'G'
30
31 /* Used only in the game_drawstate*/
32 #define UNDRAWN '?'
33
34 #define DIRECTIONS 8
35 #define DP1 (DIRECTIONS+1)
36 #define DX(dir) ( (dir) & 3 ? (((dir) & 7) > 4 ? -1 : +1) : 0 )
37 #define DY(dir) ( DX((dir)+6) )
38
39 /*
40  * Lvalue macro which expects x and y to be in range.
41  */
42 #define LV_AT(w, h, grid, x, y) ( (grid)[(y)*(w)+(x)] )
43
44 /*
45  * Rvalue macro which can cope with x and y being out of range.
46  */
47 #define AT(w, h, grid, x, y) ( (x)<0 || (x)>=(w) || (y)<0 || (y)>=(h) ? \
48                                WALL : LV_AT(w, h, grid, x, y) )
49
50 enum {
51     COL_BACKGROUND,
52     COL_OUTLINE,
53     COL_HIGHLIGHT,
54     COL_LOWLIGHT,
55     COL_PLAYER,
56     COL_DEAD_PLAYER,
57     COL_MINE,
58     COL_GEM,
59     COL_WALL,
60     COL_HINT,
61     NCOLOURS
62 };
63
64 struct game_params {
65     int w, h;
66 };
67
68 typedef struct soln {
69     int refcount;
70     int len;
71     unsigned char *list;
72 } soln;
73
74 struct game_state {
75     game_params p;
76     int px, py;
77     int gems;
78     char *grid;
79     int distance_moved;
80     int dead;
81     int cheated;
82     int solnpos;
83     soln *soln;
84 };
85
86 static game_params *default_params(void)
87 {
88     game_params *ret = snew(game_params);
89
90     ret->w = 10;
91     ret->h = 8;
92
93     return ret;
94 }
95
96 static void free_params(game_params *params)
97 {
98     sfree(params);
99 }
100
101 static game_params *dup_params(game_params *params)
102 {
103     game_params *ret = snew(game_params);
104     *ret = *params;                    /* structure copy */
105     return ret;
106 }
107
108 static const struct game_params inertia_presets[] = {
109     { 10, 8 },
110     { 15, 12 },
111     { 20, 16 },
112 };
113
114 static int game_fetch_preset(int i, char **name, game_params **params)
115 {
116     game_params p, *ret;
117     char *retname;
118     char namebuf[80];
119
120     if (i < 0 || i >= lenof(inertia_presets))
121         return FALSE;
122
123     p = inertia_presets[i];
124     ret = dup_params(&p);
125     sprintf(namebuf, "%dx%d", ret->w, ret->h);
126     retname = dupstr(namebuf);
127
128     *params = ret;
129     *name = retname;
130     return TRUE;
131 }
132
133 static void decode_params(game_params *params, char const *string)
134 {
135     params->w = params->h = atoi(string);
136     while (*string && isdigit((unsigned char)*string)) string++;
137     if (*string == 'x') {
138         string++;
139         params->h = atoi(string);
140     }
141 }
142
143 static char *encode_params(game_params *params, int full)
144 {
145     char data[256];
146
147     sprintf(data, "%dx%d", params->w, params->h);
148
149     return dupstr(data);
150 }
151
152 static config_item *game_configure(game_params *params)
153 {
154     config_item *ret;
155     char buf[80];
156
157     ret = snewn(3, config_item);
158
159     ret[0].name = "Width";
160     ret[0].type = C_STRING;
161     sprintf(buf, "%d", params->w);
162     ret[0].sval = dupstr(buf);
163     ret[0].ival = 0;
164
165     ret[1].name = "Height";
166     ret[1].type = C_STRING;
167     sprintf(buf, "%d", params->h);
168     ret[1].sval = dupstr(buf);
169     ret[1].ival = 0;
170
171     ret[2].name = NULL;
172     ret[2].type = C_END;
173     ret[2].sval = NULL;
174     ret[2].ival = 0;
175
176     return ret;
177 }
178
179 static game_params *custom_params(config_item *cfg)
180 {
181     game_params *ret = snew(game_params);
182
183     ret->w = atoi(cfg[0].sval);
184     ret->h = atoi(cfg[1].sval);
185
186     return ret;
187 }
188
189 static char *validate_params(game_params *params, int full)
190 {
191     /*
192      * Avoid completely degenerate cases which only have one
193      * row/column. We probably could generate completable puzzles
194      * of that shape, but they'd be forced to be extremely boring
195      * and at large sizes would take a while to happen upon at
196      * random as well.
197      */
198     if (params->w < 2 || params->h < 2)
199         return "Width and height must both be at least two";
200
201     /*
202      * The grid construction algorithm creates 1/5 as many gems as
203      * grid squares, and must create at least one gem to have an
204      * actual puzzle. However, an area-five grid is ruled out by
205      * the above constraint, so the practical minimum is six.
206      */
207     if (params->w * params->h < 6)
208         return "Grid area must be at least six squares";
209
210     return NULL;
211 }
212
213 /* ----------------------------------------------------------------------
214  * Solver used by grid generator.
215  */
216
217 struct solver_scratch {
218     unsigned char *reachable_from, *reachable_to;
219     int *positions;
220 };
221
222 static struct solver_scratch *new_scratch(int w, int h)
223 {
224     struct solver_scratch *sc = snew(struct solver_scratch);
225
226     sc->reachable_from = snewn(w * h * DIRECTIONS, unsigned char);
227     sc->reachable_to = snewn(w * h * DIRECTIONS, unsigned char);
228     sc->positions = snewn(w * h * DIRECTIONS, int);
229
230     return sc;
231 }
232
233 static void free_scratch(struct solver_scratch *sc)
234 {
235     sfree(sc->reachable_from);
236     sfree(sc->reachable_to);
237     sfree(sc->positions);
238     sfree(sc);
239 }
240
241 static int can_go(int w, int h, char *grid,
242                   int x1, int y1, int dir1, int x2, int y2, int dir2)
243 {
244     /*
245      * Returns TRUE if we can transition directly from (x1,y1)
246      * going in direction dir1, to (x2,y2) going in direction dir2.
247      */
248
249     /*
250      * If we're actually in the middle of an unoccupyable square,
251      * we cannot make any move.
252      */
253     if (AT(w, h, grid, x1, y1) == WALL ||
254         AT(w, h, grid, x1, y1) == MINE)
255         return FALSE;
256
257     /*
258      * If a move is capable of stopping at x1,y1,dir1, and x2,y2 is
259      * the same coordinate as x1,y1, then we can make the
260      * transition (by stopping and changing direction).
261      * 
262      * For this to be the case, we have to either have a wall
263      * beyond x1,y1,dir1, or have a stop on x1,y1.
264      */
265     if (x2 == x1 && y2 == y1 &&
266         (AT(w, h, grid, x1, y1) == STOP ||
267          AT(w, h, grid, x1, y1) == START ||
268          AT(w, h, grid, x1+DX(dir1), y1+DY(dir1)) == WALL))
269         return TRUE;
270
271     /*
272      * If a move is capable of continuing here, then x1,y1,dir1 can
273      * move one space further on.
274      */
275     if (x2 == x1+DX(dir1) && y2 == y1+DY(dir1) && dir1 == dir2 &&
276         (AT(w, h, grid, x2, y2) == BLANK ||
277          AT(w, h, grid, x2, y2) == GEM ||
278          AT(w, h, grid, x2, y2) == STOP ||
279          AT(w, h, grid, x2, y2) == START))
280         return TRUE;
281
282     /*
283      * That's it.
284      */
285     return FALSE;
286 }
287
288 static int find_gem_candidates(int w, int h, char *grid,
289                                struct solver_scratch *sc)
290 {
291     int wh = w*h;
292     int head, tail;
293     int sx, sy, gx, gy, gd, pass, possgems;
294
295     /*
296      * This function finds all the candidate gem squares, which are
297      * precisely those squares which can be picked up on a loop
298      * from the starting point back to the starting point. Doing
299      * this may involve passing through such a square in the middle
300      * of a move; so simple breadth-first search over the _squares_
301      * of the grid isn't quite adequate, because it might be that
302      * we can only reach a gem from the start by moving over it in
303      * one direction, but can only return to the start if we were
304      * moving over it in another direction.
305      * 
306      * Instead, we BFS over a space which mentions each grid square
307      * eight times - once for each direction. We also BFS twice:
308      * once to find out what square+direction pairs we can reach
309      * _from_ the start point, and once to find out what pairs we
310      * can reach the start point from. Then a square is reachable
311      * if any of the eight directions for that square has both
312      * flags set.
313      */
314
315     memset(sc->reachable_from, 0, wh * DIRECTIONS);
316     memset(sc->reachable_to, 0, wh * DIRECTIONS);
317
318     /*
319      * Find the starting square.
320      */
321     sx = -1;                           /* placate optimiser */
322     for (sy = 0; sy < h; sy++) {
323         for (sx = 0; sx < w; sx++)
324             if (AT(w, h, grid, sx, sy) == START)
325                 break;
326         if (sx < w)
327             break;
328     }
329     assert(sy < h);
330
331     for (pass = 0; pass < 2; pass++) {
332         unsigned char *reachable = (pass == 0 ? sc->reachable_from :
333                                     sc->reachable_to);
334         int sign = (pass == 0 ? +1 : -1);
335         int dir;
336
337 #ifdef SOLVER_DIAGNOSTICS
338         printf("starting pass %d\n", pass);
339 #endif
340
341         /*
342          * `head' and `tail' are indices within sc->positions which
343          * track the list of board positions left to process.
344          */
345         head = tail = 0;
346         for (dir = 0; dir < DIRECTIONS; dir++) {
347             int index = (sy*w+sx)*DIRECTIONS+dir;
348             sc->positions[tail++] = index;
349             reachable[index] = TRUE;
350 #ifdef SOLVER_DIAGNOSTICS
351             printf("starting point %d,%d,%d\n", sx, sy, dir);
352 #endif
353         }
354
355         /*
356          * Now repeatedly pick an element off the list and process
357          * it.
358          */
359         while (head < tail) {
360             int index = sc->positions[head++];
361             int dir = index % DIRECTIONS;
362             int x = (index / DIRECTIONS) % w;
363             int y = index / (w * DIRECTIONS);
364             int n, x2, y2, d2, i2;
365
366 #ifdef SOLVER_DIAGNOSTICS
367             printf("processing point %d,%d,%d\n", x, y, dir);
368 #endif
369             /*
370              * The places we attempt to switch to here are:
371              *  - each possible direction change (all the other
372              *    directions in this square)
373              *  - one step further in the direction we're going (or
374              *    one step back, if we're in the reachable_to pass).
375              */
376             for (n = -1; n < DIRECTIONS; n++) {
377                 if (n < 0) {
378                     x2 = x + sign * DX(dir);
379                     y2 = y + sign * DY(dir);
380                     d2 = dir;
381                 } else {
382                     x2 = x;
383                     y2 = y;
384                     d2 = n;
385                 }
386                 i2 = (y2*w+x2)*DIRECTIONS+d2;
387                 if (x2 >= 0 && x2 < w &&
388                     y2 >= 0 && y2 < h &&
389                     !reachable[i2]) {
390                     int ok;
391 #ifdef SOLVER_DIAGNOSTICS
392                     printf("  trying point %d,%d,%d", x2, y2, d2);
393 #endif
394                     if (pass == 0)
395                         ok = can_go(w, h, grid, x, y, dir, x2, y2, d2);
396                     else
397                         ok = can_go(w, h, grid, x2, y2, d2, x, y, dir);
398 #ifdef SOLVER_DIAGNOSTICS
399                     printf(" - %sok\n", ok ? "" : "not ");
400 #endif
401                     if (ok) {
402                         sc->positions[tail++] = i2;
403                         reachable[i2] = TRUE;
404                     }
405                 }
406             }
407         }
408     }
409
410     /*
411      * And that should be it. Now all we have to do is find the
412      * squares for which there exists _some_ direction such that
413      * the square plus that direction form a tuple which is both
414      * reachable from the start and reachable to the start.
415      */
416     possgems = 0;
417     for (gy = 0; gy < h; gy++)
418         for (gx = 0; gx < w; gx++)
419             if (AT(w, h, grid, gx, gy) == BLANK) {
420                 for (gd = 0; gd < DIRECTIONS; gd++) {
421                     int index = (gy*w+gx)*DIRECTIONS+gd;
422                     if (sc->reachable_from[index] && sc->reachable_to[index]) {
423 #ifdef SOLVER_DIAGNOSTICS
424                         printf("space at %d,%d is reachable via"
425                                " direction %d\n", gx, gy, gd);
426 #endif
427                         LV_AT(w, h, grid, gx, gy) = POSSGEM;
428                         possgems++;
429                         break;
430                     }
431                 }
432             }
433
434     return possgems;
435 }
436
437 /* ----------------------------------------------------------------------
438  * Grid generation code.
439  */
440
441 static char *gengrid(int w, int h, random_state *rs)
442 {
443     int wh = w*h;
444     char *grid = snewn(wh+1, char);
445     struct solver_scratch *sc = new_scratch(w, h);
446     int maxdist_threshold, tries;
447
448     maxdist_threshold = 2;
449     tries = 0;
450
451     while (1) {
452         int i, j;
453         int possgems;
454         int *dist, *list, head, tail, maxdist;
455
456         /*
457          * We're going to fill the grid with the five basic piece
458          * types in about 1/5 proportion. For the moment, though,
459          * we leave out the gems, because we'll put those in
460          * _after_ we run the solver to tell us where the viable
461          * locations are.
462          */
463         i = 0;
464         for (j = 0; j < wh/5; j++)
465             grid[i++] = WALL;
466         for (j = 0; j < wh/5; j++)
467             grid[i++] = STOP;
468         for (j = 0; j < wh/5; j++)
469             grid[i++] = MINE;
470         assert(i < wh);
471         grid[i++] = START;
472         while (i < wh)
473             grid[i++] = BLANK;
474         shuffle(grid, wh, sizeof(*grid), rs);
475
476         /*
477          * Find the viable gem locations, and immediately give up
478          * and try again if there aren't enough of them.
479          */
480         possgems = find_gem_candidates(w, h, grid, sc);
481         if (possgems < wh/5)
482             continue;
483
484         /*
485          * We _could_ now select wh/5 of the POSSGEMs and set them
486          * to GEM, and have a viable level. However, there's a
487          * chance that a large chunk of the level will turn out to
488          * be unreachable, so first we test for that.
489          * 
490          * We do this by finding the largest distance from any
491          * square to the nearest POSSGEM, by breadth-first search.
492          * If this is above a critical threshold, we abort and try
493          * again.
494          * 
495          * (This search is purely geometric, without regard to
496          * walls and long ways round.)
497          */
498         dist = sc->positions;
499         list = sc->positions + wh;
500         for (i = 0; i < wh; i++)
501             dist[i] = -1;
502         head = tail = 0;
503         for (i = 0; i < wh; i++)
504             if (grid[i] == POSSGEM) {
505                 dist[i] = 0;
506                 list[tail++] = i;
507             }
508         maxdist = 0;
509         while (head < tail) {
510             int pos, x, y, d;
511
512             pos = list[head++];
513             if (maxdist < dist[pos])
514                 maxdist = dist[pos];
515
516             x = pos % w;
517             y = pos / w;
518
519             for (d = 0; d < DIRECTIONS; d++) {
520                 int x2, y2, p2;
521
522                 x2 = x + DX(d);
523                 y2 = y + DY(d);
524
525                 if (x2 >= 0 && x2 < w && y2 >= 0 && y2 < h) {
526                     p2 = y2*w+x2;
527                     if (dist[p2] < 0) {
528                         dist[p2] = dist[pos] + 1;
529                         list[tail++] = p2;
530                     }
531                 }
532             }
533         }
534         assert(head == wh && tail == wh);
535
536         /*
537          * Now abandon this grid and go round again if maxdist is
538          * above the required threshold.
539          * 
540          * We can safely start the threshold as low as 2. As we
541          * accumulate failed generation attempts, we gradually
542          * raise it as we get more desperate.
543          */
544         if (maxdist > maxdist_threshold) {
545             tries++;
546             if (tries == 50) {
547                 maxdist_threshold++;
548                 tries = 0;
549             }
550             continue;
551         }
552
553         /*
554          * Now our reachable squares are plausibly evenly
555          * distributed over the grid. I'm not actually going to
556          * _enforce_ that I place the gems in such a way as not to
557          * increase that maxdist value; I'm now just going to trust
558          * to the RNG to pick a sensible subset of the POSSGEMs.
559          */
560         j = 0;
561         for (i = 0; i < wh; i++)
562             if (grid[i] == POSSGEM)
563                 list[j++] = i;
564         shuffle(list, j, sizeof(*list), rs);
565         for (i = 0; i < j; i++)
566             grid[list[i]] = (i < wh/5 ? GEM : BLANK);
567         break;
568     }
569
570     free_scratch(sc);
571
572     grid[wh] = '\0';
573
574     return grid;
575 }
576
577 static char *new_game_desc(game_params *params, random_state *rs,
578                            char **aux, int interactive)
579 {
580     return gengrid(params->w, params->h, rs);
581 }
582
583 static char *validate_desc(game_params *params, char *desc)
584 {
585     int w = params->w, h = params->h, wh = w*h;
586     int starts = 0, gems = 0, i;
587
588     for (i = 0; i < wh; i++) {
589         if (!desc[i])
590             return "Not enough data to fill grid";
591         if (desc[i] != WALL && desc[i] != START && desc[i] != STOP &&
592             desc[i] != GEM && desc[i] != MINE && desc[i] != BLANK)
593             return "Unrecognised character in game description";
594         if (desc[i] == START)
595             starts++;
596         if (desc[i] == GEM)
597             gems++;
598     }
599     if (desc[i])
600         return "Too much data to fill grid";
601     if (starts < 1)
602         return "No starting square specified";
603     if (starts > 1)
604         return "More than one starting square specified";
605     if (gems < 1)
606         return "No gems specified";
607
608     return NULL;
609 }
610
611 static game_state *new_game(midend *me, game_params *params, char *desc)
612 {
613     int w = params->w, h = params->h, wh = w*h;
614     int i;
615     game_state *state = snew(game_state);
616
617     state->p = *params;                /* structure copy */
618
619     state->grid = snewn(wh, char);
620     assert(strlen(desc) == wh);
621     memcpy(state->grid, desc, wh);
622
623     state->px = state->py = -1;
624     state->gems = 0;
625     for (i = 0; i < wh; i++) {
626         if (state->grid[i] == START) {
627             state->grid[i] = STOP;
628             state->px = i % w;
629             state->py = i / w;
630         } else if (state->grid[i] == GEM) {
631             state->gems++;
632         }
633     }
634
635     assert(state->gems > 0);
636     assert(state->px >= 0 && state->py >= 0);
637
638     state->distance_moved = 0;
639     state->dead = FALSE;
640
641     state->cheated = FALSE;
642     state->solnpos = 0;
643     state->soln = NULL;
644
645     return state;
646 }
647
648 static game_state *dup_game(game_state *state)
649 {
650     int w = state->p.w, h = state->p.h, wh = w*h;
651     game_state *ret = snew(game_state);
652
653     ret->p = state->p;
654     ret->px = state->px;
655     ret->py = state->py;
656     ret->gems = state->gems;
657     ret->grid = snewn(wh, char);
658     ret->distance_moved = state->distance_moved;
659     ret->dead = FALSE;
660     memcpy(ret->grid, state->grid, wh);
661     ret->cheated = state->cheated;
662     ret->soln = state->soln;
663     if (ret->soln)
664         ret->soln->refcount++;
665     ret->solnpos = state->solnpos;
666
667     return ret;
668 }
669
670 static void free_game(game_state *state)
671 {
672     if (state->soln && --state->soln->refcount == 0) {
673         sfree(state->soln->list);
674         sfree(state->soln);
675     }
676     sfree(state->grid);
677     sfree(state);
678 }
679
680 /*
681  * Internal function used by solver.
682  */
683 static int move_goes_to(int w, int h, char *grid, int x, int y, int d)
684 {
685     int dr;
686
687     /*
688      * See where we'd get to if we made this move.
689      */
690     dr = -1;                           /* placate optimiser */
691     while (1) {
692         if (AT(w, h, grid, x+DX(d), y+DY(d)) == WALL) {
693             dr = DIRECTIONS;           /* hit a wall, so end up stationary */
694             break;
695         }
696         x += DX(d);
697         y += DY(d);
698         if (AT(w, h, grid, x, y) == STOP) {
699             dr = DIRECTIONS;           /* hit a stop, so end up stationary */
700             break;
701         }
702         if (AT(w, h, grid, x, y) == GEM) {
703             dr = d;                    /* hit a gem, so we're still moving */
704             break;
705         }
706         if (AT(w, h, grid, x, y) == MINE)
707             return -1;                 /* hit a mine, so move is invalid */
708     }
709     assert(dr >= 0);
710     return (y*w+x)*DP1+dr;
711 }
712
713 static int compare_integers(const void *av, const void *bv)
714 {
715     const int *a = (const int *)av;
716     const int *b = (const int *)bv;
717     if (*a < *b)
718         return -1;
719     else if (*a > *b)
720         return +1;
721     else
722         return 0;
723 }
724
725 static char *solve_game(game_state *state, game_state *currstate,
726                         char *aux, char **error)
727 {
728     int w = state->p.w, h = state->p.h, wh = w*h;
729     int *nodes, *nodeindex, *edges, *backedges, *edgei, *backedgei, *circuit;
730     int nedges;
731     int *dist, *dist2, *list;
732     int *unvisited;
733     int circuitlen, circuitsize;
734     int head, tail, pass, i, j, n, x, y, d, dd;
735     char *err, *soln, *p;
736
737     /*
738      * Solving Inertia is a question of first building up the graph
739      * of where you can get to from where, and secondly finding a
740      * tour of the graph which takes in every gem.
741      * 
742      * This is of course a close cousin of the travelling salesman
743      * problem, which is NP-complete; so I rather doubt that any
744      * _optimal_ tour can be found in plausible time. Hence I'll
745      * restrict myself to merely finding a not-too-bad one.
746      * 
747      * First construct the graph, by bfsing out move by move from
748      * the current player position. Graph vertices will be
749      *  - every endpoint of a move (place the ball can be
750      *    stationary)
751      *  - every gem (place the ball can go through in motion).
752      *    Vertices of this type have an associated direction, since
753      *    if a gem can be collected by sliding through it in two
754      *    different directions it doesn't follow that you can
755      *    change direction at it.
756      * 
757      * I'm going to refer to a non-directional vertex as
758      * (y*w+x)*DP1+DIRECTIONS, and a directional one as
759      * (y*w+x)*DP1+d.
760      */
761
762     /*
763      * nodeindex[] maps node codes as shown above to numeric
764      * indices in the nodes[] array.
765      */
766     nodeindex = snewn(DP1*wh, int);
767     for (i = 0; i < DP1*wh; i++)
768         nodeindex[i] = -1;
769
770     /*
771      * Do the bfs to find all the interesting graph nodes.
772      */
773     nodes = snewn(DP1*wh, int);
774     head = tail = 0;
775
776     nodes[tail] = (currstate->py * w + currstate->px) * DP1 + DIRECTIONS;
777     nodeindex[nodes[0]] = tail;
778     tail++;
779
780     while (head < tail) {
781         int nc = nodes[head++], nnc;
782
783         d = nc % DP1;
784
785         /*
786          * Plot all possible moves from this node. If the node is
787          * directed, there's only one.
788          */
789         for (dd = 0; dd < DIRECTIONS; dd++) {
790             x = nc / DP1;
791             y = x / w;
792             x %= w;
793
794             if (d < DIRECTIONS && d != dd)
795                 continue;
796
797             nnc = move_goes_to(w, h, currstate->grid, x, y, dd);
798             if (nnc >= 0 && nnc != nc) {
799                 if (nodeindex[nnc] < 0) {
800                     nodes[tail] = nnc;
801                     nodeindex[nnc] = tail;
802                     tail++;
803                 }
804             }
805         }
806     }
807     n = head;
808
809     /*
810      * Now we know how many nodes we have, allocate the edge array
811      * and go through setting up the edges.
812      */
813     edges = snewn(DIRECTIONS*n, int);
814     edgei = snewn(n+1, int);
815     nedges = 0;
816
817     for (i = 0; i < n; i++) {
818         int nc = nodes[i];
819
820         edgei[i] = nedges;
821
822         d = nc % DP1;
823         x = nc / DP1;
824         y = x / w;
825         x %= w;
826
827         for (dd = 0; dd < DIRECTIONS; dd++) {
828             int nnc;
829
830             if (d >= DIRECTIONS || d == dd) {
831                 nnc = move_goes_to(w, h, currstate->grid, x, y, dd);
832
833                 if (nnc >= 0 && nnc != nc)
834                     edges[nedges++] = nodeindex[nnc];
835             }
836         }
837     }
838     edgei[n] = nedges;
839
840     /*
841      * Now set up the backedges array.
842      */
843     backedges = snewn(nedges, int);
844     backedgei = snewn(n+1, int);
845     for (i = j = 0; i < nedges; i++) {
846         while (j+1 < n && i >= edgei[j+1])
847             j++;
848         backedges[i] = edges[i] * n + j;
849     }
850     qsort(backedges, nedges, sizeof(int), compare_integers);
851     backedgei[0] = 0;
852     for (i = j = 0; i < nedges; i++) {
853         int k = backedges[i] / n;
854         backedges[i] %= n;
855         while (j < k)
856             backedgei[++j] = i;
857     }
858     backedgei[n] = nedges;
859
860     /*
861      * Set up the initial tour. At all times, our tour is a circuit
862      * of graph vertices (which may, and probably will often,
863      * repeat vertices). To begin with, it's got exactly one vertex
864      * in it, which is the player's current starting point.
865      */
866     circuitsize = 256;
867     circuit = snewn(circuitsize, int);
868     circuitlen = 0;
869     circuit[circuitlen++] = 0;         /* node index 0 is the starting posn */
870
871     /*
872      * Track which gems are as yet unvisited.
873      */
874     unvisited = snewn(wh, int);
875     for (i = 0; i < wh; i++)
876         unvisited[i] = FALSE;
877     for (i = 0; i < wh; i++)
878         if (currstate->grid[i] == GEM)
879             unvisited[i] = TRUE;
880
881     /*
882      * Allocate space for doing bfses inside the main loop.
883      */
884     dist = snewn(n, int);
885     dist2 = snewn(n, int);
886     list = snewn(n, int);
887
888     err = NULL;
889     soln = NULL;
890
891     /*
892      * Now enter the main loop, in each iteration of which we
893      * extend the tour to take in an as yet uncollected gem.
894      */
895     while (1) {
896         int target, n1, n2, bestdist, extralen, targetpos;
897
898 #ifdef TSP_DIAGNOSTICS
899         printf("circuit is");
900         for (i = 0; i < circuitlen; i++) {
901             int nc = nodes[circuit[i]];
902             printf(" (%d,%d,%d)", nc/DP1%w, nc/(DP1*w), nc%DP1);
903         }
904         printf("\n");
905         printf("moves are ");
906         x = nodes[circuit[0]] / DP1 % w;
907         y = nodes[circuit[0]] / DP1 / w;
908         for (i = 1; i < circuitlen; i++) {
909             int x2, y2, dx, dy;
910             if (nodes[circuit[i]] % DP1 != DIRECTIONS)
911                 continue;
912             x2 = nodes[circuit[i]] / DP1 % w;
913             y2 = nodes[circuit[i]] / DP1 / w;
914             dx = (x2 > x ? +1 : x2 < x ? -1 : 0);
915             dy = (y2 > y ? +1 : y2 < y ? -1 : 0);
916             for (d = 0; d < DIRECTIONS; d++)
917                 if (DX(d) == dx && DY(d) == dy)
918                     printf("%c", "89632147"[d]);
919             x = x2;
920             y = y2;
921         }
922         printf("\n");
923 #endif
924
925         /*
926          * First, start a pair of bfses at _every_ vertex currently
927          * in the tour, and extend them outwards to find the
928          * nearest as yet unreached gem vertex.
929          * 
930          * This is largely a heuristic: we could pick _any_ doubly
931          * reachable node here and still get a valid tour as
932          * output. I hope that picking a nearby one will result in
933          * generally good tours.
934          */
935         for (pass = 0; pass < 2; pass++) {
936             int *ep = (pass == 0 ? edges : backedges);
937             int *ei = (pass == 0 ? edgei : backedgei);
938             int *dp = (pass == 0 ? dist : dist2);
939             head = tail = 0;
940             for (i = 0; i < n; i++)
941                 dp[i] = -1;
942             for (i = 0; i < circuitlen; i++) {
943                 int ni = circuit[i];
944                 if (dp[ni] < 0) {
945                     dp[ni] = 0;
946                     list[tail++] = ni;
947                 }
948             }
949             while (head < tail) {
950                 int ni = list[head++];
951                 for (i = ei[ni]; i < ei[ni+1]; i++) {
952                     int ti = ep[i];
953                     if (ti >= 0 && dp[ti] < 0) {
954                         dp[ti] = dp[ni] + 1;
955                         list[tail++] = ti;
956                     }
957                 }
958             }
959         }
960         /* Now find the nearest unvisited gem. */
961         bestdist = -1;
962         target = -1;
963         for (i = 0; i < n; i++) {
964             if (unvisited[nodes[i] / DP1] &&
965                 dist[i] >= 0 && dist2[i] >= 0) {
966                 int thisdist = dist[i] + dist2[i];
967                 if (bestdist < 0 || bestdist > thisdist) {
968                     bestdist = thisdist;
969                     target = i;
970                 }
971             }
972         }
973
974         if (target < 0) {
975             /*
976              * If we get to here, we haven't found a gem we can get
977              * at all, which means we terminate this loop.
978              */
979             break;
980         }
981
982         /*
983          * Now we have a graph vertex at list[tail-1] which is an
984          * unvisited gem. We want to add that vertex to our tour.
985          * So we run two more breadth-first searches: one starting
986          * from that vertex and following forward edges, and
987          * another starting from the same vertex and following
988          * backward edges. This allows us to determine, for each
989          * node on the current tour, how quickly we can get both to
990          * and from the target vertex from that node.
991          */
992 #ifdef TSP_DIAGNOSTICS
993         printf("target node is %d (%d,%d,%d)\n", target, nodes[target]/DP1%w,
994                nodes[target]/DP1/w, nodes[target]%DP1);
995 #endif
996
997         for (pass = 0; pass < 2; pass++) {
998             int *ep = (pass == 0 ? edges : backedges);
999             int *ei = (pass == 0 ? edgei : backedgei);
1000             int *dp = (pass == 0 ? dist : dist2);
1001
1002             for (i = 0; i < n; i++)
1003                 dp[i] = -1;
1004             head = tail = 0;
1005
1006             dp[target] = 0;
1007             list[tail++] = target;
1008
1009             while (head < tail) {
1010                 int ni = list[head++];
1011                 for (i = ei[ni]; i < ei[ni+1]; i++) {
1012                     int ti = ep[i];
1013                     if (ti >= 0 && dp[ti] < 0) {
1014                         dp[ti] = dp[ni] + 1;
1015 /*printf("pass %d: set dist of vertex %d to %d (via %d)\n", pass, ti, dp[ti], ni);*/
1016                         list[tail++] = ti;
1017                     }
1018                 }
1019             }
1020         }
1021
1022         /*
1023          * Now for every node n, dist[n] gives the length of the
1024          * shortest path from the target vertex to n, and dist2[n]
1025          * gives the length of the shortest path from n to the
1026          * target vertex.
1027          * 
1028          * Our next step is to search linearly along the tour to
1029          * find the optimum place to insert a trip to the target
1030          * vertex and back. Our two options are either
1031          *  (a) to find two adjacent vertices A,B in the tour and
1032          *      replace the edge A->B with the path A->target->B
1033          *  (b) to find a single vertex X in the tour and replace
1034          *      it with the complete round trip X->target->X.
1035          * We do whichever takes the fewest moves.
1036          */
1037         n1 = n2 = -1;
1038         bestdist = -1;
1039         for (i = 0; i < circuitlen; i++) {
1040             int thisdist;
1041
1042             /*
1043              * Try a round trip from vertex i.
1044              */
1045             if (dist[circuit[i]] >= 0 &&
1046                 dist2[circuit[i]] >= 0) {
1047                 thisdist = dist[circuit[i]] + dist2[circuit[i]];
1048                 if (bestdist < 0 || thisdist < bestdist) {
1049                     bestdist = thisdist;
1050                     n1 = n2 = i;
1051                 }
1052             }
1053
1054             /*
1055              * Try a trip from vertex i via target to vertex i+1.
1056              */
1057             if (i+1 < circuitlen &&
1058                 dist2[circuit[i]] >= 0 &&
1059                 dist[circuit[i+1]] >= 0) {
1060                 thisdist = dist2[circuit[i]] + dist[circuit[i+1]];
1061                 if (bestdist < 0 || thisdist < bestdist) {
1062                     bestdist = thisdist;
1063                     n1 = i;
1064                     n2 = i+1;
1065                 }
1066             }
1067         }
1068         if (bestdist < 0) {
1069             /*
1070              * We couldn't find a round trip taking in this gem _at
1071              * all_. Give up.
1072              */
1073             err = "Unable to find a solution from this starting point";
1074             break;
1075         }
1076 #ifdef TSP_DIAGNOSTICS
1077         printf("insertion point: n1=%d, n2=%d, dist=%d\n", n1, n2, bestdist);
1078 #endif
1079
1080 #ifdef TSP_DIAGNOSTICS
1081         printf("circuit before lengthening is");
1082         for (i = 0; i < circuitlen; i++) {
1083             printf(" %d", circuit[i]);
1084         }
1085         printf("\n");
1086 #endif
1087
1088         /*
1089          * Now actually lengthen the tour to take in this round
1090          * trip.
1091          */
1092         extralen = dist2[circuit[n1]] + dist[circuit[n2]];
1093         if (n1 != n2)
1094             extralen--;
1095         circuitlen += extralen;
1096         if (circuitlen >= circuitsize) {
1097             circuitsize = circuitlen + 256;
1098             circuit = sresize(circuit, circuitsize, int);
1099         }
1100         memmove(circuit + n2 + extralen, circuit + n2,
1101                 (circuitlen - n2 - extralen) * sizeof(int));
1102         n2 += extralen;
1103
1104 #ifdef TSP_DIAGNOSTICS
1105         printf("circuit in middle of lengthening is");
1106         for (i = 0; i < circuitlen; i++) {
1107             printf(" %d", circuit[i]);
1108         }
1109         printf("\n");
1110 #endif
1111
1112         /*
1113          * Find the shortest-path routes to and from the target,
1114          * and write them into the circuit.
1115          */
1116         targetpos = n1 + dist2[circuit[n1]];
1117         assert(targetpos - dist2[circuit[n1]] == n1);
1118         assert(targetpos + dist[circuit[n2]] == n2);
1119         for (pass = 0; pass < 2; pass++) {
1120             int dir = (pass == 0 ? -1 : +1);
1121             int *ep = (pass == 0 ? backedges : edges);
1122             int *ei = (pass == 0 ? backedgei : edgei);
1123             int *dp = (pass == 0 ? dist : dist2);
1124             int nn = (pass == 0 ? n2 : n1);
1125             int ni = circuit[nn], ti, dest = nn;
1126
1127             while (1) {
1128                 circuit[dest] = ni;
1129                 if (dp[ni] == 0)
1130                     break;
1131                 dest += dir;
1132                 ti = -1;
1133 /*printf("pass %d: looking at vertex %d\n", pass, ni);*/
1134                 for (i = ei[ni]; i < ei[ni+1]; i++) {
1135                     ti = ep[i];
1136                     if (ti >= 0 && dp[ti] == dp[ni] - 1)
1137                         break;
1138                 }
1139                 assert(i < ei[ni+1] && ti >= 0);
1140                 ni = ti;
1141             }
1142         }
1143
1144 #ifdef TSP_DIAGNOSTICS
1145         printf("circuit after lengthening is");
1146         for (i = 0; i < circuitlen; i++) {
1147             printf(" %d", circuit[i]);
1148         }
1149         printf("\n");
1150 #endif
1151
1152         /*
1153          * Finally, mark all gems that the new piece of circuit
1154          * passes through as visited.
1155          */
1156         for (i = n1; i <= n2; i++) {
1157             int pos = nodes[circuit[i]] / DP1;
1158             assert(pos >= 0 && pos < wh);
1159             unvisited[pos] = FALSE;
1160         }
1161     }
1162
1163 #ifdef TSP_DIAGNOSTICS
1164     printf("before reduction, moves are ");
1165     x = nodes[circuit[0]] / DP1 % w;
1166     y = nodes[circuit[0]] / DP1 / w;
1167     for (i = 1; i < circuitlen; i++) {
1168         int x2, y2, dx, dy;
1169         if (nodes[circuit[i]] % DP1 != DIRECTIONS)
1170             continue;
1171         x2 = nodes[circuit[i]] / DP1 % w;
1172         y2 = nodes[circuit[i]] / DP1 / w;
1173         dx = (x2 > x ? +1 : x2 < x ? -1 : 0);
1174         dy = (y2 > y ? +1 : y2 < y ? -1 : 0);
1175         for (d = 0; d < DIRECTIONS; d++)
1176             if (DX(d) == dx && DY(d) == dy)
1177                 printf("%c", "89632147"[d]);
1178         x = x2;
1179         y = y2;
1180     }
1181     printf("\n");
1182 #endif
1183
1184     /*
1185      * That's got a basic solution. Now optimise it by removing
1186      * redundant sections of the circuit: it's entirely possible
1187      * that a piece of circuit we carefully inserted at one stage
1188      * to collect a gem has become pointless because the steps
1189      * required to collect some _later_ gem necessarily passed
1190      * through the same one.
1191      * 
1192      * So first we go through and work out how many times each gem
1193      * is collected. Then we look for maximal sections of circuit
1194      * which are redundant in the sense that their removal would
1195      * not reduce any gem's collection count to zero, and replace
1196      * each one with a bfs-derived fastest path between their
1197      * endpoints.
1198      */
1199     while (1) {
1200         int oldlen = circuitlen;
1201
1202         for (i = 0; i < wh; i++)
1203             unvisited[i] = 0;
1204         for (i = 0; i < circuitlen; i++) {
1205             int xy = nodes[circuit[i]] / DP1;
1206             if (currstate->grid[xy] == GEM)
1207                 unvisited[xy]++;
1208         }
1209
1210         /*
1211          * If there's any gem we didn't end up visiting at all,
1212          * give up.
1213          */
1214         for (i = 0; i < wh; i++) {
1215             if (currstate->grid[i] == GEM && unvisited[i] == 0) {
1216                 err = "Unable to find a solution from this starting point";
1217                 break;
1218             }
1219         }
1220         if (i < wh)
1221             break;
1222
1223         for (i = j = 0; i < circuitlen; i++) {
1224             int xy = nodes[circuit[i]] / DP1;
1225             if (currstate->grid[xy] == GEM && unvisited[xy] > 1) {
1226                 unvisited[xy]--;
1227             } else if (currstate->grid[xy] == GEM || i == circuitlen-1) {
1228                 /*
1229                  * circuit[i] collects a gem for the only time, or is
1230                  * the last node in the circuit. Therefore it cannot be
1231                  * removed; so we now want to replace the path from
1232                  * circuit[j] to circuit[i] with a bfs-shortest path.
1233                  */
1234                 int k, dest, ni, ti, thisdist;
1235
1236 #ifdef TSP_DIAGNOSTICS
1237                 printf("optimising section from %d - %d\n", j, i);
1238 #endif
1239
1240                 for (k = 0; k < n; k++)
1241                     dist[k] = -1;
1242                 head = tail = 0;
1243
1244                 dist[circuit[j]] = 0;
1245                 list[tail++] = circuit[j];
1246
1247                 while (head < tail && dist[circuit[i]] < 0) {
1248                     int ni = list[head++];
1249                     for (k = edgei[ni]; k < edgei[ni+1]; k++) {
1250                         int ti = edges[k];
1251                         if (ti >= 0 && dist[ti] < 0) {
1252                             dist[ti] = dist[ni] + 1;
1253                             list[tail++] = ti;
1254                         }
1255                     }
1256                 }
1257
1258                 thisdist = dist[circuit[i]];
1259                 assert(thisdist >= 0 && thisdist <= i-j);
1260
1261                 memmove(circuit+j+thisdist, circuit+i,
1262                         (circuitlen - i) * sizeof(int));
1263                 circuitlen -= i-j;
1264                 i = j + thisdist;
1265                 circuitlen += i-j;
1266
1267 #ifdef TSP_DIAGNOSTICS
1268                 printf("new section runs from %d - %d\n", j, i);
1269 #endif
1270
1271                 dest = i;
1272                 assert(dest >= 0);
1273                 ni = circuit[i];
1274
1275                 while (1) {
1276                     /* printf("dest=%d circuitlen=%d ni=%d dist[ni]=%d\n", dest, circuitlen, ni, dist[ni]); */
1277                     circuit[dest] = ni;
1278                     if (dist[ni] == 0)
1279                         break;
1280                     dest--;
1281                     ti = -1;
1282                     for (k = backedgei[ni]; k < backedgei[ni+1]; k++) {
1283                         ti = backedges[k];
1284                         if (ti >= 0 && dist[ti] == dist[ni] - 1)
1285                             break;
1286                     }
1287                     assert(k < backedgei[ni+1] && ti >= 0);
1288                     ni = ti;
1289                 }
1290
1291                 /*
1292                  * Now re-increment the visit counts for the new
1293                  * path.
1294                  */
1295                 while (++j < i) {
1296                     int xy = nodes[circuit[j]] / DP1;
1297                     if (currstate->grid[xy] == GEM)
1298                         unvisited[xy]++;
1299                 }
1300
1301 #ifdef TSP_DIAGNOSTICS
1302                 printf("during reduction, circuit is");
1303                 for (k = 0; k < circuitlen; k++) {
1304                     int nc = nodes[circuit[k]];
1305                     printf(" (%d,%d,%d)", nc/DP1%w, nc/(DP1*w), nc%DP1);
1306                 }
1307                 printf("\n");
1308                 printf("moves are ");
1309                 x = nodes[circuit[0]] / DP1 % w;
1310                 y = nodes[circuit[0]] / DP1 / w;
1311                 for (k = 1; k < circuitlen; k++) {
1312                     int x2, y2, dx, dy;
1313                     if (nodes[circuit[k]] % DP1 != DIRECTIONS)
1314                         continue;
1315                     x2 = nodes[circuit[k]] / DP1 % w;
1316                     y2 = nodes[circuit[k]] / DP1 / w;
1317                     dx = (x2 > x ? +1 : x2 < x ? -1 : 0);
1318                     dy = (y2 > y ? +1 : y2 < y ? -1 : 0);
1319                     for (d = 0; d < DIRECTIONS; d++)
1320                         if (DX(d) == dx && DY(d) == dy)
1321                             printf("%c", "89632147"[d]);
1322                     x = x2;
1323                     y = y2;
1324                 }
1325                 printf("\n");
1326 #endif
1327             }
1328         }
1329
1330 #ifdef TSP_DIAGNOSTICS
1331         printf("after reduction, moves are ");
1332         x = nodes[circuit[0]] / DP1 % w;
1333         y = nodes[circuit[0]] / DP1 / w;
1334         for (i = 1; i < circuitlen; i++) {
1335             int x2, y2, dx, dy;
1336             if (nodes[circuit[i]] % DP1 != DIRECTIONS)
1337                 continue;
1338             x2 = nodes[circuit[i]] / DP1 % w;
1339             y2 = nodes[circuit[i]] / DP1 / w;
1340             dx = (x2 > x ? +1 : x2 < x ? -1 : 0);
1341             dy = (y2 > y ? +1 : y2 < y ? -1 : 0);
1342             for (d = 0; d < DIRECTIONS; d++)
1343                 if (DX(d) == dx && DY(d) == dy)
1344                     printf("%c", "89632147"[d]);
1345             x = x2;
1346             y = y2;
1347         }
1348         printf("\n");
1349 #endif
1350
1351         /*
1352          * If we've managed an entire reduction pass and not made
1353          * the solution any shorter, we're _really_ done.
1354          */
1355         if (circuitlen == oldlen)
1356             break;
1357     }
1358
1359     /*
1360      * Encode the solution as a move string.
1361      */
1362     if (!err) {
1363         soln = snewn(circuitlen+2, char);
1364         p = soln;
1365         *p++ = 'S';
1366         x = nodes[circuit[0]] / DP1 % w;
1367         y = nodes[circuit[0]] / DP1 / w;
1368         for (i = 1; i < circuitlen; i++) {
1369             int x2, y2, dx, dy;
1370             if (nodes[circuit[i]] % DP1 != DIRECTIONS)
1371                 continue;
1372             x2 = nodes[circuit[i]] / DP1 % w;
1373             y2 = nodes[circuit[i]] / DP1 / w;
1374             dx = (x2 > x ? +1 : x2 < x ? -1 : 0);
1375             dy = (y2 > y ? +1 : y2 < y ? -1 : 0);
1376             for (d = 0; d < DIRECTIONS; d++)
1377                 if (DX(d) == dx && DY(d) == dy) {
1378                     *p++ = '0' + d;
1379                     break;
1380                 }
1381             assert(d < DIRECTIONS);
1382             x = x2;
1383             y = y2;
1384         }
1385         *p++ = '\0';
1386         assert(p - soln < circuitlen+2);
1387     }
1388
1389     sfree(list);
1390     sfree(dist);
1391     sfree(dist2);
1392     sfree(unvisited);
1393     sfree(circuit);
1394     sfree(backedgei);
1395     sfree(backedges);
1396     sfree(edgei);
1397     sfree(edges);
1398     sfree(nodeindex);
1399     sfree(nodes);
1400
1401     if (err)
1402         *error = err;
1403
1404     return soln;
1405 }
1406
1407 static char *game_text_format(game_state *state)
1408 {
1409     return NULL;
1410 }
1411
1412 struct game_ui {
1413     float anim_length;
1414     int flashtype;
1415     int deaths;
1416     int just_made_move;
1417     int just_died;
1418 };
1419
1420 static game_ui *new_ui(game_state *state)
1421 {
1422     game_ui *ui = snew(game_ui);
1423     ui->anim_length = 0.0F;
1424     ui->flashtype = 0;
1425     ui->deaths = 0;
1426     ui->just_made_move = FALSE;
1427     ui->just_died = FALSE;
1428     return ui;
1429 }
1430
1431 static void free_ui(game_ui *ui)
1432 {
1433     sfree(ui);
1434 }
1435
1436 static char *encode_ui(game_ui *ui)
1437 {
1438     char buf[80];
1439     /*
1440      * The deaths counter needs preserving across a serialisation.
1441      */
1442     sprintf(buf, "D%d", ui->deaths);
1443     return dupstr(buf);
1444 }
1445
1446 static void decode_ui(game_ui *ui, char *encoding)
1447 {
1448     int p = 0;
1449     sscanf(encoding, "D%d%n", &ui->deaths, &p);
1450 }
1451
1452 static void game_changed_state(game_ui *ui, game_state *oldstate,
1453                                game_state *newstate)
1454 {
1455     /*
1456      * Increment the deaths counter. We only do this if
1457      * ui->just_made_move is set (redoing a suicide move doesn't
1458      * kill you _again_), and also we only do it if the game wasn't
1459      * already completed (once you're finished, you can play).
1460      */
1461     if (!oldstate->dead && newstate->dead && ui->just_made_move &&
1462         oldstate->gems) {
1463         ui->deaths++;
1464         ui->just_died = TRUE;
1465     } else {
1466         ui->just_died = FALSE;
1467     }
1468     ui->just_made_move = FALSE;
1469 }
1470
1471 struct game_drawstate {
1472     game_params p;
1473     int tilesize;
1474     int started;
1475     unsigned short *grid;
1476     blitter *player_background;
1477     int player_bg_saved, pbgx, pbgy;
1478 };
1479
1480 #define PREFERRED_TILESIZE 32
1481 #define TILESIZE (ds->tilesize)
1482 #define BORDER    (TILESIZE)
1483 #define HIGHLIGHT_WIDTH (TILESIZE / 10)
1484 #define COORD(x)  ( (x) * TILESIZE + BORDER )
1485 #define FROMCOORD(x)  ( ((x) - BORDER + TILESIZE) / TILESIZE - 1 )
1486
1487 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
1488                             int x, int y, int button)
1489 {
1490     int w = state->p.w, h = state->p.h /*, wh = w*h */;
1491     int dir;
1492     char buf[80];
1493
1494     dir = -1;
1495
1496     if (button == LEFT_BUTTON) {
1497         /*
1498          * Mouse-clicking near the target point (or, more
1499          * accurately, in the appropriate octant) is an alternative
1500          * way to input moves.
1501          */
1502
1503         if (FROMCOORD(x) != state->px || FROMCOORD(y) != state->py) {
1504             int dx, dy;
1505             float angle;
1506
1507             dx = FROMCOORD(x) - state->px;
1508             dy = FROMCOORD(y) - state->py;
1509             /* I pass dx,dy rather than dy,dx so that the octants
1510              * end up the right way round. */
1511             angle = atan2(dx, -dy);
1512
1513             angle = (angle + (PI/8)) / (PI/4);
1514             assert(angle > -16.0F);
1515             dir = (int)(angle + 16.0F) & 7;
1516         }
1517     } else if (button == CURSOR_UP || button == (MOD_NUM_KEYPAD | '8'))
1518         dir = 0;
1519     else if (button == CURSOR_DOWN || button == (MOD_NUM_KEYPAD | '2'))
1520         dir = 4;
1521     else if (button == CURSOR_LEFT || button == (MOD_NUM_KEYPAD | '4'))
1522         dir = 6;
1523     else if (button == CURSOR_RIGHT || button == (MOD_NUM_KEYPAD | '6'))
1524         dir = 2;
1525     else if (button == (MOD_NUM_KEYPAD | '7'))
1526         dir = 7;
1527     else if (button == (MOD_NUM_KEYPAD | '1'))
1528         dir = 5;
1529     else if (button == (MOD_NUM_KEYPAD | '9'))
1530         dir = 1;
1531     else if (button == (MOD_NUM_KEYPAD | '3'))
1532         dir = 3;
1533     else if (button == ' ' && state->soln && state->solnpos < state->soln->len)
1534         dir = state->soln->list[state->solnpos];
1535
1536     if (dir < 0)
1537         return NULL;
1538
1539     /*
1540      * Reject the move if we can't make it at all due to a wall
1541      * being in the way.
1542      */
1543     if (AT(w, h, state->grid, state->px+DX(dir), state->py+DY(dir)) == WALL)
1544         return NULL;
1545
1546     /*
1547      * Reject the move if we're dead!
1548      */
1549     if (state->dead)
1550         return NULL;
1551
1552     /*
1553      * Otherwise, we can make the move. All we need to specify is
1554      * the direction.
1555      */
1556     ui->just_made_move = TRUE;
1557     sprintf(buf, "%d", dir);
1558     return dupstr(buf);
1559 }
1560
1561 static game_state *execute_move(game_state *state, char *move)
1562 {
1563     int w = state->p.w, h = state->p.h /*, wh = w*h */;
1564     int dir;
1565     game_state *ret;
1566
1567     if (*move == 'S') {
1568         int len, i;
1569         soln *sol;
1570
1571         /*
1572          * This is a solve move, so we don't actually _change_ the
1573          * grid but merely set up a stored solution path.
1574          */
1575         move++;
1576         len = strlen(move);
1577         sol = snew(soln);
1578         sol->len = len;
1579         sol->list = snewn(len, unsigned char);
1580         for (i = 0; i < len; i++)
1581             sol->list[i] = move[i] - '0';
1582         ret = dup_game(state);
1583         ret->cheated = TRUE;
1584         ret->soln = sol;
1585         ret->solnpos = 0;
1586         sol->refcount = 1;
1587         return ret;
1588     }
1589
1590     dir = atoi(move);
1591     if (dir < 0 || dir >= DIRECTIONS)
1592         return NULL;                   /* huh? */
1593
1594     if (state->dead)
1595         return NULL;
1596
1597     if (AT(w, h, state->grid, state->px+DX(dir), state->py+DY(dir)) == WALL)
1598         return NULL;                   /* wall in the way! */
1599
1600     /*
1601      * Now make the move.
1602      */
1603     ret = dup_game(state);
1604     ret->distance_moved = 0;
1605     while (1) {
1606         ret->px += DX(dir);
1607         ret->py += DY(dir);
1608         ret->distance_moved++;
1609
1610         if (AT(w, h, ret->grid, ret->px, ret->py) == GEM) {
1611             LV_AT(w, h, ret->grid, ret->px, ret->py) = BLANK;
1612             ret->gems--;
1613         }
1614
1615         if (AT(w, h, ret->grid, ret->px, ret->py) == MINE) {
1616             ret->dead = TRUE;
1617             break;
1618         }
1619
1620         if (AT(w, h, ret->grid, ret->px, ret->py) == STOP ||
1621             AT(w, h, ret->grid, ret->px+DX(dir),
1622                ret->py+DY(dir)) == WALL)
1623             break;
1624     }
1625
1626     if (ret->soln) {
1627         /*
1628          * If this move is the correct next one in the stored
1629          * solution path, advance solnpos.
1630          */
1631         if (ret->soln->list[ret->solnpos] == dir &&
1632             ret->solnpos+1 < ret->soln->len) {
1633             ret->solnpos++;
1634         } else {
1635             /*
1636              * Otherwise, the user has strayed from the path, so
1637              * the path is no longer valid.
1638              */
1639             ret->soln->refcount--;
1640             assert(ret->soln->refcount > 0);/* `state' at least still exists */
1641             ret->soln = NULL;
1642             ret->solnpos = 0;
1643         }
1644     }
1645
1646     return ret;
1647 }
1648
1649 /* ----------------------------------------------------------------------
1650  * Drawing routines.
1651  */
1652
1653 static void game_compute_size(game_params *params, int tilesize,
1654                               int *x, int *y)
1655 {
1656     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1657     struct { int tilesize; } ads, *ds = &ads;
1658     ads.tilesize = tilesize;
1659
1660     *x = 2 * BORDER + 1 + params->w * TILESIZE;
1661     *y = 2 * BORDER + 1 + params->h * TILESIZE;
1662 }
1663
1664 static void game_set_size(drawing *dr, game_drawstate *ds,
1665                           game_params *params, int tilesize)
1666 {
1667     ds->tilesize = tilesize;
1668
1669     assert(!ds->player_background);    /* set_size is never called twice */
1670     assert(!ds->player_bg_saved);
1671
1672     ds->player_background = blitter_new(dr, TILESIZE, TILESIZE);
1673 }
1674
1675 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
1676 {
1677     float *ret = snewn(3 * NCOLOURS, float);
1678     int i;
1679
1680     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
1681
1682     ret[COL_OUTLINE * 3 + 0] = 0.0F;
1683     ret[COL_OUTLINE * 3 + 1] = 0.0F;
1684     ret[COL_OUTLINE * 3 + 2] = 0.0F;
1685
1686     ret[COL_PLAYER * 3 + 0] = 0.0F;
1687     ret[COL_PLAYER * 3 + 1] = 1.0F;
1688     ret[COL_PLAYER * 3 + 2] = 0.0F;
1689
1690     ret[COL_DEAD_PLAYER * 3 + 0] = 1.0F;
1691     ret[COL_DEAD_PLAYER * 3 + 1] = 0.0F;
1692     ret[COL_DEAD_PLAYER * 3 + 2] = 0.0F;
1693
1694     ret[COL_MINE * 3 + 0] = 0.0F;
1695     ret[COL_MINE * 3 + 1] = 0.0F;
1696     ret[COL_MINE * 3 + 2] = 0.0F;
1697
1698     ret[COL_GEM * 3 + 0] = 0.6F;
1699     ret[COL_GEM * 3 + 1] = 1.0F;
1700     ret[COL_GEM * 3 + 2] = 1.0F;
1701
1702     for (i = 0; i < 3; i++) {
1703         ret[COL_WALL * 3 + i] = (3 * ret[COL_BACKGROUND * 3 + i] +
1704                                  1 * ret[COL_HIGHLIGHT * 3 + i]) / 4;
1705     }
1706
1707     ret[COL_HINT * 3 + 0] = 1.0F;
1708     ret[COL_HINT * 3 + 1] = 1.0F;
1709     ret[COL_HINT * 3 + 2] = 0.0F;
1710
1711     *ncolours = NCOLOURS;
1712     return ret;
1713 }
1714
1715 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
1716 {
1717     int w = state->p.w, h = state->p.h, wh = w*h;
1718     struct game_drawstate *ds = snew(struct game_drawstate);
1719     int i;
1720
1721     ds->tilesize = 0;
1722
1723     /* We can't allocate the blitter rectangle for the player background
1724      * until we know what size to make it. */
1725     ds->player_background = NULL;
1726     ds->player_bg_saved = FALSE;
1727     ds->pbgx = ds->pbgy = -1;
1728
1729     ds->p = state->p;                  /* structure copy */
1730     ds->started = FALSE;
1731     ds->grid = snewn(wh, unsigned short);
1732     for (i = 0; i < wh; i++)
1733         ds->grid[i] = UNDRAWN;
1734
1735     return ds;
1736 }
1737
1738 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1739 {
1740     if (ds->player_background)
1741         blitter_free(dr, ds->player_background);
1742     sfree(ds->grid);
1743     sfree(ds);
1744 }
1745
1746 static void draw_player(drawing *dr, game_drawstate *ds, int x, int y,
1747                         int dead, int hintdir)
1748 {
1749     if (dead) {
1750         int coords[DIRECTIONS*4];
1751         int d;
1752
1753         for (d = 0; d < DIRECTIONS; d++) {
1754             float x1, y1, x2, y2, x3, y3, len;
1755
1756             x1 = DX(d);
1757             y1 = DY(d);
1758             len = sqrt(x1*x1+y1*y1); x1 /= len; y1 /= len;
1759
1760             x3 = DX(d+1);
1761             y3 = DY(d+1);
1762             len = sqrt(x3*x3+y3*y3); x3 /= len; y3 /= len;
1763
1764             x2 = (x1+x3) / 4;
1765             y2 = (y1+y3) / 4;
1766
1767             coords[d*4+0] = x + TILESIZE/2 + (int)((TILESIZE*3/7) * x1);
1768             coords[d*4+1] = y + TILESIZE/2 + (int)((TILESIZE*3/7) * y1);
1769             coords[d*4+2] = x + TILESIZE/2 + (int)((TILESIZE*3/7) * x2);
1770             coords[d*4+3] = y + TILESIZE/2 + (int)((TILESIZE*3/7) * y2);
1771         }
1772         draw_polygon(dr, coords, DIRECTIONS*2, COL_DEAD_PLAYER, COL_OUTLINE);
1773     } else {
1774         draw_circle(dr, x + TILESIZE/2, y + TILESIZE/2,
1775                     TILESIZE/3, COL_PLAYER, COL_OUTLINE);
1776     }
1777
1778     if (!dead && hintdir >= 0) {
1779         float scale = (DX(hintdir) && DY(hintdir) ? 0.8F : 1.0F);
1780         int ax = (TILESIZE*2/5) * scale * DX(hintdir);
1781         int ay = (TILESIZE*2/5) * scale * DY(hintdir);
1782         int px = -ay, py = ax;
1783         int ox = x + TILESIZE/2, oy = y + TILESIZE/2;
1784         int coords[14], *c;
1785
1786         c = coords;
1787         *c++ = ox + px/9;
1788         *c++ = oy + py/9;
1789         *c++ = ox + px/9 + ax*2/3;
1790         *c++ = oy + py/9 + ay*2/3;
1791         *c++ = ox + px/3 + ax*2/3;
1792         *c++ = oy + py/3 + ay*2/3;
1793         *c++ = ox + ax;
1794         *c++ = oy + ay;
1795         *c++ = ox - px/3 + ax*2/3;
1796         *c++ = oy - py/3 + ay*2/3;
1797         *c++ = ox - px/9 + ax*2/3;
1798         *c++ = oy - py/9 + ay*2/3;
1799         *c++ = ox - px/9;
1800         *c++ = oy - py/9;
1801         draw_polygon(dr, coords, 7, COL_HINT, COL_OUTLINE);
1802     }
1803
1804     draw_update(dr, x, y, TILESIZE, TILESIZE);
1805 }
1806
1807 #define FLASH_DEAD 0x100
1808 #define FLASH_WIN  0x200
1809 #define FLASH_MASK 0x300
1810
1811 static void draw_tile(drawing *dr, game_drawstate *ds, int x, int y, int v)
1812 {
1813     int tx = COORD(x), ty = COORD(y);
1814     int bg = (v & FLASH_DEAD ? COL_DEAD_PLAYER :
1815               v & FLASH_WIN ? COL_HIGHLIGHT : COL_BACKGROUND);
1816
1817     v &= ~FLASH_MASK;
1818
1819     clip(dr, tx+1, ty+1, TILESIZE-1, TILESIZE-1);
1820     draw_rect(dr, tx+1, ty+1, TILESIZE-1, TILESIZE-1, bg);
1821
1822     if (v == WALL) {
1823         int coords[6];
1824
1825         coords[0] = tx + TILESIZE;
1826         coords[1] = ty + TILESIZE;
1827         coords[2] = tx + TILESIZE;
1828         coords[3] = ty + 1;
1829         coords[4] = tx + 1;
1830         coords[5] = ty + TILESIZE;
1831         draw_polygon(dr, coords, 3, COL_LOWLIGHT, COL_LOWLIGHT);
1832
1833         coords[0] = tx + 1;
1834         coords[1] = ty + 1;
1835         draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
1836
1837         draw_rect(dr, tx + 1 + HIGHLIGHT_WIDTH, ty + 1 + HIGHLIGHT_WIDTH,
1838                   TILESIZE - 2*HIGHLIGHT_WIDTH,
1839                   TILESIZE - 2*HIGHLIGHT_WIDTH, COL_WALL);
1840     } else if (v == MINE) {
1841         int cx = tx + TILESIZE / 2;
1842         int cy = ty + TILESIZE / 2;
1843         int r = TILESIZE / 2 - 3;
1844         int coords[4*5*2];
1845         int xdx = 1, xdy = 0, ydx = 0, ydy = 1;
1846         int tdx, tdy, i;
1847
1848         for (i = 0; i < 4*5*2; i += 5*2) {
1849             coords[i+2*0+0] = cx - r/6*xdx + r*4/5*ydx;
1850             coords[i+2*0+1] = cy - r/6*xdy + r*4/5*ydy;
1851             coords[i+2*1+0] = cx - r/6*xdx + r*ydx;
1852             coords[i+2*1+1] = cy - r/6*xdy + r*ydy;
1853             coords[i+2*2+0] = cx + r/6*xdx + r*ydx;
1854             coords[i+2*2+1] = cy + r/6*xdy + r*ydy;
1855             coords[i+2*3+0] = cx + r/6*xdx + r*4/5*ydx;
1856             coords[i+2*3+1] = cy + r/6*xdy + r*4/5*ydy;
1857             coords[i+2*4+0] = cx + r*3/5*xdx + r*3/5*ydx;
1858             coords[i+2*4+1] = cy + r*3/5*xdy + r*3/5*ydy;
1859
1860             tdx = ydx;
1861             tdy = ydy;
1862             ydx = xdx;
1863             ydy = xdy;
1864             xdx = -tdx;
1865             xdy = -tdy;
1866         }
1867
1868         draw_polygon(dr, coords, 5*4, COL_MINE, COL_MINE);
1869
1870         draw_rect(dr, cx-r/3, cy-r/3, r/3, r/4, COL_HIGHLIGHT);
1871     } else if (v == STOP) {
1872         draw_circle(dr, tx + TILESIZE/2, ty + TILESIZE/2,
1873                     TILESIZE*3/7, -1, COL_OUTLINE);
1874         draw_rect(dr, tx + TILESIZE*3/7, ty+1,
1875                   TILESIZE - 2*(TILESIZE*3/7) + 1, TILESIZE-1, bg);
1876         draw_rect(dr, tx+1, ty + TILESIZE*3/7,
1877                   TILESIZE-1, TILESIZE - 2*(TILESIZE*3/7) + 1, bg);
1878     } else if (v == GEM) {
1879         int coords[8];
1880
1881         coords[0] = tx+TILESIZE/2;
1882         coords[1] = ty+TILESIZE*1/7;
1883         coords[2] = tx+TILESIZE*1/7;
1884         coords[3] = ty+TILESIZE/2;
1885         coords[4] = tx+TILESIZE/2;
1886         coords[5] = ty+TILESIZE-TILESIZE*1/7;
1887         coords[6] = tx+TILESIZE-TILESIZE*1/7;
1888         coords[7] = ty+TILESIZE/2;
1889
1890         draw_polygon(dr, coords, 4, COL_GEM, COL_OUTLINE);
1891     }
1892
1893     unclip(dr);
1894     draw_update(dr, tx, ty, TILESIZE, TILESIZE);
1895 }
1896
1897 #define BASE_ANIM_LENGTH 0.1F
1898 #define FLASH_LENGTH 0.3F
1899
1900 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
1901                         game_state *state, int dir, game_ui *ui,
1902                         float animtime, float flashtime)
1903 {
1904     int w = state->p.w, h = state->p.h /*, wh = w*h */;
1905     int x, y;
1906     float ap;
1907     int player_dist;
1908     int flashtype;
1909     int gems, deaths;
1910     char status[256];
1911
1912     if (flashtime &&
1913         !((int)(flashtime * 3 / FLASH_LENGTH) % 2))
1914         flashtype = ui->flashtype;
1915     else
1916         flashtype = 0;
1917
1918     /*
1919      * Erase the player sprite.
1920      */
1921     if (ds->player_bg_saved) {
1922         assert(ds->player_background);
1923         blitter_load(dr, ds->player_background, ds->pbgx, ds->pbgy);
1924         draw_update(dr, ds->pbgx, ds->pbgy, TILESIZE, TILESIZE);
1925         ds->player_bg_saved = FALSE;
1926     }
1927
1928     /*
1929      * Initialise a fresh drawstate.
1930      */
1931     if (!ds->started) {
1932         int wid, ht;
1933
1934         /*
1935          * Blank out the window initially.
1936          */
1937         game_compute_size(&ds->p, TILESIZE, &wid, &ht);
1938         draw_rect(dr, 0, 0, wid, ht, COL_BACKGROUND);
1939         draw_update(dr, 0, 0, wid, ht);
1940
1941         /*
1942          * Draw the grid lines.
1943          */
1944         for (y = 0; y <= h; y++)
1945             draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y),
1946                       COL_LOWLIGHT);
1947         for (x = 0; x <= w; x++)
1948             draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h),
1949                       COL_LOWLIGHT);
1950
1951         ds->started = TRUE;
1952     }
1953
1954     /*
1955      * If we're in the process of animating a move, let's start by
1956      * working out how far the player has moved from their _older_
1957      * state.
1958      */
1959     if (oldstate) {
1960         ap = animtime / ui->anim_length;
1961         player_dist = ap * (dir > 0 ? state : oldstate)->distance_moved;
1962     } else {
1963         player_dist = 0;
1964         ap = 0.0F;
1965     }
1966
1967     /*
1968      * Draw the grid contents.
1969      * 
1970      * We count the gems as we go round this loop, for the purposes
1971      * of the status bar. Of course we have a gems counter in the
1972      * game_state already, but if we do the counting in this loop
1973      * then it tracks gems being picked up in a sliding move, and
1974      * updates one by one.
1975      */
1976     gems = 0;
1977     for (y = 0; y < h; y++)
1978         for (x = 0; x < w; x++) {
1979             unsigned short v = (unsigned char)state->grid[y*w+x];
1980
1981             /*
1982              * Special case: if the player is in the process of
1983              * moving over a gem, we draw the gem iff they haven't
1984              * gone past it yet.
1985              */
1986             if (oldstate && oldstate->grid[y*w+x] != state->grid[y*w+x]) {
1987                 /*
1988                  * Compute the distance from this square to the
1989                  * original player position.
1990                  */
1991                 int dist = max(abs(x - oldstate->px), abs(y - oldstate->py));
1992
1993                 /*
1994                  * If the player has reached here, use the new grid
1995                  * element. Otherwise use the old one.
1996                  */
1997                 if (player_dist < dist)
1998                     v = oldstate->grid[y*w+x];
1999                 else
2000                     v = state->grid[y*w+x];
2001             }
2002
2003             /*
2004              * Special case: erase the mine the dead player is
2005              * sitting on. Only at the end of the move.
2006              */
2007             if (v == MINE && !oldstate && state->dead &&
2008                 x == state->px && y == state->py)
2009                 v = BLANK;
2010
2011             if (v == GEM)
2012                 gems++;
2013
2014             v |= flashtype;
2015
2016             if (ds->grid[y*w+x] != v) {
2017                 draw_tile(dr, ds, x, y, v);
2018                 ds->grid[y*w+x] = v;
2019             }
2020         }
2021
2022     /*
2023      * Gem counter in the status bar. We replace it with
2024      * `COMPLETED!' when it reaches zero ... or rather, when the
2025      * _current state_'s gem counter is zero. (Thus, `Gems: 0' is
2026      * shown between the collection of the last gem and the
2027      * completion of the move animation that did it.)
2028      */
2029     if (state->dead && (!oldstate || oldstate->dead)) {
2030         sprintf(status, "DEAD!");
2031     } else if (state->gems || (oldstate && oldstate->gems)) {
2032         if (state->cheated)
2033             sprintf(status, "Auto-solver used. ");
2034         else
2035             *status = '\0';
2036         sprintf(status + strlen(status), "Gems: %d", gems);
2037     } else if (state->cheated) {
2038         sprintf(status, "Auto-solved.");
2039     } else {
2040         sprintf(status, "COMPLETED!");
2041     }
2042     /* We subtract one from the visible death counter if we're still
2043      * animating the move at the end of which the death took place. */
2044     deaths = ui->deaths;
2045     if (oldstate && ui->just_died) {
2046         assert(deaths > 0);
2047         deaths--;
2048     }
2049     if (deaths)
2050         sprintf(status + strlen(status), "   Deaths: %d", deaths);
2051     status_bar(dr, status);
2052
2053     /*
2054      * Draw the player sprite.
2055      */
2056     assert(!ds->player_bg_saved);
2057     assert(ds->player_background);
2058     {
2059         int ox, oy, nx, ny;
2060         nx = COORD(state->px);
2061         ny = COORD(state->py);
2062         if (oldstate) {
2063             ox = COORD(oldstate->px);
2064             oy = COORD(oldstate->py);
2065         } else {
2066             ox = nx;
2067             oy = ny;
2068         }
2069         ds->pbgx = ox + ap * (nx - ox);
2070         ds->pbgy = oy + ap * (ny - oy);
2071     }
2072     blitter_save(dr, ds->player_background, ds->pbgx, ds->pbgy);
2073     draw_player(dr, ds, ds->pbgx, ds->pbgy,
2074                 (state->dead && !oldstate),
2075                 (!oldstate && state->soln ?
2076                  state->soln->list[state->solnpos] : -1));
2077     ds->player_bg_saved = TRUE;
2078 }
2079
2080 static float game_anim_length(game_state *oldstate, game_state *newstate,
2081                               int dir, game_ui *ui)
2082 {
2083     int dist;
2084     if (dir > 0)
2085         dist = newstate->distance_moved;
2086     else
2087         dist = oldstate->distance_moved;
2088     ui->anim_length = sqrt(dist) * BASE_ANIM_LENGTH;
2089     return ui->anim_length;
2090 }
2091
2092 static float game_flash_length(game_state *oldstate, game_state *newstate,
2093                                int dir, game_ui *ui)
2094 {
2095     if (!oldstate->dead && newstate->dead) {
2096         ui->flashtype = FLASH_DEAD;
2097         return FLASH_LENGTH;
2098     } else if (oldstate->gems && !newstate->gems) {
2099         ui->flashtype = FLASH_WIN;
2100         return FLASH_LENGTH;
2101     }
2102     return 0.0F;
2103 }
2104
2105 static int game_wants_statusbar(void)
2106 {
2107     return TRUE;
2108 }
2109
2110 static int game_timing_state(game_state *state, game_ui *ui)
2111 {
2112     return TRUE;
2113 }
2114
2115 static void game_print_size(game_params *params, float *x, float *y)
2116 {
2117 }
2118
2119 static void game_print(drawing *dr, game_state *state, int tilesize)
2120 {
2121 }
2122
2123 #ifdef COMBINED
2124 #define thegame inertia
2125 #endif
2126
2127 const struct game thegame = {
2128     "Inertia", "games.inertia",
2129     default_params,
2130     game_fetch_preset,
2131     decode_params,
2132     encode_params,
2133     free_params,
2134     dup_params,
2135     TRUE, game_configure, custom_params,
2136     validate_params,
2137     new_game_desc,
2138     validate_desc,
2139     new_game,
2140     dup_game,
2141     free_game,
2142     TRUE, solve_game,
2143     FALSE, game_text_format,
2144     new_ui,
2145     free_ui,
2146     encode_ui,
2147     decode_ui,
2148     game_changed_state,
2149     interpret_move,
2150     execute_move,
2151     PREFERRED_TILESIZE, game_compute_size, game_set_size,
2152     game_colours,
2153     game_new_drawstate,
2154     game_free_drawstate,
2155     game_redraw,
2156     game_anim_length,
2157     game_flash_length,
2158     FALSE, FALSE, game_print_size, game_print,
2159     game_wants_statusbar,
2160     FALSE, game_timing_state,
2161     0,                                 /* mouse_priorities */
2162 };