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