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