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