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