chiark / gitweb /
I've proved that a grid dimension of 2 is capable of irretrievably
[sgt-puzzles.git] / mines.c
1 /*
2  * mines.c: Minesweeper clone with sophisticated grid generation.
3  * 
4  * Still TODO:
5  *
6  *  - think about configurably supporting question marks. Once,
7  *    that is, we've thought about configurability in general!
8  */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <assert.h>
14 #include <ctype.h>
15 #include <math.h>
16
17 #include "tree234.h"
18 #include "puzzles.h"
19
20 enum {
21     COL_BACKGROUND, COL_BACKGROUND2,
22     COL_1, COL_2, COL_3, COL_4, COL_5, COL_6, COL_7, COL_8,
23     COL_MINE, COL_BANG, COL_CROSS, COL_FLAG, COL_FLAGBASE, COL_QUERY,
24     COL_HIGHLIGHT, COL_LOWLIGHT,
25     NCOLOURS
26 };
27
28 #define TILE_SIZE 20
29 #define BORDER (TILE_SIZE * 3 / 2)
30 #define HIGHLIGHT_WIDTH 2
31 #define OUTER_HIGHLIGHT_WIDTH 3
32 #define COORD(x)  ( (x) * TILE_SIZE + BORDER )
33 #define FROMCOORD(x)  ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
34
35 #define FLASH_FRAME 0.13F
36
37 struct game_params {
38     int w, h, n;
39     int unique;
40 };
41
42 struct mine_layout {
43     /*
44      * This structure is shared between all the game_states for a
45      * given instance of the puzzle, so we reference-count it.
46      */
47     int refcount;
48     char *mines;
49     /*
50      * If we haven't yet actually generated the mine layout, here's
51      * all the data we will need to do so.
52      */
53     int n, unique;
54     random_state *rs;
55     midend_data *me;                   /* to give back the new game desc */
56 };
57
58 struct game_state {
59     int w, h, n, dead, won;
60     int used_solve, just_used_solve;
61     struct mine_layout *layout;        /* real mine positions */
62     signed char *grid;                         /* player knowledge */
63     /*
64      * Each item in the `grid' array is one of the following values:
65      * 
66      *  - 0 to 8 mean the square is open and has a surrounding mine
67      *    count.
68      * 
69      *  - -1 means the square is marked as a mine.
70      * 
71      *  - -2 means the square is unknown.
72      * 
73      *  - -3 means the square is marked with a question mark
74      *    (FIXME: do we even want to bother with this?).
75      * 
76      *  - 64 means the square has had a mine revealed when the game
77      *    was lost.
78      * 
79      *  - 65 means the square had a mine revealed and this was the
80      *    one the player hits.
81      * 
82      *  - 66 means the square has a crossed-out mine because the
83      *    player had incorrectly marked it.
84      */
85 };
86
87 static game_params *default_params(void)
88 {
89     game_params *ret = snew(game_params);
90
91     ret->w = ret->h = 9;
92     ret->n = 10;
93     ret->unique = TRUE;
94
95     return ret;
96 }
97
98 static int game_fetch_preset(int i, char **name, game_params **params)
99 {
100     game_params *ret;
101     char str[80];
102     static const struct { int w, h, n; } values[] = {
103         {9, 9, 10},
104         {16, 16, 40},
105         {30, 16, 99},
106     };
107
108     if (i < 0 || i >= lenof(values))
109         return FALSE;
110
111     ret = snew(game_params);
112     ret->w = values[i].w;
113     ret->h = values[i].h;
114     ret->n = values[i].n;
115     ret->unique = TRUE;
116
117     sprintf(str, "%dx%d, %d mines", ret->w, ret->h, ret->n);
118
119     *name = dupstr(str);
120     *params = ret;
121     return TRUE;
122 }
123
124 static void free_params(game_params *params)
125 {
126     sfree(params);
127 }
128
129 static game_params *dup_params(game_params *params)
130 {
131     game_params *ret = snew(game_params);
132     *ret = *params;                    /* structure copy */
133     return ret;
134 }
135
136 static void decode_params(game_params *params, char const *string)
137 {
138     char const *p = string;
139
140     params->w = atoi(p);
141     while (*p && isdigit((unsigned char)*p)) p++;
142     if (*p == 'x') {
143         p++;
144         params->h = atoi(p);
145         while (*p && isdigit((unsigned char)*p)) p++;
146     } else {
147         params->h = params->w;
148     }
149     if (*p == 'n') {
150         p++;
151         params->n = atoi(p);
152         while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
153     } else {
154         params->n = params->w * params->h / 10;
155     }
156
157     while (*p) {
158         if (*p == 'a') {
159             p++;
160             params->unique = FALSE;
161         } else
162             p++;                       /* skip any other gunk */
163     }
164 }
165
166 static char *encode_params(game_params *params, int full)
167 {
168     char ret[400];
169     int len;
170
171     len = sprintf(ret, "%dx%d", params->w, params->h);
172     /*
173      * Mine count is a generation-time parameter, since it can be
174      * deduced from the mine bitmap!
175      */
176     if (full)
177         len += sprintf(ret+len, "n%d", params->n);
178     if (full && !params->unique)
179         ret[len++] = 'a';
180     assert(len < lenof(ret));
181     ret[len] = '\0';
182
183     return dupstr(ret);
184 }
185
186 static config_item *game_configure(game_params *params)
187 {
188     config_item *ret;
189     char buf[80];
190
191     ret = snewn(5, config_item);
192
193     ret[0].name = "Width";
194     ret[0].type = C_STRING;
195     sprintf(buf, "%d", params->w);
196     ret[0].sval = dupstr(buf);
197     ret[0].ival = 0;
198
199     ret[1].name = "Height";
200     ret[1].type = C_STRING;
201     sprintf(buf, "%d", params->h);
202     ret[1].sval = dupstr(buf);
203     ret[1].ival = 0;
204
205     ret[2].name = "Mines";
206     ret[2].type = C_STRING;
207     sprintf(buf, "%d", params->n);
208     ret[2].sval = dupstr(buf);
209     ret[2].ival = 0;
210
211     ret[3].name = "Ensure solubility";
212     ret[3].type = C_BOOLEAN;
213     ret[3].sval = NULL;
214     ret[3].ival = params->unique;
215
216     ret[4].name = NULL;
217     ret[4].type = C_END;
218     ret[4].sval = NULL;
219     ret[4].ival = 0;
220
221     return ret;
222 }
223
224 static game_params *custom_params(config_item *cfg)
225 {
226     game_params *ret = snew(game_params);
227
228     ret->w = atoi(cfg[0].sval);
229     ret->h = atoi(cfg[1].sval);
230     ret->n = atoi(cfg[2].sval);
231     if (strchr(cfg[2].sval, '%'))
232         ret->n = ret->n * (ret->w * ret->h) / 100;
233     ret->unique = cfg[3].ival;
234
235     return ret;
236 }
237
238 static char *validate_params(game_params *params)
239 {
240     /*
241      * Lower limit on grid size: each dimension must be at least 3.
242      * 1 is theoretically workable if rather boring, but 2 is a
243      * real problem: there is often _no_ way to generate a uniquely
244      * solvable 2xn Mines grid. You either run into two mines
245      * blocking the way and no idea what's behind them, or one mine
246      * and no way to know which of the two rows it's in. If the
247      * mine count is even you can create a soluble grid by packing
248      * all the mines at one end (so what when you hit a two-mine
249      * wall there are only as many covered squares left as there
250      * are mines); but if it's odd, you are doomed, because you
251      * _have_ to have a gap somewhere which you can't determine the
252      * position of.
253      */
254     if (params->w <= 2 || params->h <= 2)
255         return "Width and height must both be greater than two";
256     if (params->n > params->w * params->h - 9)
257         return "Too many mines for grid size";
258
259     /*
260      * FIXME: Need more constraints here. Not sure what the
261      * sensible limits for Minesweeper actually are. The limits
262      * probably ought to change, however, depending on uniqueness.
263      */
264
265     return NULL;
266 }
267
268 /* ----------------------------------------------------------------------
269  * Minesweeper solver, used to ensure the generated grids are
270  * solvable without having to take risks.
271  */
272
273 /*
274  * Count the bits in a word. Only needs to cope with 16 bits.
275  */
276 static int bitcount16(int word)
277 {
278     word = ((word & 0xAAAA) >> 1) + (word & 0x5555);
279     word = ((word & 0xCCCC) >> 2) + (word & 0x3333);
280     word = ((word & 0xF0F0) >> 4) + (word & 0x0F0F);
281     word = ((word & 0xFF00) >> 8) + (word & 0x00FF);
282
283     return word;
284 }
285
286 /*
287  * We use a tree234 to store a large number of small localised
288  * sets, each with a mine count. We also keep some of those sets
289  * linked together into a to-do list.
290  */
291 struct set {
292     short x, y, mask, mines;
293     int todo;
294     struct set *prev, *next;
295 };
296
297 static int setcmp(void *av, void *bv)
298 {
299     struct set *a = (struct set *)av;
300     struct set *b = (struct set *)bv;
301
302     if (a->y < b->y)
303         return -1;
304     else if (a->y > b->y)
305         return +1;
306     else if (a->x < b->x)
307         return -1;
308     else if (a->x > b->x)
309         return +1;
310     else if (a->mask < b->mask)
311         return -1;
312     else if (a->mask > b->mask)
313         return +1;
314     else
315         return 0;
316 }
317
318 struct setstore {
319     tree234 *sets;
320     struct set *todo_head, *todo_tail;
321 };
322
323 static struct setstore *ss_new(void)
324 {
325     struct setstore *ss = snew(struct setstore);
326     ss->sets = newtree234(setcmp);
327     ss->todo_head = ss->todo_tail = NULL;
328     return ss;
329 }
330
331 /*
332  * Take two input sets, in the form (x,y,mask). Munge the first by
333  * taking either its intersection with the second or its difference
334  * with the second. Return the new mask part of the first set.
335  */
336 static int setmunge(int x1, int y1, int mask1, int x2, int y2, int mask2,
337                     int diff)
338 {
339     /*
340      * Adjust the second set so that it has the same x,y
341      * coordinates as the first.
342      */
343     if (abs(x2-x1) >= 3 || abs(y2-y1) >= 3) {
344         mask2 = 0;
345     } else {
346         while (x2 > x1) {
347             mask2 &= ~(4|32|256);
348             mask2 <<= 1;
349             x2--;
350         }
351         while (x2 < x1) {
352             mask2 &= ~(1|8|64);
353             mask2 >>= 1;
354             x2++;
355         }
356         while (y2 > y1) {
357             mask2 &= ~(64|128|256);
358             mask2 <<= 3;
359             y2--;
360         }
361         while (y2 < y1) {
362             mask2 &= ~(1|2|4);
363             mask2 >>= 3;
364             y2++;
365         }
366     }
367
368     /*
369      * Invert the second set if `diff' is set (we're after A &~ B
370      * rather than A & B).
371      */
372     if (diff)
373         mask2 ^= 511;
374
375     /*
376      * Now all that's left is a logical AND.
377      */
378     return mask1 & mask2;
379 }
380
381 static void ss_add_todo(struct setstore *ss, struct set *s)
382 {
383     if (s->todo)
384         return;                        /* already on it */
385
386 #ifdef SOLVER_DIAGNOSTICS
387     printf("adding set on todo list: %d,%d %03x %d\n",
388            s->x, s->y, s->mask, s->mines);
389 #endif
390
391     s->prev = ss->todo_tail;
392     if (s->prev)
393         s->prev->next = s;
394     else
395         ss->todo_head = s;
396     ss->todo_tail = s;
397     s->next = NULL;
398     s->todo = TRUE;
399 }
400
401 static void ss_add(struct setstore *ss, int x, int y, int mask, int mines)
402 {
403     struct set *s;
404
405     assert(mask != 0);
406
407     /*
408      * Normalise so that x and y are genuinely the bounding
409      * rectangle.
410      */
411     while (!(mask & (1|8|64)))
412         mask >>= 1, x++;
413     while (!(mask & (1|2|4)))
414         mask >>= 3, y++;
415
416     /*
417      * Create a set structure and add it to the tree.
418      */
419     s = snew(struct set);
420     s->x = x;
421     s->y = y;
422     s->mask = mask;
423     s->mines = mines;
424     s->todo = FALSE;
425     if (add234(ss->sets, s) != s) {
426         /*
427          * This set already existed! Free it and return.
428          */
429         sfree(s);
430         return;
431     }
432
433     /*
434      * We've added a new set to the tree, so put it on the todo
435      * list.
436      */
437     ss_add_todo(ss, s);
438 }
439
440 static void ss_remove(struct setstore *ss, struct set *s)
441 {
442     struct set *next = s->next, *prev = s->prev;
443
444 #ifdef SOLVER_DIAGNOSTICS
445     printf("removing set %d,%d %03x\n", s->x, s->y, s->mask);
446 #endif
447     /*
448      * Remove s from the todo list.
449      */
450     if (prev)
451         prev->next = next;
452     else if (s == ss->todo_head)
453         ss->todo_head = next;
454
455     if (next)
456         next->prev = prev;
457     else if (s == ss->todo_tail)
458         ss->todo_tail = prev;
459
460     s->todo = FALSE;
461
462     /*
463      * Remove s from the tree.
464      */
465     del234(ss->sets, s);
466
467     /*
468      * Destroy the actual set structure.
469      */
470     sfree(s);
471 }
472
473 /*
474  * Return a dynamically allocated list of all the sets which
475  * overlap a provided input set.
476  */
477 static struct set **ss_overlap(struct setstore *ss, int x, int y, int mask)
478 {
479     struct set **ret = NULL;
480     int nret = 0, retsize = 0;
481     int xx, yy;
482
483     for (xx = x-3; xx < x+3; xx++)
484         for (yy = y-3; yy < y+3; yy++) {
485             struct set stmp, *s;
486             int pos;
487
488             /*
489              * Find the first set with these top left coordinates.
490              */
491             stmp.x = xx;
492             stmp.y = yy;
493             stmp.mask = 0;
494
495             if (findrelpos234(ss->sets, &stmp, NULL, REL234_GE, &pos)) {
496                 while ((s = index234(ss->sets, pos)) != NULL &&
497                        s->x == xx && s->y == yy) {
498                     /*
499                      * This set potentially overlaps the input one.
500                      * Compute the intersection to see if they
501                      * really overlap, and add it to the list if
502                      * so.
503                      */
504                     if (setmunge(x, y, mask, s->x, s->y, s->mask, FALSE)) {
505                         /*
506                          * There's an overlap.
507                          */
508                         if (nret >= retsize) {
509                             retsize = nret + 32;
510                             ret = sresize(ret, retsize, struct set *);
511                         }
512                         ret[nret++] = s;
513                     }
514
515                     pos++;
516                 }
517             }
518         }
519
520     ret = sresize(ret, nret+1, struct set *);
521     ret[nret] = NULL;
522
523     return ret;
524 }
525
526 /*
527  * Get an element from the head of the set todo list.
528  */
529 static struct set *ss_todo(struct setstore *ss)
530 {
531     if (ss->todo_head) {
532         struct set *ret = ss->todo_head;
533         ss->todo_head = ret->next;
534         if (ss->todo_head)
535             ss->todo_head->prev = NULL;
536         else
537             ss->todo_tail = NULL;
538         ret->next = ret->prev = NULL;
539         ret->todo = FALSE;
540         return ret;
541     } else {
542         return NULL;
543     }
544 }
545
546 struct squaretodo {
547     int *next;
548     int head, tail;
549 };
550
551 static void std_add(struct squaretodo *std, int i)
552 {
553     if (std->tail >= 0)
554         std->next[std->tail] = i;
555     else
556         std->head = i;
557     std->tail = i;
558     std->next[i] = -1;
559 }
560
561 static void known_squares(int w, int h, struct squaretodo *std,
562                           signed char *grid,
563                           int (*open)(void *ctx, int x, int y), void *openctx,
564                           int x, int y, int mask, int mine)
565 {
566     int xx, yy, bit;
567
568     bit = 1;
569
570     for (yy = 0; yy < 3; yy++)
571         for (xx = 0; xx < 3; xx++) {
572             if (mask & bit) {
573                 int i = (y + yy) * w + (x + xx);
574
575                 /*
576                  * It's possible that this square is _already_
577                  * known, in which case we don't try to add it to
578                  * the list twice.
579                  */
580                 if (grid[i] == -2) {
581
582                     if (mine) {
583                         grid[i] = -1;   /* and don't open it! */
584                     } else {
585                         grid[i] = open(openctx, x + xx, y + yy);
586                         assert(grid[i] != -1);   /* *bang* */
587                     }
588                     std_add(std, i);
589
590                 }
591             }
592             bit <<= 1;
593         }
594 }
595
596 /*
597  * This is data returned from the `perturb' function. It details
598  * which squares have become mines and which have become clear. The
599  * solver is (of course) expected to honourably not use that
600  * knowledge directly, but to efficently adjust its internal data
601  * structures and proceed based on only the information it
602  * legitimately has.
603  */
604 struct perturbation {
605     int x, y;
606     int delta;                         /* +1 == become a mine; -1 == cleared */
607 };
608 struct perturbations {
609     int n;
610     struct perturbation *changes;
611 };
612
613 /*
614  * Main solver entry point. You give it a grid of existing
615  * knowledge (-1 for a square known to be a mine, 0-8 for empty
616  * squares with a given number of neighbours, -2 for completely
617  * unknown), plus a function which you can call to open new squares
618  * once you're confident of them. It fills in as much more of the
619  * grid as it can.
620  * 
621  * Return value is:
622  * 
623  *  - -1 means deduction stalled and nothing could be done
624  *  - 0 means deduction succeeded fully
625  *  - >0 means deduction succeeded but some number of perturbation
626  *    steps were required; the exact return value is the number of
627  *    perturb calls.
628  */
629 static int minesolve(int w, int h, int n, signed char *grid,
630                      int (*open)(void *ctx, int x, int y),
631                      struct perturbations *(*perturb)(void *ctx,
632                                                       signed char *grid,
633                                                       int x, int y, int mask),
634                      void *ctx, random_state *rs)
635 {
636     struct setstore *ss = ss_new();
637     struct set **list;
638     struct squaretodo astd, *std = &astd;
639     int x, y, i, j;
640     int nperturbs = 0;
641
642     /*
643      * Set up a linked list of squares with known contents, so that
644      * we can process them one by one.
645      */
646     std->next = snewn(w*h, int);
647     std->head = std->tail = -1;
648
649     /*
650      * Initialise that list with all known squares in the input
651      * grid.
652      */
653     for (y = 0; y < h; y++) {
654         for (x = 0; x < w; x++) {
655             i = y*w+x;
656             if (grid[i] != -2)
657                 std_add(std, i);
658         }
659     }
660
661     /*
662      * Main deductive loop.
663      */
664     while (1) {
665         int done_something = FALSE;
666         struct set *s;
667
668         /*
669          * If there are any known squares on the todo list, process
670          * them and construct a set for each.
671          */
672         while (std->head != -1) {
673             i = std->head;
674 #ifdef SOLVER_DIAGNOSTICS
675             printf("known square at %d,%d [%d]\n", i%w, i/w, grid[i]);
676 #endif
677             std->head = std->next[i];
678             if (std->head == -1)
679                 std->tail = -1;
680
681             x = i % w;
682             y = i / w;
683
684             if (grid[i] >= 0) {
685                 int dx, dy, mines, bit, val;
686 #ifdef SOLVER_DIAGNOSTICS
687                 printf("creating set around this square\n");
688 #endif
689                 /*
690                  * Empty square. Construct the set of non-known squares
691                  * around this one, and determine its mine count.
692                  */
693                 mines = grid[i];
694                 bit = 1;
695                 val = 0;
696                 for (dy = -1; dy <= +1; dy++) {
697                     for (dx = -1; dx <= +1; dx++) {
698 #ifdef SOLVER_DIAGNOSTICS
699                         printf("grid %d,%d = %d\n", x+dx, y+dy, grid[i+dy*w+dx]);
700 #endif
701                         if (x+dx < 0 || x+dx >= w || y+dy < 0 || y+dy >= h)
702                             /* ignore this one */;
703                         else if (grid[i+dy*w+dx] == -1)
704                             mines--;
705                         else if (grid[i+dy*w+dx] == -2)
706                             val |= bit;
707                         bit <<= 1;
708                     }
709                 }
710                 if (val)
711                     ss_add(ss, x-1, y-1, val, mines);
712             }
713
714             /*
715              * Now, whether the square is empty or full, we must
716              * find any set which contains it and replace it with
717              * one which does not.
718              */
719             {
720 #ifdef SOLVER_DIAGNOSTICS
721                 printf("finding sets containing known square %d,%d\n", x, y);
722 #endif
723                 list = ss_overlap(ss, x, y, 1);
724
725                 for (j = 0; list[j]; j++) {
726                     int newmask, newmines;
727
728                     s = list[j];
729
730                     /*
731                      * Compute the mask for this set minus the
732                      * newly known square.
733                      */
734                     newmask = setmunge(s->x, s->y, s->mask, x, y, 1, TRUE);
735
736                     /*
737                      * Compute the new mine count.
738                      */
739                     newmines = s->mines - (grid[i] == -1);
740
741                     /*
742                      * Insert the new set into the collection,
743                      * unless it's been whittled right down to
744                      * nothing.
745                      */
746                     if (newmask)
747                         ss_add(ss, s->x, s->y, newmask, newmines);
748
749                     /*
750                      * Destroy the old one; it is actually obsolete.
751                      */
752                     ss_remove(ss, s);
753                 }
754
755                 sfree(list);
756             }
757
758             /*
759              * Marking a fresh square as known certainly counts as
760              * doing something.
761              */
762             done_something = TRUE;
763         }
764
765         /*
766          * Now pick a set off the to-do list and attempt deductions
767          * based on it.
768          */
769         if ((s = ss_todo(ss)) != NULL) {
770
771 #ifdef SOLVER_DIAGNOSTICS
772             printf("set to do: %d,%d %03x %d\n", s->x, s->y, s->mask, s->mines);
773 #endif
774             /*
775              * Firstly, see if this set has a mine count of zero or
776              * of its own cardinality.
777              */
778             if (s->mines == 0 || s->mines == bitcount16(s->mask)) {
779                 /*
780                  * If so, we can immediately mark all the squares
781                  * in the set as known.
782                  */
783 #ifdef SOLVER_DIAGNOSTICS
784                 printf("easy\n");
785 #endif
786                 known_squares(w, h, std, grid, open, ctx,
787                               s->x, s->y, s->mask, (s->mines != 0));
788
789                 /*
790                  * Having done that, we need do nothing further
791                  * with this set; marking all the squares in it as
792                  * known will eventually eliminate it, and will
793                  * also permit further deductions about anything
794                  * that overlaps it.
795                  */
796                 continue;
797             }
798
799             /*
800              * Failing that, we now search through all the sets
801              * which overlap this one.
802              */
803             list = ss_overlap(ss, s->x, s->y, s->mask);
804
805             for (j = 0; list[j]; j++) {
806                 struct set *s2 = list[j];
807                 int swing, s2wing, swc, s2wc;
808
809                 /*
810                  * Find the non-overlapping parts s2-s and s-s2,
811                  * and their cardinalities.
812                  * 
813                  * I'm going to refer to these parts as `wings'
814                  * surrounding the central part common to both
815                  * sets. The `s wing' is s-s2; the `s2 wing' is
816                  * s2-s.
817                  */
818                 swing = setmunge(s->x, s->y, s->mask, s2->x, s2->y, s2->mask,
819                                  TRUE);
820                 s2wing = setmunge(s2->x, s2->y, s2->mask, s->x, s->y, s->mask,
821                                  TRUE);
822                 swc = bitcount16(swing);
823                 s2wc = bitcount16(s2wing);
824
825                 /*
826                  * If one set has more mines than the other, and
827                  * the number of extra mines is equal to the
828                  * cardinality of that set's wing, then we can mark
829                  * every square in the wing as a known mine, and
830                  * every square in the other wing as known clear.
831                  */
832                 if (swc == s->mines - s2->mines ||
833                     s2wc == s2->mines - s->mines) {
834                     known_squares(w, h, std, grid, open, ctx,
835                                   s->x, s->y, swing,
836                                   (swc == s->mines - s2->mines));
837                     known_squares(w, h, std, grid, open, ctx,
838                                   s2->x, s2->y, s2wing,
839                                   (s2wc == s2->mines - s->mines));
840                     continue;
841                 }
842
843                 /*
844                  * Failing that, see if one set is a subset of the
845                  * other. If so, we can divide up the mine count of
846                  * the larger set between the smaller set and its
847                  * complement, even if neither smaller set ends up
848                  * being immediately clearable.
849                  */
850                 if (swc == 0 && s2wc != 0) {
851                     /* s is a subset of s2. */
852                     assert(s2->mines > s->mines);
853                     ss_add(ss, s2->x, s2->y, s2wing, s2->mines - s->mines);
854                 } else if (s2wc == 0 && swc != 0) {
855                     /* s2 is a subset of s. */
856                     assert(s->mines > s2->mines);
857                     ss_add(ss, s->x, s->y, swing, s->mines - s2->mines);
858                 }
859             }
860
861             sfree(list);
862
863             /*
864              * In this situation we have definitely done
865              * _something_, even if it's only reducing the size of
866              * our to-do list.
867              */
868             done_something = TRUE;
869         } else if (n >= 0) {
870             /*
871              * We have nothing left on our todo list, which means
872              * all localised deductions have failed. Our next step
873              * is to resort to global deduction based on the total
874              * mine count. This is computationally expensive
875              * compared to any of the above deductions, which is
876              * why we only ever do it when all else fails, so that
877              * hopefully it won't have to happen too often.
878              * 
879              * If you pass n<0 into this solver, that informs it
880              * that you do not know the total mine count, so it
881              * won't even attempt these deductions.
882              */
883
884             int minesleft, squaresleft;
885             int nsets, setused[10], cursor;
886
887             /*
888              * Start by scanning the current grid state to work out
889              * how many unknown squares we still have, and how many
890              * mines are to be placed in them.
891              */
892             squaresleft = 0;
893             minesleft = n;
894             for (i = 0; i < w*h; i++) {
895                 if (grid[i] == -1)
896                     minesleft--;
897                 else if (grid[i] == -2)
898                     squaresleft++;
899             }
900
901 #ifdef SOLVER_DIAGNOSTICS
902             printf("global deduction time: squaresleft=%d minesleft=%d\n",
903                    squaresleft, minesleft);
904             for (y = 0; y < h; y++) {
905                 for (x = 0; x < w; x++) {
906                     int v = grid[y*w+x];
907                     if (v == -1)
908                         putchar('*');
909                     else if (v == -2)
910                         putchar('?');
911                     else if (v == 0)
912                         putchar('-');
913                     else
914                         putchar('0' + v);
915                 }
916                 putchar('\n');
917             }
918 #endif
919
920             /*
921              * If there _are_ no unknown squares, we have actually
922              * finished.
923              */
924             if (squaresleft == 0) {
925                 assert(minesleft == 0);
926                 break;
927             }
928
929             /*
930              * First really simple case: if there are no more mines
931              * left, or if there are exactly as many mines left as
932              * squares to play them in, then it's all easy.
933              */
934             if (minesleft == 0 || minesleft == squaresleft) {
935                 for (i = 0; i < w*h; i++)
936                     if (grid[i] == -2)
937                         known_squares(w, h, std, grid, open, ctx,
938                                       i % w, i / w, 1, minesleft != 0);
939                 continue;              /* now go back to main deductive loop */
940             }
941
942             /*
943              * Failing that, we have to do some _real_ work.
944              * Ideally what we do here is to try every single
945              * combination of the currently available sets, in an
946              * attempt to find a disjoint union (i.e. a set of
947              * squares with a known mine count between them) such
948              * that the remaining unknown squares _not_ contained
949              * in that union either contain no mines or are all
950              * mines.
951              * 
952              * Actually enumerating all 2^n possibilities will get
953              * a bit slow for large n, so I artificially cap this
954              * recursion at n=10 to avoid too much pain.
955              */
956             nsets = count234(ss->sets);
957             if (nsets <= lenof(setused)) {
958                 /*
959                  * Doing this with actual recursive function calls
960                  * would get fiddly because a load of local
961                  * variables from this function would have to be
962                  * passed down through the recursion. So instead
963                  * I'm going to use a virtual recursion within this
964                  * function. The way this works is:
965                  * 
966                  *  - we have an array `setused', such that
967                  *    setused[n] is 0 or 1 depending on whether set
968                  *    n is currently in the union we are
969                  *    considering.
970                  * 
971                  *  - we have a value `cursor' which indicates how
972                  *    much of `setused' we have so far filled in.
973                  *    It's conceptually the recursion depth.
974                  * 
975                  * We begin by setting `cursor' to zero. Then:
976                  * 
977                  *  - if cursor can advance, we advance it by one.
978                  *    We set the value in `setused' that it went
979                  *    past to 1 if that set is disjoint from
980                  *    anything else currently in `setused', or to 0
981                  *    otherwise.
982                  * 
983                  *  - If cursor cannot advance because it has
984                  *    reached the end of the setused list, then we
985                  *    have a maximal disjoint union. Check to see
986                  *    whether its mine count has any useful
987                  *    properties. If so, mark all the squares not
988                  *    in the union as known and terminate.
989                  * 
990                  *  - If cursor has reached the end of setused and
991                  *    the algorithm _hasn't_ terminated, back
992                  *    cursor up to the nearest 1, turn it into a 0
993                  *    and advance cursor just past it.
994                  * 
995                  *  - If we attempt to back up to the nearest 1 and
996                  *    there isn't one at all, then we have gone
997                  *    through all disjoint unions of sets in the
998                  *    list and none of them has been helpful, so we
999                  *    give up.
1000                  */
1001                 struct set *sets[lenof(setused)];
1002                 for (i = 0; i < nsets; i++)
1003                     sets[i] = index234(ss->sets, i);
1004
1005                 cursor = 0;
1006                 while (1) {
1007
1008                     if (cursor < nsets) {
1009                         int ok = TRUE;
1010
1011                         /* See if any existing set overlaps this one. */
1012                         for (i = 0; i < cursor; i++)
1013                             if (setused[i] &&
1014                                 setmunge(sets[cursor]->x,
1015                                          sets[cursor]->y,
1016                                          sets[cursor]->mask,
1017                                          sets[i]->x, sets[i]->y, sets[i]->mask,
1018                                          FALSE)) {
1019                                 ok = FALSE;
1020                                 break;
1021                             }
1022
1023                         if (ok) {
1024                             /*
1025                              * We're adding this set to our union,
1026                              * so adjust minesleft and squaresleft
1027                              * appropriately.
1028                              */
1029                             minesleft -= sets[cursor]->mines;
1030                             squaresleft -= bitcount16(sets[cursor]->mask);
1031                         }
1032
1033                         setused[cursor++] = ok;
1034                     } else {
1035 #ifdef SOLVER_DIAGNOSTICS
1036                         printf("trying a set combination with %d %d\n",
1037                                squaresleft, minesleft);
1038 #endif /* SOLVER_DIAGNOSTICS */
1039
1040                         /*
1041                          * We've reached the end. See if we've got
1042                          * anything interesting.
1043                          */
1044                         if (squaresleft > 0 &&
1045                             (minesleft == 0 || minesleft == squaresleft)) {
1046                             /*
1047                              * We have! There is at least one
1048                              * square not contained within the set
1049                              * union we've just found, and we can
1050                              * deduce that either all such squares
1051                              * are mines or all are not (depending
1052                              * on whether minesleft==0). So now all
1053                              * we have to do is actually go through
1054                              * the grid, find those squares, and
1055                              * mark them.
1056                              */
1057                             for (i = 0; i < w*h; i++)
1058                                 if (grid[i] == -2) {
1059                                     int outside = TRUE;
1060                                     y = i / w;
1061                                     x = i % w;
1062                                     for (j = 0; j < nsets; j++)
1063                                         if (setused[j] &&
1064                                             setmunge(sets[j]->x, sets[j]->y,
1065                                                      sets[j]->mask, x, y, 1,
1066                                                      FALSE)) {
1067                                             outside = FALSE;
1068                                             break;
1069                                         }
1070                                     if (outside)
1071                                         known_squares(w, h, std, grid,
1072                                                       open, ctx,
1073                                                       x, y, 1, minesleft != 0);
1074                                 }
1075
1076                             done_something = TRUE;
1077                             break;     /* return to main deductive loop */
1078                         }
1079
1080                         /*
1081                          * If we reach here, then this union hasn't
1082                          * done us any good, so move on to the
1083                          * next. Backtrack cursor to the nearest 1,
1084                          * change it to a 0 and continue.
1085                          */
1086                         while (--cursor >= 0 && !setused[cursor]);
1087                         if (cursor >= 0) {
1088                             assert(setused[cursor]);
1089
1090                             /*
1091                              * We're removing this set from our
1092                              * union, so re-increment minesleft and
1093                              * squaresleft.
1094                              */
1095                             minesleft += sets[cursor]->mines;
1096                             squaresleft += bitcount16(sets[cursor]->mask);
1097
1098                             setused[cursor++] = 0;
1099                         } else {
1100                             /*
1101                              * We've backtracked all the way to the
1102                              * start without finding a single 1,
1103                              * which means that our virtual
1104                              * recursion is complete and nothing
1105                              * helped.
1106                              */
1107                             break;
1108                         }
1109                     }
1110
1111                 }
1112
1113             }
1114         }
1115
1116         if (done_something)
1117             continue;
1118
1119 #ifdef SOLVER_DIAGNOSTICS
1120         /*
1121          * Dump the current known state of the grid.
1122          */
1123         printf("solver ran out of steam, ret=%d, grid:\n", nperturbs);
1124         for (y = 0; y < h; y++) {
1125             for (x = 0; x < w; x++) {
1126                 int v = grid[y*w+x];
1127                 if (v == -1)
1128                     putchar('*');
1129                 else if (v == -2)
1130                     putchar('?');
1131                 else if (v == 0)
1132                     putchar('-');
1133                 else
1134                     putchar('0' + v);
1135             }
1136             putchar('\n');
1137         }
1138
1139         {
1140             struct set *s;
1141
1142             for (i = 0; (s = index234(ss->sets, i)) != NULL; i++)
1143                 printf("remaining set: %d,%d %03x %d\n", s->x, s->y, s->mask, s->mines);
1144         }
1145 #endif
1146
1147         /*
1148          * Now we really are at our wits' end as far as solving
1149          * this grid goes. Our only remaining option is to call
1150          * a perturb function and ask it to modify the grid to
1151          * make it easier.
1152          */
1153         if (perturb) {
1154             struct perturbations *ret;
1155             struct set *s;
1156
1157             nperturbs++;
1158
1159             /*
1160              * Choose a set at random from the current selection,
1161              * and ask the perturb function to either fill or empty
1162              * it.
1163              * 
1164              * If we have no sets at all, we must give up.
1165              */
1166             if (count234(ss->sets) == 0) {
1167 #ifdef SOLVER_DIAGNOSTICS
1168                 printf("perturbing on entire unknown set\n");
1169 #endif
1170                 ret = perturb(ctx, grid, 0, 0, 0);
1171             } else {
1172                 s = index234(ss->sets, random_upto(rs, count234(ss->sets)));
1173 #ifdef SOLVER_DIAGNOSTICS
1174                 printf("perturbing on set %d,%d %03x\n", s->x, s->y, s->mask);
1175 #endif
1176                 ret = perturb(ctx, grid, s->x, s->y, s->mask);
1177             }
1178
1179             if (ret) {
1180                 assert(ret->n > 0);    /* otherwise should have been NULL */
1181
1182                 /*
1183                  * A number of squares have been fiddled with, and
1184                  * the returned structure tells us which. Adjust
1185                  * the mine count in any set which overlaps one of
1186                  * those squares, and put them back on the to-do
1187                  * list. Also, if the square itself is marked as a
1188                  * known non-mine, put it back on the squares-to-do
1189                  * list.
1190                  */
1191                 for (i = 0; i < ret->n; i++) {
1192 #ifdef SOLVER_DIAGNOSTICS
1193                     printf("perturbation %s mine at %d,%d\n",
1194                            ret->changes[i].delta > 0 ? "added" : "removed",
1195                            ret->changes[i].x, ret->changes[i].y);
1196 #endif
1197
1198                     if (ret->changes[i].delta < 0 &&
1199                         grid[ret->changes[i].y*w+ret->changes[i].x] != -2) {
1200                         std_add(std, ret->changes[i].y*w+ret->changes[i].x);
1201                     }
1202
1203                     list = ss_overlap(ss,
1204                                       ret->changes[i].x, ret->changes[i].y, 1);
1205
1206                     for (j = 0; list[j]; j++) {
1207                         list[j]->mines += ret->changes[i].delta;
1208                         ss_add_todo(ss, list[j]);
1209                     }
1210
1211                     sfree(list);
1212                 }
1213
1214                 /*
1215                  * Now free the returned data.
1216                  */
1217                 sfree(ret->changes);
1218                 sfree(ret);
1219
1220 #ifdef SOLVER_DIAGNOSTICS
1221                 /*
1222                  * Dump the current known state of the grid.
1223                  */
1224                 printf("state after perturbation:\n");
1225                 for (y = 0; y < h; y++) {
1226                     for (x = 0; x < w; x++) {
1227                         int v = grid[y*w+x];
1228                         if (v == -1)
1229                             putchar('*');
1230                         else if (v == -2)
1231                             putchar('?');
1232                         else if (v == 0)
1233                             putchar('-');
1234                         else
1235                             putchar('0' + v);
1236                     }
1237                     putchar('\n');
1238                 }
1239
1240                 {
1241                     struct set *s;
1242
1243                     for (i = 0; (s = index234(ss->sets, i)) != NULL; i++)
1244                         printf("remaining set: %d,%d %03x %d\n", s->x, s->y, s->mask, s->mines);
1245                 }
1246 #endif
1247
1248                 /*
1249                  * And now we can go back round the deductive loop.
1250                  */
1251                 continue;
1252             }
1253         }
1254
1255         /*
1256          * If we get here, even that didn't work (either we didn't
1257          * have a perturb function or it returned failure), so we
1258          * give up entirely.
1259          */
1260         break;
1261     }
1262
1263     /*
1264      * See if we've got any unknown squares left.
1265      */
1266     for (y = 0; y < h; y++)
1267         for (x = 0; x < w; x++)
1268             if (grid[y*w+x] == -2) {
1269                 nperturbs = -1;        /* failed to complete */
1270                 break;
1271             }
1272
1273     /*
1274      * Free the set list and square-todo list.
1275      */
1276     {
1277         struct set *s;
1278         while ((s = delpos234(ss->sets, 0)) != NULL)
1279             sfree(s);
1280         freetree234(ss->sets);
1281         sfree(ss);
1282         sfree(std->next);
1283     }
1284
1285     return nperturbs;
1286 }
1287
1288 /* ----------------------------------------------------------------------
1289  * Grid generator which uses the above solver.
1290  */
1291
1292 struct minectx {
1293     signed char *grid;
1294     int w, h;
1295     int sx, sy;
1296     int allow_big_perturbs;
1297     random_state *rs;
1298 };
1299
1300 static int mineopen(void *vctx, int x, int y)
1301 {
1302     struct minectx *ctx = (struct minectx *)vctx;
1303     int i, j, n;
1304
1305     assert(x >= 0 && x < ctx->w && y >= 0 && y < ctx->h);
1306     if (ctx->grid[y * ctx->w + x])
1307         return -1;                     /* *bang* */
1308
1309     n = 0;
1310     for (i = -1; i <= +1; i++) {
1311         if (x + i < 0 || x + i >= ctx->w)
1312             continue;
1313         for (j = -1; j <= +1; j++) {
1314             if (y + j < 0 || y + j >= ctx->h)
1315                 continue;
1316             if (i == 0 && j == 0)
1317                 continue;
1318             if (ctx->grid[(y+j) * ctx->w + (x+i)])
1319                 n++;
1320         }
1321     }
1322
1323     return n;
1324 }
1325
1326 /* Structure used internally to mineperturb(). */
1327 struct square {
1328     int x, y, type, random;
1329 };
1330 static int squarecmp(const void *av, const void *bv)
1331 {
1332     const struct square *a = (const struct square *)av;
1333     const struct square *b = (const struct square *)bv;
1334     if (a->type < b->type)
1335         return -1;
1336     else if (a->type > b->type)
1337         return +1;
1338     else if (a->random < b->random)
1339         return -1;
1340     else if (a->random > b->random)
1341         return +1;
1342     else if (a->y < b->y)
1343         return -1;
1344     else if (a->y > b->y)
1345         return +1;
1346     else if (a->x < b->x)
1347         return -1;
1348     else if (a->x > b->x)
1349         return +1;
1350     return 0;
1351 }
1352
1353 /*
1354  * Normally this function is passed an (x,y,mask) set description.
1355  * On occasions, though, there is no _localised_ set being used,
1356  * and the set being perturbed is supposed to be the entirety of
1357  * the unreachable area. This is signified by the special case
1358  * mask==0: in this case, anything labelled -2 in the grid is part
1359  * of the set.
1360  * 
1361  * Allowing perturbation in this special case appears to make it
1362  * guaranteeably possible to generate a workable grid for any mine
1363  * density, but they tend to be a bit boring, with mines packed
1364  * densely into far corners of the grid and the remainder being
1365  * less dense than one might like. Therefore, to improve overall
1366  * grid quality I disable this feature for the first few attempts,
1367  * and fall back to it after no useful grid has been generated.
1368  */
1369 static struct perturbations *mineperturb(void *vctx, signed char *grid,
1370                                          int setx, int sety, int mask)
1371 {
1372     struct minectx *ctx = (struct minectx *)vctx;
1373     struct square *sqlist;
1374     int x, y, dx, dy, i, n, nfull, nempty;
1375     struct square **tofill, **toempty, **todo;
1376     int ntofill, ntoempty, ntodo, dtodo, dset;
1377     struct perturbations *ret;
1378     int *setlist;
1379
1380     if (!mask && !ctx->allow_big_perturbs)
1381         return NULL;
1382
1383     /*
1384      * Make a list of all the squares in the grid which we can
1385      * possibly use. This list should be in preference order, which
1386      * means
1387      * 
1388      *  - first, unknown squares on the boundary of known space
1389      *  - next, unknown squares beyond that boundary
1390      *  - as a very last resort, known squares, but not within one
1391      *    square of the starting position.
1392      * 
1393      * Each of these sections needs to be shuffled independently.
1394      * We do this by preparing list of all squares and then sorting
1395      * it with a random secondary key.
1396      */
1397     sqlist = snewn(ctx->w * ctx->h, struct square);
1398     n = 0;
1399     for (y = 0; y < ctx->h; y++)
1400         for (x = 0; x < ctx->w; x++) {
1401             /*
1402              * If this square is too near the starting position,
1403              * don't put it on the list at all.
1404              */
1405             if (abs(y - ctx->sy) <= 1 && abs(x - ctx->sx) <= 1)
1406                 continue;
1407
1408             /*
1409              * If this square is in the input set, also don't put
1410              * it on the list!
1411              */
1412             if ((mask == 0 && grid[y*ctx->w+x] == -2) ||
1413                 (x >= setx && x < setx + 3 &&
1414                  y >= sety && y < sety + 3 &&
1415                  mask & (1 << ((y-sety)*3+(x-setx)))))
1416                 continue;
1417
1418             sqlist[n].x = x;
1419             sqlist[n].y = y;
1420
1421             if (grid[y*ctx->w+x] != -2) {
1422                 sqlist[n].type = 3;    /* known square */
1423             } else {
1424                 /*
1425                  * Unknown square. Examine everything around it and
1426                  * see if it borders on any known squares. If it
1427                  * does, it's class 1, otherwise it's 2.
1428                  */
1429
1430                 sqlist[n].type = 2;
1431
1432                 for (dy = -1; dy <= +1; dy++)
1433                     for (dx = -1; dx <= +1; dx++)
1434                         if (x+dx >= 0 && x+dx < ctx->w &&
1435                             y+dy >= 0 && y+dy < ctx->h &&
1436                             grid[(y+dy)*ctx->w+(x+dx)] != -2) {
1437                             sqlist[n].type = 1;
1438                             break;
1439                         }
1440             }
1441
1442             /*
1443              * Finally, a random number to cause qsort to
1444              * shuffle within each group.
1445              */
1446             sqlist[n].random = random_bits(ctx->rs, 31);
1447
1448             n++;
1449         }
1450
1451     qsort(sqlist, n, sizeof(struct square), squarecmp);
1452
1453     /*
1454      * Now count up the number of full and empty squares in the set
1455      * we've been provided.
1456      */
1457     nfull = nempty = 0;
1458     if (mask) {
1459         for (dy = 0; dy < 3; dy++)
1460             for (dx = 0; dx < 3; dx++)
1461                 if (mask & (1 << (dy*3+dx))) {
1462                     assert(setx+dx <= ctx->w);
1463                     assert(sety+dy <= ctx->h);
1464                     if (ctx->grid[(sety+dy)*ctx->w+(setx+dx)])
1465                         nfull++;
1466                     else
1467                         nempty++;
1468                 }
1469     } else {
1470         for (y = 0; y < ctx->h; y++)
1471             for (x = 0; x < ctx->w; x++)
1472                 if (grid[y*ctx->w+x] == -2) {
1473                     if (ctx->grid[y*ctx->w+x])
1474                         nfull++;
1475                     else
1476                         nempty++;
1477                 }
1478     }
1479
1480     /*
1481      * Now go through our sorted list until we find either `nfull'
1482      * empty squares, or `nempty' full squares; these will be
1483      * swapped with the appropriate squares in the set to either
1484      * fill or empty the set while keeping the same number of mines
1485      * overall.
1486      */
1487     ntofill = ntoempty = 0;
1488     if (mask) {
1489         tofill = snewn(9, struct square *);
1490         toempty = snewn(9, struct square *);
1491     } else {
1492         tofill = snewn(ctx->w * ctx->h, struct square *);
1493         toempty = snewn(ctx->w * ctx->h, struct square *);
1494     }
1495     for (i = 0; i < n; i++) {
1496         struct square *sq = &sqlist[i];
1497         if (ctx->grid[sq->y * ctx->w + sq->x])
1498             toempty[ntoempty++] = sq;
1499         else
1500             tofill[ntofill++] = sq;
1501         if (ntofill == nfull || ntoempty == nempty)
1502             break;
1503     }
1504
1505     /*
1506      * If we haven't found enough empty squares outside the set to
1507      * empty it into _or_ enough full squares outside it to fill it
1508      * up with, we'll have to settle for doing only a partial job.
1509      * In this case we choose to always _fill_ the set (because
1510      * this case will tend to crop up when we're working with very
1511      * high mine densities and the only way to get a solvable grid
1512      * is going to be to pack most of the mines solidly around the
1513      * edges). So now our job is to make a list of the empty
1514      * squares in the set, and shuffle that list so that we fill a
1515      * random selection of them.
1516      */
1517     if (ntofill != nfull && ntoempty != nempty) {
1518         int k;
1519
1520         assert(ntoempty != 0);
1521
1522         setlist = snewn(ctx->w * ctx->h, int);
1523         i = 0;
1524         if (mask) {
1525             for (dy = 0; dy < 3; dy++)
1526                 for (dx = 0; dx < 3; dx++)
1527                     if (mask & (1 << (dy*3+dx))) {
1528                         assert(setx+dx <= ctx->w);
1529                         assert(sety+dy <= ctx->h);
1530                         if (!ctx->grid[(sety+dy)*ctx->w+(setx+dx)])
1531                             setlist[i++] = (sety+dy)*ctx->w+(setx+dx);
1532                     }
1533         } else {
1534             for (y = 0; y < ctx->h; y++)
1535                 for (x = 0; x < ctx->w; x++)
1536                     if (grid[y*ctx->w+x] == -2) {
1537                         if (!ctx->grid[y*ctx->w+x])
1538                             setlist[i++] = y*ctx->w+x;
1539                     }
1540         }
1541         assert(i > ntoempty);
1542         /*
1543          * Now pick `ntoempty' items at random from the list.
1544          */
1545         for (k = 0; k < ntoempty; k++) {
1546             int index = k + random_upto(ctx->rs, i - k);
1547             int tmp;
1548
1549             tmp = setlist[k];
1550             setlist[k] = setlist[index];
1551             setlist[index] = tmp;
1552         }
1553     } else
1554         setlist = NULL;
1555
1556     /*
1557      * Now we're pretty much there. We need to either
1558      *  (a) put a mine in each of the empty squares in the set, and
1559      *      take one out of each square in `toempty'
1560      *  (b) take a mine out of each of the full squares in the set,
1561      *      and put one in each square in `tofill'
1562      * depending on which one we've found enough squares to do.
1563      * 
1564      * So we start by constructing our list of changes to return to
1565      * the solver, so that it can update its data structures
1566      * efficiently rather than having to rescan the whole grid.
1567      */
1568     ret = snew(struct perturbations);
1569     if (ntofill == nfull) {
1570         todo = tofill;
1571         ntodo = ntofill;
1572         dtodo = +1;
1573         dset = -1;
1574         sfree(toempty);
1575     } else {
1576         /*
1577          * (We also fall into this case if we've constructed a
1578          * setlist.)
1579          */
1580         todo = toempty;
1581         ntodo = ntoempty;
1582         dtodo = -1;
1583         dset = +1;
1584         sfree(tofill);
1585     }
1586     ret->n = 2 * ntodo;
1587     ret->changes = snewn(ret->n, struct perturbation);
1588     for (i = 0; i < ntodo; i++) {
1589         ret->changes[i].x = todo[i]->x;
1590         ret->changes[i].y = todo[i]->y;
1591         ret->changes[i].delta = dtodo;
1592     }
1593     /* now i == ntodo */
1594     if (setlist) {
1595         int j;
1596         assert(todo == toempty);
1597         for (j = 0; j < ntoempty; j++) {
1598             ret->changes[i].x = setlist[j] % ctx->w;
1599             ret->changes[i].y = setlist[j] / ctx->w;
1600             ret->changes[i].delta = dset;
1601             i++;
1602         }
1603         sfree(setlist);
1604     } else if (mask) {
1605         for (dy = 0; dy < 3; dy++)
1606             for (dx = 0; dx < 3; dx++)
1607                 if (mask & (1 << (dy*3+dx))) {
1608                     int currval = (ctx->grid[(sety+dy)*ctx->w+(setx+dx)] ? +1 : -1);
1609                     if (dset == -currval) {
1610                         ret->changes[i].x = setx + dx;
1611                         ret->changes[i].y = sety + dy;
1612                         ret->changes[i].delta = dset;
1613                         i++;
1614                     }
1615                 }
1616     } else {
1617         for (y = 0; y < ctx->h; y++)
1618             for (x = 0; x < ctx->w; x++)
1619                 if (grid[y*ctx->w+x] == -2) {
1620                     int currval = (ctx->grid[y*ctx->w+x] ? +1 : -1);
1621                     if (dset == -currval) {
1622                         ret->changes[i].x = x;
1623                         ret->changes[i].y = y;
1624                         ret->changes[i].delta = dset;
1625                         i++;
1626                     }
1627                 }
1628     }
1629     assert(i == ret->n);
1630
1631     sfree(sqlist);
1632     sfree(todo);
1633
1634     /*
1635      * Having set up the precise list of changes we're going to
1636      * make, we now simply make them and return.
1637      */
1638     for (i = 0; i < ret->n; i++) {
1639         int delta;
1640
1641         x = ret->changes[i].x;
1642         y = ret->changes[i].y;
1643         delta = ret->changes[i].delta;
1644
1645         /*
1646          * Check we're not trying to add an existing mine or remove
1647          * an absent one.
1648          */
1649         assert((delta < 0) ^ (ctx->grid[y*ctx->w+x] == 0));
1650
1651         /*
1652          * Actually make the change.
1653          */
1654         ctx->grid[y*ctx->w+x] = (delta > 0);
1655
1656         /*
1657          * Update any numbers already present in the grid.
1658          */
1659         for (dy = -1; dy <= +1; dy++)
1660             for (dx = -1; dx <= +1; dx++)
1661                 if (x+dx >= 0 && x+dx < ctx->w &&
1662                     y+dy >= 0 && y+dy < ctx->h &&
1663                     grid[(y+dy)*ctx->w+(x+dx)] != -2) {
1664                     if (dx == 0 && dy == 0) {
1665                         /*
1666                          * The square itself is marked as known in
1667                          * the grid. Mark it as a mine if it's a
1668                          * mine, or else work out its number.
1669                          */
1670                         if (delta > 0) {
1671                             grid[y*ctx->w+x] = -1;
1672                         } else {
1673                             int dx2, dy2, minecount = 0;
1674                             for (dy2 = -1; dy2 <= +1; dy2++)
1675                                 for (dx2 = -1; dx2 <= +1; dx2++)
1676                                     if (x+dx2 >= 0 && x+dx2 < ctx->w &&
1677                                         y+dy2 >= 0 && y+dy2 < ctx->h &&
1678                                         ctx->grid[(y+dy2)*ctx->w+(x+dx2)])
1679                                         minecount++;
1680                             grid[y*ctx->w+x] = minecount;
1681                         }
1682                     } else {
1683                         if (grid[(y+dy)*ctx->w+(x+dx)] >= 0)
1684                             grid[(y+dy)*ctx->w+(x+dx)] += delta;
1685                     }
1686                 }
1687     }
1688
1689 #ifdef GENERATION_DIAGNOSTICS
1690     {
1691         int yy, xx;
1692         printf("grid after perturbing:\n");
1693         for (yy = 0; yy < ctx->h; yy++) {
1694             for (xx = 0; xx < ctx->w; xx++) {
1695                 int v = ctx->grid[yy*ctx->w+xx];
1696                 if (yy == ctx->sy && xx == ctx->sx) {
1697                     assert(!v);
1698                     putchar('S');
1699                 } else if (v) {
1700                     putchar('*');
1701                 } else {
1702                     putchar('-');
1703                 }
1704             }
1705             putchar('\n');
1706         }
1707         printf("\n");
1708     }
1709 #endif
1710
1711     return ret;
1712 }
1713
1714 static char *minegen(int w, int h, int n, int x, int y, int unique,
1715                      random_state *rs)
1716 {
1717     char *ret = snewn(w*h, char);
1718     int success;
1719     int ntries = 0;
1720
1721     do {
1722         success = FALSE;
1723         ntries++;
1724
1725         memset(ret, 0, w*h);
1726
1727         /*
1728          * Start by placing n mines, none of which is at x,y or within
1729          * one square of it.
1730          */
1731         {
1732             int *tmp = snewn(w*h, int);
1733             int i, j, k, nn;
1734
1735             /*
1736              * Write down the list of possible mine locations.
1737              */
1738             k = 0;
1739             for (i = 0; i < h; i++)
1740                 for (j = 0; j < w; j++)
1741                     if (abs(i - y) > 1 || abs(j - x) > 1)
1742                         tmp[k++] = i*w+j;
1743
1744             /*
1745              * Now pick n off the list at random.
1746              */
1747             nn = n;
1748             while (nn-- > 0) {
1749                 i = random_upto(rs, k);
1750                 ret[tmp[i]] = 1;
1751                 tmp[i] = tmp[--k];
1752             }
1753
1754             sfree(tmp);
1755         }
1756
1757 #ifdef GENERATION_DIAGNOSTICS
1758         {
1759             int yy, xx;
1760             printf("grid after initial generation:\n");
1761             for (yy = 0; yy < h; yy++) {
1762                 for (xx = 0; xx < w; xx++) {
1763                     int v = ret[yy*w+xx];
1764                     if (yy == y && xx == x) {
1765                         assert(!v);
1766                         putchar('S');
1767                     } else if (v) {
1768                         putchar('*');
1769                     } else {
1770                         putchar('-');
1771                     }
1772                 }
1773                 putchar('\n');
1774             }
1775             printf("\n");
1776         }
1777 #endif
1778
1779         /*
1780          * Now set up a results grid to run the solver in, and a
1781          * context for the solver to open squares. Then run the solver
1782          * repeatedly; if the number of perturb steps ever goes up or
1783          * it ever returns -1, give up completely.
1784          *
1785          * We bypass this bit if we're not after a unique grid.
1786          */
1787         if (unique) {
1788             signed char *solvegrid = snewn(w*h, char);
1789             struct minectx actx, *ctx = &actx;
1790             int solveret, prevret = -2;
1791
1792             ctx->grid = ret;
1793             ctx->w = w;
1794             ctx->h = h;
1795             ctx->sx = x;
1796             ctx->sy = y;
1797             ctx->rs = rs;
1798             ctx->allow_big_perturbs = (ntries > 100);
1799
1800             while (1) {
1801                 memset(solvegrid, -2, w*h);
1802                 solvegrid[y*w+x] = mineopen(ctx, x, y);
1803                 assert(solvegrid[y*w+x] == 0); /* by deliberate arrangement */
1804
1805                 solveret =
1806                     minesolve(w, h, n, solvegrid, mineopen, mineperturb, ctx, rs);
1807                 if (solveret < 0 || (prevret >= 0 && solveret >= prevret)) {
1808                     success = FALSE;
1809                     break;
1810                 } else if (solveret == 0) {
1811                     success = TRUE;
1812                     break;
1813                 }
1814             }
1815
1816             sfree(solvegrid);
1817         } else {
1818             success = TRUE;
1819         }
1820
1821     } while (!success);
1822
1823     return ret;
1824 }
1825
1826 /*
1827  * The Mines game descriptions contain the location of every mine,
1828  * and can therefore be used to cheat.
1829  * 
1830  * It would be pointless to attempt to _prevent_ this form of
1831  * cheating by encrypting the description, since Mines is
1832  * open-source so anyone can find out the encryption key. However,
1833  * I think it is worth doing a bit of gentle obfuscation to prevent
1834  * _accidental_ spoilers: if you happened to note that the game ID
1835  * starts with an F, for example, you might be unable to put the
1836  * knowledge of those mines out of your mind while playing. So,
1837  * just as discussions of film endings are rot13ed to avoid
1838  * spoiling it for people who don't want to be told, we apply a
1839  * keyless, reversible, but visually completely obfuscatory masking
1840  * function to the mine bitmap.
1841  */
1842 static void obfuscate_bitmap(unsigned char *bmp, int bits, int decode)
1843 {
1844     int bytes, firsthalf, secondhalf;
1845     struct step {
1846         unsigned char *seedstart;
1847         int seedlen;
1848         unsigned char *targetstart;
1849         int targetlen;
1850     } steps[2];
1851     int i, j;
1852
1853     /*
1854      * My obfuscation algorithm is similar in concept to the OAEP
1855      * encoding used in some forms of RSA. Here's a specification
1856      * of it:
1857      * 
1858      *  + We have a `masking function' which constructs a stream of
1859      *    pseudorandom bytes from a seed of some number of input
1860      *    bytes.
1861      * 
1862      *  + We pad out our input bit stream to a whole number of
1863      *    bytes by adding up to 7 zero bits on the end. (In fact
1864      *    the bitmap passed as input to this function will already
1865      *    have had this done in practice.)
1866      * 
1867      *  + We divide the _byte_ stream exactly in half, rounding the
1868      *    half-way position _down_. So an 81-bit input string, for
1869      *    example, rounds up to 88 bits or 11 bytes, and then
1870      *    dividing by two gives 5 bytes in the first half and 6 in
1871      *    the second half.
1872      * 
1873      *  + We generate a mask from the second half of the bytes, and
1874      *    XOR it over the first half.
1875      * 
1876      *  + We generate a mask from the (encoded) first half of the
1877      *    bytes, and XOR it over the second half. Any null bits at
1878      *    the end which were added as padding are cleared back to
1879      *    zero even if this operation would have made them nonzero.
1880      * 
1881      * To de-obfuscate, the steps are precisely the same except
1882      * that the final two are reversed.
1883      * 
1884      * Finally, our masking function. Given an input seed string of
1885      * bytes, the output mask consists of concatenating the SHA-1
1886      * hashes of the seed string and successive decimal integers,
1887      * starting from 0.
1888      */
1889
1890     bytes = (bits + 7) / 8;
1891     firsthalf = bytes / 2;
1892     secondhalf = bytes - firsthalf;
1893
1894     steps[decode ? 1 : 0].seedstart = bmp + firsthalf;
1895     steps[decode ? 1 : 0].seedlen = secondhalf;
1896     steps[decode ? 1 : 0].targetstart = bmp;
1897     steps[decode ? 1 : 0].targetlen = firsthalf;
1898
1899     steps[decode ? 0 : 1].seedstart = bmp;
1900     steps[decode ? 0 : 1].seedlen = firsthalf;
1901     steps[decode ? 0 : 1].targetstart = bmp + firsthalf;
1902     steps[decode ? 0 : 1].targetlen = secondhalf;
1903
1904     for (i = 0; i < 2; i++) {
1905         SHA_State base, final;
1906         unsigned char digest[20];
1907         char numberbuf[80];
1908         int digestpos = 20, counter = 0;
1909
1910         SHA_Init(&base);
1911         SHA_Bytes(&base, steps[i].seedstart, steps[i].seedlen);
1912
1913         for (j = 0; j < steps[i].targetlen; j++) {
1914             if (digestpos >= 20) {
1915                 sprintf(numberbuf, "%d", counter++);
1916                 final = base;
1917                 SHA_Bytes(&final, numberbuf, strlen(numberbuf));
1918                 SHA_Final(&final, digest);
1919                 digestpos = 0;
1920             }
1921             steps[i].targetstart[j] ^= digest[digestpos++];
1922         }
1923
1924         /*
1925          * Mask off the pad bits in the final byte after both steps.
1926          */
1927         if (bits % 8)
1928             bmp[bits / 8] &= 0xFF & (0xFF00 >> (bits % 8));
1929     }
1930 }
1931
1932 static char *new_mine_layout(int w, int h, int n, int x, int y, int unique,
1933                              random_state *rs, char **game_desc)
1934 {
1935     signed char *grid, *ret, *p;
1936     unsigned char *bmp;
1937     int i, area;
1938
1939 #ifdef TEST_OBFUSCATION
1940     static int tested_obfuscation = FALSE;
1941     if (!tested_obfuscation) {
1942         /*
1943          * A few simple test vectors for the obfuscator.
1944          * 
1945          * First test: the 28-bit stream 1234567. This divides up
1946          * into 1234 and 567[0]. The SHA of 56 70 30 (appending
1947          * "0") is 15ce8ab946640340bbb99f3f48fd2c45d1a31d30. Thus,
1948          * we XOR the 16-bit string 15CE into the input 1234 to get
1949          * 07FA. Next, we SHA that with "0": the SHA of 07 FA 30 is
1950          * 3370135c5e3da4fed937adc004a79533962b6391. So we XOR the
1951          * 12-bit string 337 into the input 567 to get 650. Thus
1952          * our output is 07FA650.
1953          */
1954         {
1955             unsigned char bmp1[] = "\x12\x34\x56\x70";
1956             obfuscate_bitmap(bmp1, 28, FALSE);
1957             printf("test 1 encode: %s\n",
1958                    memcmp(bmp1, "\x07\xfa\x65\x00", 4) ? "failed" : "passed");
1959             obfuscate_bitmap(bmp1, 28, TRUE);
1960             printf("test 1 decode: %s\n",
1961                    memcmp(bmp1, "\x12\x34\x56\x70", 4) ? "failed" : "passed");
1962         }
1963         /*
1964          * Second test: a long string to make sure we switch from
1965          * one SHA to the next correctly. My input string this time
1966          * is simply fifty bytes of zeroes.
1967          */
1968         {
1969             unsigned char bmp2[50];
1970             unsigned char bmp2a[50];
1971             memset(bmp2, 0, 50);
1972             memset(bmp2a, 0, 50);
1973             obfuscate_bitmap(bmp2, 50 * 8, FALSE);
1974             /*
1975              * SHA of twenty-five zero bytes plus "0" is
1976              * b202c07b990c01f6ff2d544707f60e506019b671. SHA of
1977              * twenty-five zero bytes plus "1" is
1978              * fcb1d8b5a2f6b592fe6780b36aa9d65dd7aa6db9. Thus our
1979              * first half becomes
1980              * b202c07b990c01f6ff2d544707f60e506019b671fcb1d8b5a2.
1981              * 
1982              * SHA of that lot plus "0" is
1983              * 10b0af913db85d37ca27f52a9f78bba3a80030db. SHA of the
1984              * same string plus "1" is
1985              * 3d01d8df78e76d382b8106f480135a1bc751d725. So the
1986              * second half becomes
1987              * 10b0af913db85d37ca27f52a9f78bba3a80030db3d01d8df78.
1988              */
1989             printf("test 2 encode: %s\n",
1990                    memcmp(bmp2, "\xb2\x02\xc0\x7b\x99\x0c\x01\xf6\xff\x2d\x54"
1991                           "\x47\x07\xf6\x0e\x50\x60\x19\xb6\x71\xfc\xb1\xd8"
1992                           "\xb5\xa2\x10\xb0\xaf\x91\x3d\xb8\x5d\x37\xca\x27"
1993                           "\xf5\x2a\x9f\x78\xbb\xa3\xa8\x00\x30\xdb\x3d\x01"
1994                           "\xd8\xdf\x78", 50) ? "failed" : "passed");
1995             obfuscate_bitmap(bmp2, 50 * 8, TRUE);
1996             printf("test 2 decode: %s\n",
1997                    memcmp(bmp2, bmp2a, 50) ? "failed" : "passed");
1998         }
1999     }
2000 #endif
2001
2002     grid = minegen(w, h, n, x, y, unique, rs);
2003
2004     if (game_desc) {
2005         /*
2006          * Set up the mine bitmap and obfuscate it.
2007          */
2008         area = w * h;
2009         bmp = snewn((area + 7) / 8, unsigned char);
2010         memset(bmp, 0, (area + 7) / 8);
2011         for (i = 0; i < area; i++) {
2012             if (grid[i])
2013                 bmp[i / 8] |= 0x80 >> (i % 8);
2014         }
2015         obfuscate_bitmap(bmp, area, FALSE);
2016
2017         /*
2018          * Now encode the resulting bitmap in hex. We can work to
2019          * nibble rather than byte granularity, since the obfuscation
2020          * function guarantees to return a bit string of the same
2021          * length as its input.
2022          */
2023         ret = snewn((area+3)/4 + 100, char);
2024         p = ret + sprintf(ret, "%d,%d,m", x, y);   /* 'm' == masked */
2025         for (i = 0; i < (area+3)/4; i++) {
2026             int v = bmp[i/2];
2027             if (i % 2 == 0)
2028                 v >>= 4;
2029             *p++ = "0123456789abcdef"[v & 0xF];
2030         }
2031         *p = '\0';
2032
2033         sfree(bmp);
2034
2035         *game_desc = ret;
2036     }   
2037
2038     return grid;
2039 }
2040
2041 static char *new_game_desc(game_params *params, random_state *rs,
2042                            game_aux_info **aux, int interactive)
2043 {
2044     if (!interactive) {
2045         /*
2046          * For batch-generated grids, pre-open one square.
2047          */
2048         int x = random_upto(rs, params->w);
2049         int y = random_upto(rs, params->h);
2050         signed char *grid;
2051         char *desc;
2052
2053         grid = new_mine_layout(params->w, params->h, params->n,
2054                                x, y, params->unique, rs, &desc);
2055         sfree(grid);
2056         return desc;
2057     } else {
2058         char *rsdesc, *desc;
2059
2060         rsdesc = random_state_encode(rs);
2061         desc = snewn(strlen(rsdesc) + 100, char);
2062         sprintf(desc, "r%d,%c,%s", params->n, params->unique ? 'u' : 'a', rsdesc);
2063         sfree(rsdesc);
2064         return desc;
2065     }
2066 }
2067
2068 static void game_free_aux_info(game_aux_info *aux)
2069 {
2070     assert(!"Shouldn't happen");
2071 }
2072
2073 static char *validate_desc(game_params *params, char *desc)
2074 {
2075     int wh = params->w * params->h;
2076     int x, y;
2077
2078     if (*desc == 'r') {
2079         if (!*desc || !isdigit((unsigned char)*desc))
2080             return "No initial mine count in game description";
2081         while (*desc && isdigit((unsigned char)*desc))
2082             desc++;                    /* skip over mine count */
2083         if (*desc != ',')
2084             return "No ',' after initial x-coordinate in game description";
2085         desc++;
2086         if (*desc != 'u' && *desc != 'a')
2087             return "No uniqueness specifier in game description";
2088         desc++;
2089         if (*desc != ',')
2090             return "No ',' after uniqueness specifier in game description";
2091         /* now ignore the rest */
2092     } else {
2093         if (!*desc || !isdigit((unsigned char)*desc))
2094             return "No initial x-coordinate in game description";
2095         x = atoi(desc);
2096         if (x < 0 || x >= params->w)
2097             return "Initial x-coordinate was out of range";
2098         while (*desc && isdigit((unsigned char)*desc))
2099             desc++;                    /* skip over x coordinate */
2100         if (*desc != ',')
2101             return "No ',' after initial x-coordinate in game description";
2102         desc++;                        /* eat comma */
2103         if (!*desc || !isdigit((unsigned char)*desc))
2104             return "No initial y-coordinate in game description";
2105         y = atoi(desc);
2106         if (y < 0 || y >= params->h)
2107             return "Initial y-coordinate was out of range";
2108         while (*desc && isdigit((unsigned char)*desc))
2109             desc++;                    /* skip over y coordinate */
2110         if (*desc != ',')
2111             return "No ',' after initial y-coordinate in game description";
2112         desc++;                        /* eat comma */
2113         /* eat `m', meaning `masked', if present */
2114         if (*desc == 'm')
2115             desc++;
2116         /* now just check length of remainder */
2117         if (strlen(desc) != (wh+3)/4)
2118             return "Game description is wrong length";
2119     }
2120
2121     return NULL;
2122 }
2123
2124 static int open_square(game_state *state, int x, int y)
2125 {
2126     int w = state->w, h = state->h;
2127     int xx, yy, nmines, ncovered;
2128
2129     if (!state->layout->mines) {
2130         /*
2131          * We have a preliminary game in which the mine layout
2132          * hasn't been generated yet. Generate it based on the
2133          * initial click location.
2134          */
2135         char *desc;
2136         state->layout->mines = new_mine_layout(w, h, state->layout->n,
2137                                                x, y, state->layout->unique,
2138                                                state->layout->rs,
2139                                                &desc);
2140         midend_supersede_game_desc(state->layout->me, desc);
2141         sfree(desc);
2142         random_free(state->layout->rs);
2143         state->layout->rs = NULL;
2144     }
2145
2146     if (state->layout->mines[y*w+x]) {
2147         /*
2148          * The player has landed on a mine. Bad luck. Expose the
2149          * mine that killed them, but not the rest (in case they
2150          * want to Undo and carry on playing).
2151          */
2152         state->dead = TRUE;
2153         state->grid[y*w+x] = 65;
2154         return -1;
2155     }
2156
2157     /*
2158      * Otherwise, the player has opened a safe square. Mark it to-do.
2159      */
2160     state->grid[y*w+x] = -10;          /* `todo' value internal to this func */
2161
2162     /*
2163      * Now go through the grid finding all `todo' values and
2164      * opening them. Every time one of them turns out to have no
2165      * neighbouring mines, we add all its unopened neighbours to
2166      * the list as well.
2167      * 
2168      * FIXME: We really ought to be able to do this better than
2169      * using repeated N^2 scans of the grid.
2170      */
2171     while (1) {
2172         int done_something = FALSE;
2173
2174         for (yy = 0; yy < h; yy++)
2175             for (xx = 0; xx < w; xx++)
2176                 if (state->grid[yy*w+xx] == -10) {
2177                     int dx, dy, v;
2178
2179                     assert(!state->layout->mines[yy*w+xx]);
2180
2181                     v = 0;
2182
2183                     for (dx = -1; dx <= +1; dx++)
2184                         for (dy = -1; dy <= +1; dy++)
2185                             if (xx+dx >= 0 && xx+dx < state->w &&
2186                                 yy+dy >= 0 && yy+dy < state->h &&
2187                                 state->layout->mines[(yy+dy)*w+(xx+dx)])
2188                                 v++;
2189
2190                     state->grid[yy*w+xx] = v;
2191
2192                     if (v == 0) {
2193                         for (dx = -1; dx <= +1; dx++)
2194                             for (dy = -1; dy <= +1; dy++)
2195                                 if (xx+dx >= 0 && xx+dx < state->w &&
2196                                     yy+dy >= 0 && yy+dy < state->h &&
2197                                     state->grid[(yy+dy)*w+(xx+dx)] == -2)
2198                                     state->grid[(yy+dy)*w+(xx+dx)] = -10;
2199                     }
2200
2201                     done_something = TRUE;
2202                 }
2203
2204         if (!done_something)
2205             break;
2206     }
2207
2208     /*
2209      * Finally, scan the grid and see if exactly as many squares
2210      * are still covered as there are mines. If so, set the `won'
2211      * flag and fill in mine markers on all covered squares.
2212      */
2213     nmines = ncovered = 0;
2214     for (yy = 0; yy < h; yy++)
2215         for (xx = 0; xx < w; xx++) {
2216             if (state->grid[yy*w+xx] < 0)
2217                 ncovered++;
2218             if (state->layout->mines[yy*w+xx])
2219                 nmines++;
2220         }
2221     assert(ncovered >= nmines);
2222     if (ncovered == nmines) {
2223         for (yy = 0; yy < h; yy++)
2224             for (xx = 0; xx < w; xx++) {
2225                 if (state->grid[yy*w+xx] < 0)
2226                     state->grid[yy*w+xx] = -1;
2227         }
2228         state->won = TRUE;
2229     }
2230
2231     return 0;
2232 }
2233
2234 static game_state *new_game(midend_data *me, game_params *params, char *desc)
2235 {
2236     game_state *state = snew(game_state);
2237     int i, wh, x, y, ret, masked;
2238     unsigned char *bmp;
2239
2240     state->w = params->w;
2241     state->h = params->h;
2242     state->n = params->n;
2243     state->dead = state->won = FALSE;
2244     state->used_solve = state->just_used_solve = FALSE;
2245
2246     wh = state->w * state->h;
2247
2248     state->layout = snew(struct mine_layout);
2249     state->layout->refcount = 1;
2250
2251     state->grid = snewn(wh, char);
2252     memset(state->grid, -2, wh);
2253
2254     if (*desc == 'r') {
2255         desc++;
2256         state->layout->n = atoi(desc);
2257         while (*desc && isdigit((unsigned char)*desc))
2258             desc++;                    /* skip over mine count */
2259         if (*desc) desc++;             /* eat comma */
2260         if (*desc == 'a')
2261             state->layout->unique = FALSE;
2262         else
2263             state->layout->unique = TRUE;
2264         desc++;
2265         if (*desc) desc++;             /* eat comma */
2266
2267         state->layout->mines = NULL;
2268         state->layout->rs = random_state_decode(desc);
2269         state->layout->me = me;
2270
2271     } else {
2272         state->layout->rs = NULL;
2273         state->layout->me = NULL;
2274
2275         state->layout->mines = snewn(wh, char);
2276         x = atoi(desc);
2277         while (*desc && isdigit((unsigned char)*desc))
2278             desc++;                    /* skip over x coordinate */
2279         if (*desc) desc++;             /* eat comma */
2280         y = atoi(desc);
2281         while (*desc && isdigit((unsigned char)*desc))
2282             desc++;                    /* skip over y coordinate */
2283         if (*desc) desc++;             /* eat comma */
2284
2285         if (*desc == 'm') {
2286             masked = TRUE;
2287             desc++;
2288         } else {
2289             /*
2290              * We permit game IDs to be entered by hand without the
2291              * masking transformation.
2292              */
2293             masked = FALSE;
2294         }
2295
2296         bmp = snewn((wh + 7) / 8, unsigned char);
2297         memset(bmp, 0, (wh + 7) / 8);
2298         for (i = 0; i < (wh+3)/4; i++) {
2299             int c = desc[i];
2300             int v;
2301
2302             assert(c != 0);            /* validate_desc should have caught */
2303             if (c >= '0' && c <= '9')
2304                 v = c - '0';
2305             else if (c >= 'a' && c <= 'f')
2306                 v = c - 'a' + 10;
2307             else if (c >= 'A' && c <= 'F')
2308                 v = c - 'A' + 10;
2309             else
2310                 v = 0;
2311
2312             bmp[i / 2] |= v << (4 * (1 - (i % 2)));
2313         }
2314
2315         if (masked)
2316             obfuscate_bitmap(bmp, wh, TRUE);
2317
2318         memset(state->layout->mines, 0, wh);
2319         for (i = 0; i < wh; i++) {
2320             if (bmp[i / 8] & (0x80 >> (i % 8)))
2321                 state->layout->mines[i] = 1;
2322         }
2323
2324         ret = open_square(state, x, y);
2325     }
2326
2327     return state;
2328 }
2329
2330 static game_state *dup_game(game_state *state)
2331 {
2332     game_state *ret = snew(game_state);
2333
2334     ret->w = state->w;
2335     ret->h = state->h;
2336     ret->n = state->n;
2337     ret->dead = state->dead;
2338     ret->won = state->won;
2339     ret->used_solve = state->used_solve;
2340     ret->just_used_solve = state->just_used_solve;
2341     ret->layout = state->layout;
2342     ret->layout->refcount++;
2343     ret->grid = snewn(ret->w * ret->h, char);
2344     memcpy(ret->grid, state->grid, ret->w * ret->h);
2345
2346     return ret;
2347 }
2348
2349 static void free_game(game_state *state)
2350 {
2351     if (--state->layout->refcount <= 0) {
2352         sfree(state->layout->mines);
2353         if (state->layout->rs)
2354             random_free(state->layout->rs);
2355         sfree(state->layout);
2356     }
2357     sfree(state->grid);
2358     sfree(state);
2359 }
2360
2361 static game_state *solve_game(game_state *state, game_aux_info *aux,
2362                               char **error)
2363 {
2364     /*
2365      * Simply expose the entire grid as if it were a completed
2366      * solution.
2367      */
2368     game_state *ret;
2369     int yy, xx;
2370
2371     if (!state->layout->mines) {
2372         *error = "Game has not been started yet";
2373         return NULL;
2374     }
2375
2376     ret = dup_game(state);
2377     for (yy = 0; yy < ret->h; yy++)
2378         for (xx = 0; xx < ret->w; xx++) {
2379
2380             if (ret->layout->mines[yy*ret->w+xx]) {
2381                 ret->grid[yy*ret->w+xx] = -1;
2382             } else {
2383                 int dx, dy, v;
2384
2385                 v = 0;
2386
2387                 for (dx = -1; dx <= +1; dx++)
2388                     for (dy = -1; dy <= +1; dy++)
2389                         if (xx+dx >= 0 && xx+dx < ret->w &&
2390                             yy+dy >= 0 && yy+dy < ret->h &&
2391                             ret->layout->mines[(yy+dy)*ret->w+(xx+dx)])
2392                             v++;
2393
2394                 ret->grid[yy*ret->w+xx] = v;
2395             }
2396         }
2397     ret->used_solve = ret->just_used_solve = TRUE;
2398     ret->won = TRUE;
2399
2400     return ret;
2401 }
2402
2403 static char *game_text_format(game_state *state)
2404 {
2405     char *ret;
2406     int x, y;
2407
2408     ret = snewn((state->w + 1) * state->h + 1, char);
2409     for (y = 0; y < state->h; y++) {
2410         for (x = 0; x < state->w; x++) {
2411             int v = state->grid[y*state->w+x];
2412             if (v == 0)
2413                 v = '-';
2414             else if (v >= 1 && v <= 8)
2415                 v = '0' + v;
2416             else if (v == -1)
2417                 v = '*';
2418             else if (v == -2 || v == -3)
2419                 v = '?';
2420             else if (v >= 64)
2421                 v = '!';
2422             ret[y * (state->w+1) + x] = v;
2423         }
2424         ret[y * (state->w+1) + state->w] = '\n';
2425     }
2426     ret[(state->w + 1) * state->h] = '\0';
2427
2428     return ret;
2429 }
2430
2431 struct game_ui {
2432     int hx, hy, hradius;               /* for mouse-down highlights */
2433     int flash_is_death;
2434     int deaths;
2435 };
2436
2437 static game_ui *new_ui(game_state *state)
2438 {
2439     game_ui *ui = snew(game_ui);
2440     ui->hx = ui->hy = -1;
2441     ui->hradius = 0;
2442     ui->deaths = 0;
2443     ui->flash_is_death = FALSE;        /* *shrug* */
2444     return ui;
2445 }
2446
2447 static void free_ui(game_ui *ui)
2448 {
2449     sfree(ui);
2450 }
2451
2452 static game_state *make_move(game_state *from, game_ui *ui, game_drawstate *ds,
2453                              int x, int y, int button)
2454 {
2455     game_state *ret;
2456     int cx, cy;
2457
2458     if (from->dead || from->won)
2459         return NULL;                   /* no further moves permitted */
2460
2461     if (!IS_MOUSE_DOWN(button) && !IS_MOUSE_DRAG(button) &&
2462         !IS_MOUSE_RELEASE(button))
2463         return NULL;
2464
2465     cx = FROMCOORD(x);
2466     cy = FROMCOORD(y);
2467     if (cx < 0 || cx >= from->w || cy < 0 || cy >= from->h)
2468         return NULL;
2469
2470     if (button == LEFT_BUTTON || button == LEFT_DRAG ||
2471         button == MIDDLE_BUTTON || button == MIDDLE_DRAG) {
2472         /*
2473          * Mouse-downs and mouse-drags just cause highlighting
2474          * updates.
2475          */
2476         ui->hx = cx;
2477         ui->hy = cy;
2478         ui->hradius = (from->grid[cy*from->w+cx] >= 0 ? 1 : 0);
2479         return from;
2480     }
2481
2482     if (button == RIGHT_BUTTON) {
2483         /*
2484          * Right-clicking only works on a covered square, and it
2485          * toggles between -1 (marked as mine) and -2 (not marked
2486          * as mine).
2487          *
2488          * FIXME: question marks.
2489          */
2490         if (from->grid[cy * from->w + cx] != -2 &&
2491             from->grid[cy * from->w + cx] != -1)
2492             return NULL;
2493
2494         ret = dup_game(from);
2495         ret->just_used_solve = FALSE;
2496         ret->grid[cy * from->w + cx] ^= (-2 ^ -1);
2497
2498         return ret;
2499     }
2500
2501     if (button == LEFT_RELEASE || button == MIDDLE_RELEASE) {
2502         ui->hx = ui->hy = -1;
2503         ui->hradius = 0;
2504
2505         /*
2506          * At this stage we must never return NULL: we have adjusted
2507          * the ui, so at worst we return `from'.
2508          */
2509
2510         /*
2511          * Left-clicking on a covered square opens a tile. Not
2512          * permitted if the tile is marked as a mine, for safety.
2513          * (Unmark it and _then_ open it.)
2514          */
2515         if (button == LEFT_RELEASE &&
2516             (from->grid[cy * from->w + cx] == -2 ||
2517              from->grid[cy * from->w + cx] == -3)) {
2518             ret = dup_game(from);
2519             ret->just_used_solve = FALSE;
2520             open_square(ret, cx, cy);
2521             if (ret->dead)
2522                 ui->deaths++;
2523             return ret;
2524         }
2525
2526         /*
2527          * Left-clicking or middle-clicking on an uncovered tile:
2528          * first we check to see if the number of mine markers
2529          * surrounding the tile is equal to its mine count, and if
2530          * so then we open all other surrounding squares.
2531          */
2532         if (from->grid[cy * from->w + cx] > 0) {
2533             int dy, dx, n;
2534
2535             /* Count mine markers. */
2536             n = 0;
2537             for (dy = -1; dy <= +1; dy++)
2538                 for (dx = -1; dx <= +1; dx++)
2539                     if (cx+dx >= 0 && cx+dx < from->w &&
2540                         cy+dy >= 0 && cy+dy < from->h) {
2541                         if (from->grid[(cy+dy)*from->w+(cx+dx)] == -1)
2542                             n++;
2543                     }
2544
2545             if (n == from->grid[cy * from->w + cx]) {
2546                 ret = dup_game(from);
2547                 ret->just_used_solve = FALSE;
2548                 for (dy = -1; dy <= +1; dy++)
2549                     for (dx = -1; dx <= +1; dx++)
2550                         if (cx+dx >= 0 && cx+dx < ret->w &&
2551                             cy+dy >= 0 && cy+dy < ret->h &&
2552                             (ret->grid[(cy+dy)*ret->w+(cx+dx)] == -2 ||
2553                              ret->grid[(cy+dy)*ret->w+(cx+dx)] == -3))
2554                             open_square(ret, cx+dx, cy+dy);
2555                 if (ret->dead)
2556                     ui->deaths++;
2557                 return ret;
2558             }
2559         }
2560
2561         return from;
2562     }
2563
2564     return NULL;
2565 }
2566
2567 /* ----------------------------------------------------------------------
2568  * Drawing routines.
2569  */
2570
2571 struct game_drawstate {
2572     int w, h, started;
2573     signed char *grid;
2574     /*
2575      * Items in this `grid' array have all the same values as in
2576      * the game_state grid, and in addition:
2577      * 
2578      *  - -10 means the tile was drawn `specially' as a result of a
2579      *    flash, so it will always need redrawing.
2580      * 
2581      *  - -22 and -23 mean the tile is highlighted for a possible
2582      *    click.
2583      */
2584 };
2585
2586 static void game_size(game_params *params, int *x, int *y)
2587 {
2588     *x = BORDER * 2 + TILE_SIZE * params->w;
2589     *y = BORDER * 2 + TILE_SIZE * params->h;
2590 }
2591
2592 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
2593 {
2594     float *ret = snewn(3 * NCOLOURS, float);
2595
2596     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2597
2598     ret[COL_BACKGROUND2 * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 19.0 / 20.0;
2599     ret[COL_BACKGROUND2 * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 19.0 / 20.0;
2600     ret[COL_BACKGROUND2 * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 19.0 / 20.0;
2601
2602     ret[COL_1 * 3 + 0] = 0.0F;
2603     ret[COL_1 * 3 + 1] = 0.0F;
2604     ret[COL_1 * 3 + 2] = 1.0F;
2605
2606     ret[COL_2 * 3 + 0] = 0.0F;
2607     ret[COL_2 * 3 + 1] = 0.5F;
2608     ret[COL_2 * 3 + 2] = 0.0F;
2609
2610     ret[COL_3 * 3 + 0] = 1.0F;
2611     ret[COL_3 * 3 + 1] = 0.0F;
2612     ret[COL_3 * 3 + 2] = 0.0F;
2613
2614     ret[COL_4 * 3 + 0] = 0.0F;
2615     ret[COL_4 * 3 + 1] = 0.0F;
2616     ret[COL_4 * 3 + 2] = 0.5F;
2617
2618     ret[COL_5 * 3 + 0] = 0.5F;
2619     ret[COL_5 * 3 + 1] = 0.0F;
2620     ret[COL_5 * 3 + 2] = 0.0F;
2621
2622     ret[COL_6 * 3 + 0] = 0.0F;
2623     ret[COL_6 * 3 + 1] = 0.5F;
2624     ret[COL_6 * 3 + 2] = 0.5F;
2625
2626     ret[COL_7 * 3 + 0] = 0.0F;
2627     ret[COL_7 * 3 + 1] = 0.0F;
2628     ret[COL_7 * 3 + 2] = 0.0F;
2629
2630     ret[COL_8 * 3 + 0] = 0.5F;
2631     ret[COL_8 * 3 + 1] = 0.5F;
2632     ret[COL_8 * 3 + 2] = 0.5F;
2633
2634     ret[COL_MINE * 3 + 0] = 0.0F;
2635     ret[COL_MINE * 3 + 1] = 0.0F;
2636     ret[COL_MINE * 3 + 2] = 0.0F;
2637
2638     ret[COL_BANG * 3 + 0] = 1.0F;
2639     ret[COL_BANG * 3 + 1] = 0.0F;
2640     ret[COL_BANG * 3 + 2] = 0.0F;
2641
2642     ret[COL_CROSS * 3 + 0] = 1.0F;
2643     ret[COL_CROSS * 3 + 1] = 0.0F;
2644     ret[COL_CROSS * 3 + 2] = 0.0F;
2645
2646     ret[COL_FLAG * 3 + 0] = 1.0F;
2647     ret[COL_FLAG * 3 + 1] = 0.0F;
2648     ret[COL_FLAG * 3 + 2] = 0.0F;
2649
2650     ret[COL_FLAGBASE * 3 + 0] = 0.0F;
2651     ret[COL_FLAGBASE * 3 + 1] = 0.0F;
2652     ret[COL_FLAGBASE * 3 + 2] = 0.0F;
2653
2654     ret[COL_QUERY * 3 + 0] = 0.0F;
2655     ret[COL_QUERY * 3 + 1] = 0.0F;
2656     ret[COL_QUERY * 3 + 2] = 0.0F;
2657
2658     ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
2659     ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
2660     ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
2661
2662     ret[COL_LOWLIGHT * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 2.0 / 3.0;
2663     ret[COL_LOWLIGHT * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 2.0 / 3.0;
2664     ret[COL_LOWLIGHT * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 2.0 / 3.0;
2665
2666     *ncolours = NCOLOURS;
2667     return ret;
2668 }
2669
2670 static game_drawstate *game_new_drawstate(game_state *state)
2671 {
2672     struct game_drawstate *ds = snew(struct game_drawstate);
2673
2674     ds->w = state->w;
2675     ds->h = state->h;
2676     ds->started = FALSE;
2677     ds->grid = snewn(ds->w * ds->h, char);
2678
2679     memset(ds->grid, -99, ds->w * ds->h);
2680
2681     return ds;
2682 }
2683
2684 static void game_free_drawstate(game_drawstate *ds)
2685 {
2686     sfree(ds->grid);
2687     sfree(ds);
2688 }
2689
2690 static void draw_tile(frontend *fe, int x, int y, int v, int bg)
2691 {
2692     if (v < 0) {
2693         int coords[12];
2694         int hl = 0;
2695
2696         if (v == -22 || v == -23) {
2697             v += 20;
2698
2699             /*
2700              * Omit the highlights in this case.
2701              */
2702             draw_rect(fe, x, y, TILE_SIZE, TILE_SIZE,
2703                       bg == COL_BACKGROUND ? COL_BACKGROUND2 : bg);
2704             draw_line(fe, x, y, x + TILE_SIZE - 1, y, COL_LOWLIGHT);
2705             draw_line(fe, x, y, x, y + TILE_SIZE - 1, COL_LOWLIGHT);
2706         } else {
2707             /*
2708              * Draw highlights to indicate the square is covered.
2709              */
2710             coords[0] = x + TILE_SIZE - 1;
2711             coords[1] = y + TILE_SIZE - 1;
2712             coords[2] = x + TILE_SIZE - 1;
2713             coords[3] = y;
2714             coords[4] = x;
2715             coords[5] = y + TILE_SIZE - 1;
2716             draw_polygon(fe, coords, 3, TRUE, COL_LOWLIGHT ^ hl);
2717             draw_polygon(fe, coords, 3, FALSE, COL_LOWLIGHT ^ hl);
2718
2719             coords[0] = x;
2720             coords[1] = y;
2721             draw_polygon(fe, coords, 3, TRUE, COL_HIGHLIGHT ^ hl);
2722             draw_polygon(fe, coords, 3, FALSE, COL_HIGHLIGHT ^ hl);
2723
2724             draw_rect(fe, x + HIGHLIGHT_WIDTH, y + HIGHLIGHT_WIDTH,
2725                       TILE_SIZE - 2*HIGHLIGHT_WIDTH, TILE_SIZE - 2*HIGHLIGHT_WIDTH,
2726                       bg);
2727         }
2728
2729         if (v == -1) {
2730             /*
2731              * Draw a flag.
2732              */
2733 #define SETCOORD(n, dx, dy) do { \
2734     coords[(n)*2+0] = x + TILE_SIZE * (dx); \
2735     coords[(n)*2+1] = y + TILE_SIZE * (dy); \
2736 } while (0)
2737             SETCOORD(0, 0.6, 0.35);
2738             SETCOORD(1, 0.6, 0.7);
2739             SETCOORD(2, 0.8, 0.8);
2740             SETCOORD(3, 0.25, 0.8);
2741             SETCOORD(4, 0.55, 0.7);
2742             SETCOORD(5, 0.55, 0.35);
2743             draw_polygon(fe, coords, 6, TRUE, COL_FLAGBASE);
2744             draw_polygon(fe, coords, 6, FALSE, COL_FLAGBASE);
2745
2746             SETCOORD(0, 0.6, 0.2);
2747             SETCOORD(1, 0.6, 0.5);
2748             SETCOORD(2, 0.2, 0.35);
2749             draw_polygon(fe, coords, 3, TRUE, COL_FLAG);
2750             draw_polygon(fe, coords, 3, FALSE, COL_FLAG);
2751 #undef SETCOORD
2752
2753         } else if (v == -3) {
2754             /*
2755              * Draw a question mark.
2756              */
2757             draw_text(fe, x + TILE_SIZE / 2, y + TILE_SIZE / 2,
2758                       FONT_VARIABLE, TILE_SIZE * 6 / 8,
2759                       ALIGN_VCENTRE | ALIGN_HCENTRE,
2760                       COL_QUERY, "?");
2761         }
2762     } else {
2763         /*
2764          * Clear the square to the background colour, and draw thin
2765          * grid lines along the top and left.
2766          * 
2767          * Exception is that for value 65 (mine we've just trodden
2768          * on), we clear the square to COL_BANG.
2769          */
2770         draw_rect(fe, x, y, TILE_SIZE, TILE_SIZE,
2771                   (v == 65 ? COL_BANG :
2772                    bg == COL_BACKGROUND ? COL_BACKGROUND2 : bg));
2773         draw_line(fe, x, y, x + TILE_SIZE - 1, y, COL_LOWLIGHT);
2774         draw_line(fe, x, y, x, y + TILE_SIZE - 1, COL_LOWLIGHT);
2775
2776         if (v > 0 && v <= 8) {
2777             /*
2778              * Mark a number.
2779              */
2780             char str[2];
2781             str[0] = v + '0';
2782             str[1] = '\0';
2783             draw_text(fe, x + TILE_SIZE / 2, y + TILE_SIZE / 2,
2784                       FONT_VARIABLE, TILE_SIZE * 7 / 8,
2785                       ALIGN_VCENTRE | ALIGN_HCENTRE,
2786                       (COL_1 - 1) + v, str);
2787
2788         } else if (v >= 64) {
2789             /*
2790              * Mark a mine.
2791              * 
2792              * FIXME: this could be done better!
2793              */
2794 #if 0
2795             draw_text(fe, x + TILE_SIZE / 2, y + TILE_SIZE / 2,
2796                       FONT_VARIABLE, TILE_SIZE * 7 / 8,
2797                       ALIGN_VCENTRE | ALIGN_HCENTRE,
2798                       COL_MINE, "*");
2799 #else
2800             {
2801                 int cx = x + TILE_SIZE / 2;
2802                 int cy = y + TILE_SIZE / 2;
2803                 int r = TILE_SIZE / 2 - 3;
2804                 int coords[4*5*2];
2805                 int xdx = 1, xdy = 0, ydx = 0, ydy = 1;
2806                 int tdx, tdy, i;
2807
2808                 for (i = 0; i < 4*5*2; i += 5*2) {
2809                     coords[i+2*0+0] = cx - r/6*xdx + r*4/5*ydx;
2810                     coords[i+2*0+1] = cy - r/6*xdy + r*4/5*ydy;
2811                     coords[i+2*1+0] = cx - r/6*xdx + r*ydx;
2812                     coords[i+2*1+1] = cy - r/6*xdy + r*ydy;
2813                     coords[i+2*2+0] = cx + r/6*xdx + r*ydx;
2814                     coords[i+2*2+1] = cy + r/6*xdy + r*ydy;
2815                     coords[i+2*3+0] = cx + r/6*xdx + r*4/5*ydx;
2816                     coords[i+2*3+1] = cy + r/6*xdy + r*4/5*ydy;
2817                     coords[i+2*4+0] = cx + r*3/5*xdx + r*3/5*ydx;
2818                     coords[i+2*4+1] = cy + r*3/5*xdy + r*3/5*ydy;
2819
2820                     tdx = ydx;
2821                     tdy = ydy;
2822                     ydx = xdx;
2823                     ydy = xdy;
2824                     xdx = -tdx;
2825                     xdy = -tdy;
2826                 }
2827
2828                 draw_polygon(fe, coords, 5*4, TRUE, COL_MINE);
2829                 draw_polygon(fe, coords, 5*4, FALSE, COL_MINE);
2830
2831                 draw_rect(fe, cx-r/3, cy-r/3, r/3, r/4, COL_HIGHLIGHT);
2832             }
2833 #endif
2834
2835             if (v == 66) {
2836                 /*
2837                  * Cross through the mine.
2838                  */
2839                 int dx;
2840                 for (dx = -1; dx <= +1; dx++) {
2841                     draw_line(fe, x + 3 + dx, y + 2,
2842                               x + TILE_SIZE - 3 + dx,
2843                               y + TILE_SIZE - 2, COL_CROSS);
2844                     draw_line(fe, x + TILE_SIZE - 3 + dx, y + 2,
2845                               x + 3 + dx, y + TILE_SIZE - 2,
2846                               COL_CROSS);
2847                 }
2848             }
2849         }
2850     }
2851
2852     draw_update(fe, x, y, TILE_SIZE, TILE_SIZE);
2853 }
2854
2855 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
2856                         game_state *state, int dir, game_ui *ui,
2857                         float animtime, float flashtime)
2858 {
2859     int x, y;
2860     int mines, markers, bg;
2861
2862     if (flashtime) {
2863         int frame = (flashtime / FLASH_FRAME);
2864         if (frame % 2)
2865             bg = (ui->flash_is_death ? COL_BACKGROUND : COL_LOWLIGHT);
2866         else
2867             bg = (ui->flash_is_death ? COL_BANG : COL_HIGHLIGHT);
2868     } else
2869         bg = COL_BACKGROUND;
2870
2871     if (!ds->started) {
2872         int coords[10];
2873
2874         draw_rect(fe, 0, 0,
2875                   TILE_SIZE * state->w + 2 * BORDER,
2876                   TILE_SIZE * state->h + 2 * BORDER, COL_BACKGROUND);
2877         draw_update(fe, 0, 0,
2878                     TILE_SIZE * state->w + 2 * BORDER,
2879                     TILE_SIZE * state->h + 2 * BORDER);
2880
2881         /*
2882          * Recessed area containing the whole puzzle.
2883          */
2884         coords[0] = COORD(state->w) + OUTER_HIGHLIGHT_WIDTH - 1;
2885         coords[1] = COORD(state->h) + OUTER_HIGHLIGHT_WIDTH - 1;
2886         coords[2] = COORD(state->w) + OUTER_HIGHLIGHT_WIDTH - 1;
2887         coords[3] = COORD(0) - OUTER_HIGHLIGHT_WIDTH;
2888         coords[4] = coords[2] - TILE_SIZE;
2889         coords[5] = coords[3] + TILE_SIZE;
2890         coords[8] = COORD(0) - OUTER_HIGHLIGHT_WIDTH;
2891         coords[9] = COORD(state->h) + OUTER_HIGHLIGHT_WIDTH - 1;
2892         coords[6] = coords[8] + TILE_SIZE;
2893         coords[7] = coords[9] - TILE_SIZE;
2894         draw_polygon(fe, coords, 5, TRUE, COL_HIGHLIGHT);
2895         draw_polygon(fe, coords, 5, FALSE, COL_HIGHLIGHT);
2896
2897         coords[1] = COORD(0) - OUTER_HIGHLIGHT_WIDTH;
2898         coords[0] = COORD(0) - OUTER_HIGHLIGHT_WIDTH;
2899         draw_polygon(fe, coords, 5, TRUE, COL_LOWLIGHT);
2900         draw_polygon(fe, coords, 5, FALSE, COL_LOWLIGHT);
2901
2902         ds->started = TRUE;
2903     }
2904
2905     /*
2906      * Now draw the tiles. Also in this loop, count up the number
2907      * of mines and mine markers.
2908      */
2909     mines = markers = 0;
2910     for (y = 0; y < ds->h; y++)
2911         for (x = 0; x < ds->w; x++) {
2912             int v = state->grid[y*ds->w+x];
2913
2914             if (v == -1)
2915                 markers++;
2916             if (state->layout->mines && state->layout->mines[y*ds->w+x])
2917                 mines++;
2918
2919             if ((v == -2 || v == -3) &&
2920                 (abs(x-ui->hx) <= ui->hradius && abs(y-ui->hy) <= ui->hradius))
2921                 v -= 20;
2922
2923             if (ds->grid[y*ds->w+x] != v || bg != COL_BACKGROUND) {
2924                 draw_tile(fe, COORD(x), COORD(y), v, bg);
2925                 ds->grid[y*ds->w+x] = (bg == COL_BACKGROUND ? v : -10);
2926             }
2927         }
2928
2929     if (!state->layout->mines)
2930         mines = state->layout->n;
2931
2932     /*
2933      * Update the status bar.
2934      */
2935     {
2936         char statusbar[512];
2937         if (state->dead) {
2938             sprintf(statusbar, "DEAD!");
2939         } else if (state->won) {
2940             if (state->used_solve)
2941                 sprintf(statusbar, "Auto-solved.");
2942             else
2943                 sprintf(statusbar, "COMPLETED!");
2944         } else {
2945             sprintf(statusbar, "Marked: %d / %d", markers, mines);
2946         }
2947         if (ui->deaths)
2948             sprintf(statusbar + strlen(statusbar),
2949                     "  Deaths: %d", ui->deaths);
2950         status_bar(fe, statusbar);
2951     }
2952 }
2953
2954 static float game_anim_length(game_state *oldstate, game_state *newstate,
2955                               int dir, game_ui *ui)
2956 {
2957     return 0.0F;
2958 }
2959
2960 static float game_flash_length(game_state *oldstate, game_state *newstate,
2961                                int dir, game_ui *ui)
2962 {
2963     if (oldstate->used_solve || newstate->used_solve)
2964         return 0.0F;
2965
2966     if (dir > 0 && !oldstate->dead && !oldstate->won) {
2967         if (newstate->dead) {
2968             ui->flash_is_death = TRUE;
2969             return 3 * FLASH_FRAME;
2970         }
2971         if (newstate->won) {
2972             ui->flash_is_death = FALSE;
2973             return 2 * FLASH_FRAME;
2974         }
2975     }
2976     return 0.0F;
2977 }
2978
2979 static int game_wants_statusbar(void)
2980 {
2981     return TRUE;
2982 }
2983
2984 static int game_timing_state(game_state *state)
2985 {
2986     if (state->dead || state->won || !state->layout->mines)
2987         return FALSE;
2988     return TRUE;
2989 }
2990
2991 #ifdef COMBINED
2992 #define thegame mines
2993 #endif
2994
2995 const struct game thegame = {
2996     "Mines", "games.mines",
2997     default_params,
2998     game_fetch_preset,
2999     decode_params,
3000     encode_params,
3001     free_params,
3002     dup_params,
3003     TRUE, game_configure, custom_params,
3004     validate_params,
3005     new_game_desc,
3006     game_free_aux_info,
3007     validate_desc,
3008     new_game,
3009     dup_game,
3010     free_game,
3011     TRUE, solve_game,
3012     TRUE, game_text_format,
3013     new_ui,
3014     free_ui,
3015     make_move,
3016     game_size,
3017     game_colours,
3018     game_new_drawstate,
3019     game_free_drawstate,
3020     game_redraw,
3021     game_anim_length,
3022     game_flash_length,
3023     game_wants_statusbar,
3024     TRUE, game_timing_state,
3025     BUTTON_BEATS(LEFT_BUTTON, RIGHT_BUTTON),
3026 };