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