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