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