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