chiark / gitweb /
Ahem; forgot about recursion. Recursive solving now shows its
[sgt-puzzles.git] / map.c
1 /*
2  * map.c: Game involving four-colouring a map.
3  */
4
5 /*
6  * TODO:
7  * 
8  *  - clue marking
9  *  - better four-colouring algorithm?
10  *  - can we make the pencil marks look nicer?
11  *  - ability to drag a set of pencil marks?
12  */
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <assert.h>
18 #include <ctype.h>
19 #include <math.h>
20
21 #include "puzzles.h"
22
23 /*
24  * In standalone solver mode, `verbose' is a variable which can be
25  * set by command-line option; in debugging mode it's simply always
26  * true.
27  */
28 #if defined STANDALONE_SOLVER
29 #define SOLVER_DIAGNOSTICS
30 int verbose = FALSE;
31 #elif defined SOLVER_DIAGNOSTICS
32 #define verbose TRUE
33 #endif
34
35 /*
36  * I don't seriously anticipate wanting to change the number of
37  * colours used in this game, but it doesn't cost much to use a
38  * #define just in case :-)
39  */
40 #define FOUR 4
41 #define THREE (FOUR-1)
42 #define FIVE (FOUR+1)
43 #define SIX (FOUR+2)
44
45 /*
46  * Ghastly run-time configuration option, just for Gareth (again).
47  */
48 static int flash_type = -1;
49 static float flash_length;
50
51 /*
52  * Difficulty levels. I do some macro ickery here to ensure that my
53  * enum and the various forms of my name list always match up.
54  */
55 #define DIFFLIST(A) \
56     A(EASY,Easy,e) \
57     A(NORMAL,Normal,n) \
58     A(HARD,Hard,h) \
59     A(RECURSE,Unreasonable,u)
60 #define ENUM(upper,title,lower) DIFF_ ## upper,
61 #define TITLE(upper,title,lower) #title,
62 #define ENCODE(upper,title,lower) #lower
63 #define CONFIG(upper,title,lower) ":" #title
64 enum { DIFFLIST(ENUM) DIFFCOUNT };
65 static char const *const map_diffnames[] = { DIFFLIST(TITLE) };
66 static char const map_diffchars[] = DIFFLIST(ENCODE);
67 #define DIFFCONFIG DIFFLIST(CONFIG)
68
69 enum { TE, BE, LE, RE };               /* top/bottom/left/right edges */
70
71 enum {
72     COL_BACKGROUND,
73     COL_GRID,
74     COL_0, COL_1, COL_2, COL_3,
75     COL_ERROR, COL_ERRTEXT,
76     NCOLOURS
77 };
78
79 struct game_params {
80     int w, h, n, diff;
81 };
82
83 struct map {
84     int refcount;
85     int *map;
86     int *graph;
87     int n;
88     int ngraph;
89     int *immutable;
90     int *edgex, *edgey;                /* position of a point on each edge */
91     int *regionx, *regiony;            /* position of a point in each region */
92 };
93
94 struct game_state {
95     game_params p;
96     struct map *map;
97     int *colouring, *pencil;
98     int completed, cheated;
99 };
100
101 static game_params *default_params(void)
102 {
103     game_params *ret = snew(game_params);
104
105     ret->w = 20;
106     ret->h = 15;
107     ret->n = 30;
108     ret->diff = DIFF_NORMAL;
109
110     return ret;
111 }
112
113 static const struct game_params map_presets[] = {
114     {20, 15, 30, DIFF_EASY},
115     {20, 15, 30, DIFF_NORMAL},
116     {20, 15, 30, DIFF_HARD},
117     {20, 15, 30, DIFF_RECURSE},
118     {30, 25, 75, DIFF_NORMAL},
119     {30, 25, 75, DIFF_HARD},
120 };
121
122 static int game_fetch_preset(int i, char **name, game_params **params)
123 {
124     game_params *ret;
125     char str[80];
126
127     if (i < 0 || i >= lenof(map_presets))
128         return FALSE;
129
130     ret = snew(game_params);
131     *ret = map_presets[i];
132
133     sprintf(str, "%dx%d, %d regions, %s", ret->w, ret->h, ret->n,
134             map_diffnames[ret->diff]);
135
136     *name = dupstr(str);
137     *params = ret;
138     return TRUE;
139 }
140
141 static void free_params(game_params *params)
142 {
143     sfree(params);
144 }
145
146 static game_params *dup_params(game_params *params)
147 {
148     game_params *ret = snew(game_params);
149     *ret = *params;                    /* structure copy */
150     return ret;
151 }
152
153 static void decode_params(game_params *params, char const *string)
154 {
155     char const *p = string;
156
157     params->w = atoi(p);
158     while (*p && isdigit((unsigned char)*p)) p++;
159     if (*p == 'x') {
160         p++;
161         params->h = atoi(p);
162         while (*p && isdigit((unsigned char)*p)) p++;
163     } else {
164         params->h = params->w;
165     }
166     if (*p == 'n') {
167         p++;
168         params->n = atoi(p);
169         while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
170     } else {
171         params->n = params->w * params->h / 8;
172     }
173     if (*p == 'd') {
174         int i;
175         p++;
176         for (i = 0; i < DIFFCOUNT; i++)
177             if (*p == map_diffchars[i])
178                 params->diff = i;
179         if (*p) p++;
180     }
181 }
182
183 static char *encode_params(game_params *params, int full)
184 {
185     char ret[400];
186
187     sprintf(ret, "%dx%dn%d", params->w, params->h, params->n);
188     if (full)
189         sprintf(ret + strlen(ret), "d%c", map_diffchars[params->diff]);
190
191     return dupstr(ret);
192 }
193
194 static config_item *game_configure(game_params *params)
195 {
196     config_item *ret;
197     char buf[80];
198
199     ret = snewn(5, config_item);
200
201     ret[0].name = "Width";
202     ret[0].type = C_STRING;
203     sprintf(buf, "%d", params->w);
204     ret[0].sval = dupstr(buf);
205     ret[0].ival = 0;
206
207     ret[1].name = "Height";
208     ret[1].type = C_STRING;
209     sprintf(buf, "%d", params->h);
210     ret[1].sval = dupstr(buf);
211     ret[1].ival = 0;
212
213     ret[2].name = "Regions";
214     ret[2].type = C_STRING;
215     sprintf(buf, "%d", params->n);
216     ret[2].sval = dupstr(buf);
217     ret[2].ival = 0;
218
219     ret[3].name = "Difficulty";
220     ret[3].type = C_CHOICES;
221     ret[3].sval = DIFFCONFIG;
222     ret[3].ival = params->diff;
223
224     ret[4].name = NULL;
225     ret[4].type = C_END;
226     ret[4].sval = NULL;
227     ret[4].ival = 0;
228
229     return ret;
230 }
231
232 static game_params *custom_params(config_item *cfg)
233 {
234     game_params *ret = snew(game_params);
235
236     ret->w = atoi(cfg[0].sval);
237     ret->h = atoi(cfg[1].sval);
238     ret->n = atoi(cfg[2].sval);
239     ret->diff = cfg[3].ival;
240
241     return ret;
242 }
243
244 static char *validate_params(game_params *params, int full)
245 {
246     if (params->w < 2 || params->h < 2)
247         return "Width and height must be at least two";
248     if (params->n < 5)
249         return "Must have at least five regions";
250     if (params->n > params->w * params->h)
251         return "Too many regions to fit in grid";
252     return NULL;
253 }
254
255 /* ----------------------------------------------------------------------
256  * Cumulative frequency table functions.
257  */
258
259 /*
260  * Initialise a cumulative frequency table. (Hardly worth writing
261  * this function; all it does is to initialise everything in the
262  * array to zero.)
263  */
264 static void cf_init(int *table, int n)
265 {
266     int i;
267
268     for (i = 0; i < n; i++)
269         table[i] = 0;
270 }
271
272 /*
273  * Increment the count of symbol `sym' by `count'.
274  */
275 static void cf_add(int *table, int n, int sym, int count)
276 {
277     int bit;
278
279     bit = 1;
280     while (sym != 0) {
281         if (sym & bit) {
282             table[sym] += count;
283             sym &= ~bit;
284         }
285         bit <<= 1;
286     }
287
288     table[0] += count;
289 }
290
291 /*
292  * Cumulative frequency lookup: return the total count of symbols
293  * with value less than `sym'.
294  */
295 static int cf_clookup(int *table, int n, int sym)
296 {
297     int bit, index, limit, count;
298
299     if (sym == 0)
300         return 0;
301
302     assert(0 < sym && sym <= n);
303
304     count = table[0];                  /* start with the whole table size */
305
306     bit = 1;
307     while (bit < n)
308         bit <<= 1;
309
310     limit = n;
311
312     while (bit > 0) {
313         /*
314          * Find the least number with its lowest set bit in this
315          * position which is greater than or equal to sym.
316          */
317         index = ((sym + bit - 1) &~ (bit * 2 - 1)) + bit;
318
319         if (index < limit) {
320             count -= table[index];
321             limit = index;
322         }
323
324         bit >>= 1;
325     }
326
327     return count;
328 }
329
330 /*
331  * Single frequency lookup: return the count of symbol `sym'.
332  */
333 static int cf_slookup(int *table, int n, int sym)
334 {
335     int count, bit;
336
337     assert(0 <= sym && sym < n);
338
339     count = table[sym];
340
341     for (bit = 1; sym+bit < n && !(sym & bit); bit <<= 1)
342         count -= table[sym+bit];
343
344     return count;
345 }
346
347 /*
348  * Return the largest symbol index such that the cumulative
349  * frequency up to that symbol is less than _or equal to_ count.
350  */
351 static int cf_whichsym(int *table, int n, int count) {
352     int bit, sym, top;
353
354     assert(count >= 0 && count < table[0]);
355
356     bit = 1;
357     while (bit < n)
358         bit <<= 1;
359
360     sym = 0;
361     top = table[0];
362
363     while (bit > 0) {
364         if (sym+bit < n) {
365             if (count >= top - table[sym+bit])
366                 sym += bit;
367             else
368                 top -= table[sym+bit];
369         }
370
371         bit >>= 1;
372     }
373
374     return sym;
375 }
376
377 /* ----------------------------------------------------------------------
378  * Map generation.
379  * 
380  * FIXME: this isn't entirely optimal at present, because it
381  * inherently prioritises growing the largest region since there
382  * are more squares adjacent to it. This acts as a destabilising
383  * influence leading to a few large regions and mostly small ones.
384  * It might be better to do it some other way.
385  */
386
387 #define WEIGHT_INCREASED 2             /* for increased perimeter */
388 #define WEIGHT_DECREASED 4             /* for decreased perimeter */
389 #define WEIGHT_UNCHANGED 3             /* for unchanged perimeter */
390
391 /*
392  * Look at a square and decide which colours can be extended into
393  * it.
394  * 
395  * If called with index < 0, it adds together one of
396  * WEIGHT_INCREASED, WEIGHT_DECREASED or WEIGHT_UNCHANGED for each
397  * colour that has a valid extension (according to the effect that
398  * it would have on the perimeter of the region being extended) and
399  * returns the overall total.
400  * 
401  * If called with index >= 0, it returns one of the possible
402  * colours depending on the value of index, in such a way that the
403  * number of possible inputs which would give rise to a given
404  * return value correspond to the weight of that value.
405  */
406 static int extend_options(int w, int h, int n, int *map,
407                           int x, int y, int index)
408 {
409     int c, i, dx, dy;
410     int col[8];
411     int total = 0;
412
413     if (map[y*w+x] >= 0) {
414         assert(index < 0);
415         return 0;                      /* can't do this square at all */
416     }
417
418     /*
419      * Fetch the eight neighbours of this square, in order around
420      * the square.
421      */
422     for (dy = -1; dy <= +1; dy++)
423         for (dx = -1; dx <= +1; dx++) {
424             int index = (dy < 0 ? 6-dx : dy > 0 ? 2+dx : 2*(1+dx));
425             if (x+dx >= 0 && x+dx < w && y+dy >= 0 && y+dy < h)
426                 col[index] = map[(y+dy)*w+(x+dx)];
427             else
428                 col[index] = -1;
429         }
430
431     /*
432      * Iterate over each colour that might be feasible.
433      * 
434      * FIXME: this routine currently has O(n) running time. We
435      * could turn it into O(FOUR) by only bothering to iterate over
436      * the colours mentioned in the four neighbouring squares.
437      */
438
439     for (c = 0; c < n; c++) {
440         int count, neighbours, runs;
441
442         /*
443          * One of the even indices of col (representing the
444          * orthogonal neighbours of this square) must be equal to
445          * c, or else this square is not adjacent to region c and
446          * obviously cannot become an extension of it at this time.
447          */
448         neighbours = 0;
449         for (i = 0; i < 8; i += 2)
450             if (col[i] == c)
451                 neighbours++;
452         if (!neighbours)
453             continue;
454
455         /*
456          * Now we know this square is adjacent to region c. The
457          * next question is, would extending it cause the region to
458          * become non-simply-connected? If so, we mustn't do it.
459          * 
460          * We determine this by looking around col to see if we can
461          * find more than one separate run of colour c.
462          */
463         runs = 0;
464         for (i = 0; i < 8; i++)
465             if (col[i] == c && col[(i+1) & 7] != c)
466                 runs++;
467         if (runs > 1)
468             continue;
469
470         assert(runs == 1);
471
472         /*
473          * This square is a possibility. Determine its effect on
474          * the region's perimeter (computed from the number of
475          * orthogonal neighbours - 1 means a perimeter increase, 3
476          * a decrease, 2 no change; 4 is impossible because the
477          * region would already not be simply connected) and we're
478          * done.
479          */
480         assert(neighbours > 0 && neighbours < 4);
481         count = (neighbours == 1 ? WEIGHT_INCREASED :
482                  neighbours == 2 ? WEIGHT_UNCHANGED : WEIGHT_DECREASED);
483
484         total += count;
485         if (index >= 0 && index < count)
486             return c;
487         else
488             index -= count;
489     }
490
491     assert(index < 0);
492
493     return total;
494 }
495
496 static void genmap(int w, int h, int n, int *map, random_state *rs)
497 {
498     int wh = w*h;
499     int x, y, i, k;
500     int *tmp;
501
502     assert(n <= wh);
503     tmp = snewn(wh, int);
504
505     /*
506      * Clear the map, and set up `tmp' as a list of grid indices.
507      */
508     for (i = 0; i < wh; i++) {
509         map[i] = -1;
510         tmp[i] = i;
511     }
512
513     /*
514      * Place the region seeds by selecting n members from `tmp'.
515      */
516     k = wh;
517     for (i = 0; i < n; i++) {
518         int j = random_upto(rs, k);
519         map[tmp[j]] = i;
520         tmp[j] = tmp[--k];
521     }
522
523     /*
524      * Re-initialise `tmp' as a cumulative frequency table. This
525      * will store the number of possible region colours we can
526      * extend into each square.
527      */
528     cf_init(tmp, wh);
529
530     /*
531      * Go through the grid and set up the initial cumulative
532      * frequencies.
533      */
534     for (y = 0; y < h; y++)
535         for (x = 0; x < w; x++)
536             cf_add(tmp, wh, y*w+x,
537                    extend_options(w, h, n, map, x, y, -1));
538
539     /*
540      * Now repeatedly choose a square we can extend a region into,
541      * and do so.
542      */
543     while (tmp[0] > 0) {
544         int k = random_upto(rs, tmp[0]);
545         int sq;
546         int colour;
547         int xx, yy;
548
549         sq = cf_whichsym(tmp, wh, k);
550         k -= cf_clookup(tmp, wh, sq);
551         x = sq % w;
552         y = sq / w;
553         colour = extend_options(w, h, n, map, x, y, k);
554
555         map[sq] = colour;
556
557         /*
558          * Re-scan the nine cells around the one we've just
559          * modified.
560          */
561         for (yy = max(y-1, 0); yy < min(y+2, h); yy++)
562             for (xx = max(x-1, 0); xx < min(x+2, w); xx++) {
563                 cf_add(tmp, wh, yy*w+xx,
564                        -cf_slookup(tmp, wh, yy*w+xx) +
565                        extend_options(w, h, n, map, xx, yy, -1));
566             }
567     }
568
569     /*
570      * Finally, go through and normalise the region labels into
571      * order, meaning that indistinguishable maps are actually
572      * identical.
573      */
574     for (i = 0; i < n; i++)
575         tmp[i] = -1;
576     k = 0;
577     for (i = 0; i < wh; i++) {
578         assert(map[i] >= 0);
579         if (tmp[map[i]] < 0)
580             tmp[map[i]] = k++;
581         map[i] = tmp[map[i]];
582     }
583
584     sfree(tmp);
585 }
586
587 /* ----------------------------------------------------------------------
588  * Functions to handle graphs.
589  */
590
591 /*
592  * Having got a map in a square grid, convert it into a graph
593  * representation.
594  */
595 static int gengraph(int w, int h, int n, int *map, int *graph)
596 {
597     int i, j, x, y;
598
599     /*
600      * Start by setting the graph up as an adjacency matrix. We'll
601      * turn it into a list later.
602      */
603     for (i = 0; i < n*n; i++)
604         graph[i] = 0;
605
606     /*
607      * Iterate over the map looking for all adjacencies.
608      */
609     for (y = 0; y < h; y++)
610         for (x = 0; x < w; x++) {
611             int v, vx, vy;
612             v = map[y*w+x];
613             if (x+1 < w && (vx = map[y*w+(x+1)]) != v)
614                 graph[v*n+vx] = graph[vx*n+v] = 1;
615             if (y+1 < h && (vy = map[(y+1)*w+x]) != v)
616                 graph[v*n+vy] = graph[vy*n+v] = 1;
617         }
618
619     /*
620      * Turn the matrix into a list.
621      */
622     for (i = j = 0; i < n*n; i++)
623         if (graph[i])
624             graph[j++] = i;
625
626     return j;
627 }
628
629 static int graph_edge_index(int *graph, int n, int ngraph, int i, int j)
630 {
631     int v = i*n+j;
632     int top, bot, mid;
633
634     bot = -1;
635     top = ngraph;
636     while (top - bot > 1) {
637         mid = (top + bot) / 2;
638         if (graph[mid] == v)
639             return mid;
640         else if (graph[mid] < v)
641             bot = mid;
642         else
643             top = mid;
644     }
645     return -1;
646 }
647
648 #define graph_adjacent(graph, n, ngraph, i, j) \
649     (graph_edge_index((graph), (n), (ngraph), (i), (j)) >= 0)
650
651 static int graph_vertex_start(int *graph, int n, int ngraph, int i)
652 {
653     int v = i*n;
654     int top, bot, mid;
655
656     bot = -1;
657     top = ngraph;
658     while (top - bot > 1) {
659         mid = (top + bot) / 2;
660         if (graph[mid] < v)
661             bot = mid;
662         else
663             top = mid;
664     }
665     return top;
666 }
667
668 /* ----------------------------------------------------------------------
669  * Generate a four-colouring of a graph.
670  *
671  * FIXME: it would be nice if we could convert this recursion into
672  * pseudo-recursion using some sort of explicit stack array, for
673  * the sake of the Palm port and its limited stack.
674  */
675
676 static int fourcolour_recurse(int *graph, int n, int ngraph,
677                               int *colouring, int *scratch, random_state *rs)
678 {
679     int nfree, nvert, start, i, j, k, c, ci;
680     int cs[FOUR];
681
682     /*
683      * Find the smallest number of free colours in any uncoloured
684      * vertex, and count the number of such vertices.
685      */
686
687     nfree = FIVE;                      /* start off bigger than FOUR! */
688     nvert = 0;
689     for (i = 0; i < n; i++)
690         if (colouring[i] < 0 && scratch[i*FIVE+FOUR] <= nfree) {
691             if (nfree > scratch[i*FIVE+FOUR]) {
692                 nfree = scratch[i*FIVE+FOUR];
693                 nvert = 0;
694             }
695             nvert++;
696         }
697
698     /*
699      * If there aren't any uncoloured vertices at all, we're done.
700      */
701     if (nvert == 0)
702         return TRUE;                   /* we've got a colouring! */
703
704     /*
705      * Pick a random vertex in that set.
706      */
707     j = random_upto(rs, nvert);
708     for (i = 0; i < n; i++)
709         if (colouring[i] < 0 && scratch[i*FIVE+FOUR] == nfree)
710             if (j-- == 0)
711                 break;
712     assert(i < n);
713     start = graph_vertex_start(graph, n, ngraph, i);
714
715     /*
716      * Loop over the possible colours for i, and recurse for each
717      * one.
718      */
719     ci = 0;
720     for (c = 0; c < FOUR; c++)
721         if (scratch[i*FIVE+c] == 0)
722             cs[ci++] = c;
723     shuffle(cs, ci, sizeof(*cs), rs);
724
725     while (ci-- > 0) {
726         c = cs[ci];
727
728         /*
729          * Fill in this colour.
730          */
731         colouring[i] = c;
732
733         /*
734          * Update the scratch space to reflect a new neighbour
735          * of this colour for each neighbour of vertex i.
736          */
737         for (j = start; j < ngraph && graph[j] < n*(i+1); j++) {
738             k = graph[j] - i*n;
739             if (scratch[k*FIVE+c] == 0)
740                 scratch[k*FIVE+FOUR]--;
741             scratch[k*FIVE+c]++;
742         }
743
744         /*
745          * Recurse.
746          */
747         if (fourcolour_recurse(graph, n, ngraph, colouring, scratch, rs))
748             return TRUE;               /* got one! */
749
750         /*
751          * If that didn't work, clean up and try again with a
752          * different colour.
753          */
754         for (j = start; j < ngraph && graph[j] < n*(i+1); j++) {
755             k = graph[j] - i*n;
756             scratch[k*FIVE+c]--;
757             if (scratch[k*FIVE+c] == 0)
758                 scratch[k*FIVE+FOUR]++;
759         }
760         colouring[i] = -1;
761     }
762
763     /*
764      * If we reach here, we were unable to find a colouring at all.
765      * (This doesn't necessarily mean the Four Colour Theorem is
766      * violated; it might just mean we've gone down a dead end and
767      * need to back up and look somewhere else. It's only an FCT
768      * violation if we get all the way back up to the top level and
769      * still fail.)
770      */
771     return FALSE;
772 }
773
774 static void fourcolour(int *graph, int n, int ngraph, int *colouring,
775                        random_state *rs)
776 {
777     int *scratch;
778     int i;
779
780     /*
781      * For each vertex and each colour, we store the number of
782      * neighbours that have that colour. Also, we store the number
783      * of free colours for the vertex.
784      */
785     scratch = snewn(n * FIVE, int);
786     for (i = 0; i < n * FIVE; i++)
787         scratch[i] = (i % FIVE == FOUR ? FOUR : 0);
788
789     /*
790      * Clear the colouring to start with.
791      */
792     for (i = 0; i < n; i++)
793         colouring[i] = -1;
794
795     i = fourcolour_recurse(graph, n, ngraph, colouring, scratch, rs);
796     assert(i);                         /* by the Four Colour Theorem :-) */
797
798     sfree(scratch);
799 }
800
801 /* ----------------------------------------------------------------------
802  * Non-recursive solver.
803  */
804
805 struct solver_scratch {
806     unsigned char *possible;           /* bitmap of colours for each region */
807
808     int *graph;
809     int n;
810     int ngraph;
811
812     int *bfsqueue;
813     int *bfscolour;
814 #ifdef SOLVER_DIAGNOSTICS
815     int *bfsprev;
816 #endif
817
818     int depth;
819 };
820
821 static struct solver_scratch *new_scratch(int *graph, int n, int ngraph)
822 {
823     struct solver_scratch *sc;
824
825     sc = snew(struct solver_scratch);
826     sc->graph = graph;
827     sc->n = n;
828     sc->ngraph = ngraph;
829     sc->possible = snewn(n, unsigned char);
830     sc->depth = 0;
831     sc->bfsqueue = snewn(n, int);
832     sc->bfscolour = snewn(n, int);
833 #ifdef SOLVER_DIAGNOSTICS
834     sc->bfsprev = snewn(n, int);
835 #endif
836
837     return sc;
838 }
839
840 static void free_scratch(struct solver_scratch *sc)
841 {
842     sfree(sc->possible);
843     sfree(sc->bfsqueue);
844     sfree(sc->bfscolour);
845 #ifdef SOLVER_DIAGNOSTICS
846     sfree(sc->bfsprev);
847 #endif
848     sfree(sc);
849 }
850
851 /*
852  * Count the bits in a word. Only needs to cope with FOUR bits.
853  */
854 static int bitcount(int word)
855 {
856     assert(FOUR <= 4);                 /* or this needs changing */
857     word = ((word & 0xA) >> 1) + (word & 0x5);
858     word = ((word & 0xC) >> 2) + (word & 0x3);
859     return word;
860 }
861
862 #ifdef SOLVER_DIAGNOSTICS
863 static const char colnames[FOUR] = { 'R', 'Y', 'G', 'B' };
864 #endif
865
866 static int place_colour(struct solver_scratch *sc,
867                         int *colouring, int index, int colour
868 #ifdef SOLVER_DIAGNOSTICS
869                         , char *verb
870 #endif
871                         )
872 {
873     int *graph = sc->graph, n = sc->n, ngraph = sc->ngraph;
874     int j, k;
875
876     if (!(sc->possible[index] & (1 << colour))) {
877 #ifdef SOLVER_DIAGNOSTICS
878         if (verbose)
879             printf("%*scannot place %c in region %d\n", 2*sc->depth, "",
880                    colnames[colour], index);
881 #endif
882         return FALSE;                  /* can't do it */
883     }
884
885     sc->possible[index] = 1 << colour;
886     colouring[index] = colour;
887
888 #ifdef SOLVER_DIAGNOSTICS
889     if (verbose)
890         printf("%*s%s %c in region %d\n", 2*sc->depth, "",
891                verb, colnames[colour], index);
892 #endif
893
894     /*
895      * Rule out this colour from all the region's neighbours.
896      */
897     for (j = graph_vertex_start(graph, n, ngraph, index);
898          j < ngraph && graph[j] < n*(index+1); j++) {
899         k = graph[j] - index*n;
900 #ifdef SOLVER_DIAGNOSTICS
901         if (verbose && (sc->possible[k] & (1 << colour)))
902             printf("%*s  ruling out %c in region %d\n", 2*sc->depth, "",
903                    colnames[colour], k);
904 #endif
905         sc->possible[k] &= ~(1 << colour);
906     }
907
908     return TRUE;
909 }
910
911 #ifdef SOLVER_DIAGNOSTICS
912 static char *colourset(char *buf, int set)
913 {
914     int i;
915     char *p = buf;
916     char *sep = "";
917
918     for (i = 0; i < FOUR; i++)
919         if (set & (1 << i)) {
920             p += sprintf(p, "%s%c", sep, colnames[i]);
921             sep = ",";
922         }
923
924     return buf;
925 }
926 #endif
927
928 /*
929  * Returns 0 for impossible, 1 for success, 2 for failure to
930  * converge (i.e. puzzle is either ambiguous or just too
931  * difficult).
932  */
933 static int map_solver(struct solver_scratch *sc,
934                       int *graph, int n, int ngraph, int *colouring,
935                       int difficulty)
936 {
937     int i;
938
939     if (sc->depth == 0) {
940         /*
941          * Initialise scratch space.
942          */
943         for (i = 0; i < n; i++)
944             sc->possible[i] = (1 << FOUR) - 1;
945
946         /*
947          * Place clues.
948          */
949         for (i = 0; i < n; i++)
950             if (colouring[i] >= 0) {
951                 if (!place_colour(sc, colouring, i, colouring[i]
952 #ifdef SOLVER_DIAGNOSTICS
953                                   , "initial clue:"
954 #endif
955                                   )) {
956 #ifdef SOLVER_DIAGNOSTICS
957                     if (verbose)
958                         printf("%*sinitial clue set is inconsistent\n",
959                                2*sc->depth, "");
960 #endif
961                     return 0;          /* the clues aren't even consistent! */
962                 }
963             }
964     }
965
966     /*
967      * Now repeatedly loop until we find nothing further to do.
968      */
969     while (1) {
970         int done_something = FALSE;
971
972         if (difficulty < DIFF_EASY)
973             break;                     /* can't do anything at all! */
974
975         /*
976          * Simplest possible deduction: find a region with only one
977          * possible colour.
978          */
979         for (i = 0; i < n; i++) if (colouring[i] < 0) {
980             int p = sc->possible[i];
981
982             if (p == 0) {
983 #ifdef SOLVER_DIAGNOSTICS
984                 if (verbose)
985                     printf("%*sregion %d has no possible colours left\n",
986                            2*sc->depth, "", i);
987 #endif
988                 return 0;              /* puzzle is inconsistent */
989             }
990
991             if ((p & (p-1)) == 0) {    /* p is a power of two */
992                 int c, ret;
993                 for (c = 0; c < FOUR; c++)
994                     if (p == (1 << c))
995                         break;
996                 assert(c < FOUR);
997                 ret = place_colour(sc, colouring, i, c
998 #ifdef SOLVER_DIAGNOSTICS
999                                    , "placing"
1000 #endif
1001                                    );
1002                 /*
1003                  * place_colour() can only fail if colour c was not
1004                  * even a _possibility_ for region i, and we're
1005                  * pretty sure it was because we checked before
1006                  * calling place_colour(). So we can safely assert
1007                  * here rather than having to return a nice
1008                  * friendly error code.
1009                  */
1010                 assert(ret);
1011                 done_something = TRUE;
1012             }
1013         }
1014
1015         if (done_something)
1016             continue;
1017
1018         if (difficulty < DIFF_NORMAL)
1019             break;                     /* can't do anything harder */
1020
1021         /*
1022          * Failing that, go up one level. Look for pairs of regions
1023          * which (a) both have the same pair of possible colours,
1024          * (b) are adjacent to one another, (c) are adjacent to the
1025          * same region, and (d) that region still thinks it has one
1026          * or both of those possible colours.
1027          * 
1028          * Simplest way to do this is by going through the graph
1029          * edge by edge, so that we start with property (b) and
1030          * then look for (a) and finally (c) and (d).
1031          */
1032         for (i = 0; i < ngraph; i++) {
1033             int j1 = graph[i] / n, j2 = graph[i] % n;
1034             int j, k, v, v2;
1035 #ifdef SOLVER_DIAGNOSTICS
1036             int started = FALSE;
1037 #endif
1038
1039             if (j1 > j2)
1040                 continue;              /* done it already, other way round */
1041
1042             if (colouring[j1] >= 0 || colouring[j2] >= 0)
1043                 continue;              /* they're not undecided */
1044
1045             if (sc->possible[j1] != sc->possible[j2])
1046                 continue;              /* they don't have the same possibles */
1047
1048             v = sc->possible[j1];
1049             /*
1050              * See if v contains exactly two set bits.
1051              */
1052             v2 = v & -v;           /* find lowest set bit */
1053             v2 = v & ~v2;          /* clear it */
1054             if (v2 == 0 || (v2 & (v2-1)) != 0)   /* not power of 2 */
1055                 continue;
1056
1057             /*
1058              * We've found regions j1 and j2 satisfying properties
1059              * (a) and (b): they have two possible colours between
1060              * them, and since they're adjacent to one another they
1061              * must use _both_ those colours between them.
1062              * Therefore, if they are both adjacent to any other
1063              * region then that region cannot be either colour.
1064              * 
1065              * Go through the neighbours of j1 and see if any are
1066              * shared with j2.
1067              */
1068             for (j = graph_vertex_start(graph, n, ngraph, j1);
1069                  j < ngraph && graph[j] < n*(j1+1); j++) {
1070                 k = graph[j] - j1*n;
1071                 if (graph_adjacent(graph, n, ngraph, k, j2) &&
1072                     (sc->possible[k] & v)) {
1073 #ifdef SOLVER_DIAGNOSTICS
1074                     if (verbose) {
1075                         char buf[80];
1076                         if (!started)
1077                             printf("%*sadjacent regions %d,%d share colours"
1078                                    " %s\n", 2*sc->depth, "", j1, j2,
1079                                    colourset(buf, v));
1080                         started = TRUE;
1081                         printf("%*s  ruling out %s in region %d\n",2*sc->depth,
1082                                "", colourset(buf, sc->possible[k] & v), k);
1083                     }
1084 #endif
1085                     sc->possible[k] &= ~v;
1086                     done_something = TRUE;
1087                 }
1088             }
1089         }
1090
1091         if (done_something)
1092             continue;
1093
1094         if (difficulty < DIFF_HARD)
1095             break;                     /* can't do anything harder */
1096
1097         /*
1098          * Right; now we get creative. Now we're going to look for
1099          * `forcing chains'. A forcing chain is a path through the
1100          * graph with the following properties:
1101          * 
1102          *  (a) Each vertex on the path has precisely two possible
1103          *      colours.
1104          * 
1105          *  (b) Each pair of vertices which are adjacent on the
1106          *      path share at least one possible colour in common.
1107          * 
1108          *  (c) Each vertex in the middle of the path shares _both_
1109          *      of its colours with at least one of its neighbours
1110          *      (not the same one with both neighbours).
1111          * 
1112          * These together imply that at least one of the possible
1113          * colour choices at one end of the path forces _all_ the
1114          * rest of the colours along the path. In order to make
1115          * real use of this, we need further properties:
1116          * 
1117          *  (c) Ruling out some colour C from the vertex at one end
1118          *      of the path forces the vertex at the other end to
1119          *      take colour C.
1120          * 
1121          *  (d) The two end vertices are mutually adjacent to some
1122          *      third vertex.
1123          * 
1124          *  (e) That third vertex currently has C as a possibility.
1125          * 
1126          * If we can find all of that lot, we can deduce that at
1127          * least one of the two ends of the forcing chain has
1128          * colour C, and that therefore the mutually adjacent third
1129          * vertex does not.
1130          * 
1131          * To find forcing chains, we're going to start a bfs at
1132          * each suitable vertex of the graph, once for each of its
1133          * two possible colours.
1134          */
1135         for (i = 0; i < n; i++) {
1136             int c;
1137
1138             if (colouring[i] >= 0 || bitcount(sc->possible[i]) != 2)
1139                 continue;
1140
1141             for (c = 0; c < FOUR; c++)
1142                 if (sc->possible[i] & (1 << c)) {
1143                     int j, k, gi, origc, currc, head, tail;
1144                     /*
1145                      * Try a bfs from this vertex, ruling out
1146                      * colour c.
1147                      * 
1148                      * Within this loop, we work in colour bitmaps
1149                      * rather than actual colours, because
1150                      * converting back and forth is a needless
1151                      * computational expense.
1152                      */
1153
1154                     origc = 1 << c;
1155
1156                     for (j = 0; j < n; j++) {
1157                         sc->bfscolour[j] = -1;
1158 #ifdef SOLVER_DIAGNOSTICS
1159                         sc->bfsprev[j] = -1;
1160 #endif
1161                     }
1162                     head = tail = 0;
1163                     sc->bfsqueue[tail++] = i;
1164                     sc->bfscolour[i] = sc->possible[i] &~ origc;
1165
1166                     while (head < tail) {
1167                         j = sc->bfsqueue[head++];
1168                         currc = sc->bfscolour[j];
1169
1170                         /*
1171                          * Try neighbours of j.
1172                          */
1173                         for (gi = graph_vertex_start(graph, n, ngraph, j);
1174                              gi < ngraph && graph[gi] < n*(j+1); gi++) {
1175                             k = graph[gi] - j*n;
1176
1177                             /*
1178                              * To continue with the bfs in vertex
1179                              * k, we need k to be
1180                              *  (a) not already visited
1181                              *  (b) have two possible colours
1182                              *  (c) those colours include currc.
1183                              */
1184
1185                             if (sc->bfscolour[k] < 0 &&
1186                                 colouring[k] < 0 &&
1187                                 bitcount(sc->possible[k]) == 2 &&
1188                                 (sc->possible[k] & currc)) {
1189                                 sc->bfsqueue[tail++] = k;
1190                                 sc->bfscolour[k] =
1191                                     sc->possible[k] &~ currc;
1192 #ifdef SOLVER_DIAGNOSTICS
1193                                 sc->bfsprev[k] = j;
1194 #endif
1195                             }
1196
1197                             /*
1198                              * One other possibility is that k
1199                              * might be the region in which we can
1200                              * make a real deduction: if it's
1201                              * adjacent to i, contains currc as a
1202                              * possibility, and currc is equal to
1203                              * the original colour we ruled out.
1204                              */
1205                             if (currc == origc &&
1206                                 graph_adjacent(graph, n, ngraph, k, i) &&
1207                                 (sc->possible[k] & currc)) {
1208 #ifdef SOLVER_DIAGNOSTICS
1209                                 if (verbose) {
1210                                     char buf[80], *sep = "";
1211                                     int r;
1212
1213                                     printf("%*sforcing chain, colour %s, ",
1214                                            2*sc->depth, "",
1215                                            colourset(buf, origc));
1216                                     for (r = j; r != -1; r = sc->bfsprev[r]) {
1217                                         printf("%s%d", sep, r);
1218                                         sep = "-";
1219                                     }
1220                                     printf("\n%*s  ruling out %s in region"
1221                                            " %d\n", 2*sc->depth, "",
1222                                            colourset(buf, origc), k);
1223                                 }
1224 #endif
1225                                 sc->possible[k] &= ~origc;
1226                                 done_something = TRUE;
1227                             }
1228                         }
1229                     }
1230
1231                     assert(tail <= n);
1232                 }
1233         }
1234
1235         if (!done_something)
1236             break;
1237     }
1238
1239     /*
1240      * See if we've got a complete solution, and return if so.
1241      */
1242     for (i = 0; i < n; i++)
1243         if (colouring[i] < 0)
1244             break;
1245     if (i == n) {
1246 #ifdef SOLVER_DIAGNOSTICS
1247         if (verbose)
1248             printf("%*sone solution found\n", 2*sc->depth, "");
1249 #endif
1250         return 1;                      /* success! */
1251     }
1252
1253     /*
1254      * If recursion is not permissible, we now give up.
1255      */
1256     if (difficulty < DIFF_RECURSE) {
1257 #ifdef SOLVER_DIAGNOSTICS
1258         if (verbose)
1259             printf("%*sunable to proceed further without recursion\n",
1260                    2*sc->depth, "");
1261 #endif
1262         return 2;                      /* unable to complete */
1263     }
1264
1265     /*
1266      * Now we've got to do something recursive. So first hunt for a
1267      * currently-most-constrained region.
1268      */
1269     {
1270         int best, bestc;
1271         struct solver_scratch *rsc;
1272         int *subcolouring, *origcolouring;
1273         int ret, subret;
1274         int we_already_got_one;
1275
1276         best = -1;
1277         bestc = FIVE;
1278
1279         for (i = 0; i < n; i++) if (colouring[i] < 0) {
1280             int p = sc->possible[i];
1281             enum { compile_time_assertion = 1 / (FOUR <= 4) };
1282             int c;
1283
1284             /* Count the set bits. */
1285             c = (p & 5) + ((p >> 1) & 5);
1286             c = (c & 3) + ((c >> 2) & 3);
1287             assert(c > 1);             /* or colouring[i] would be >= 0 */
1288
1289             if (c < bestc) {
1290                 best = i;
1291                 bestc = c;
1292             }
1293         }
1294
1295         assert(best >= 0);             /* or we'd be solved already */
1296
1297 #ifdef SOLVER_DIAGNOSTICS
1298         if (verbose)
1299             printf("%*srecursing on region %d\n", 2*sc->depth, "", best);
1300 #endif
1301
1302         /*
1303          * Now iterate over the possible colours for this region.
1304          */
1305         rsc = new_scratch(graph, n, ngraph);
1306         rsc->depth = sc->depth + 1;
1307         origcolouring = snewn(n, int);
1308         memcpy(origcolouring, colouring, n * sizeof(int));
1309         subcolouring = snewn(n, int);
1310         we_already_got_one = FALSE;
1311         ret = 0;
1312
1313         for (i = 0; i < FOUR; i++) {
1314             if (!(sc->possible[best] & (1 << i)))
1315                 continue;
1316
1317             memcpy(rsc->possible, sc->possible, n);
1318             memcpy(subcolouring, origcolouring, n * sizeof(int));
1319
1320             place_colour(rsc, subcolouring, best, i
1321 #ifdef SOLVER_DIAGNOSTICS
1322                          , "trying"
1323 #endif
1324                          );
1325
1326             subret = map_solver(rsc, graph, n, ngraph,
1327                                 subcolouring, difficulty);
1328
1329 #ifdef SOLVER_DIAGNOSTICS
1330             if (verbose) {
1331                 printf("%*sretracting %c in region %d; found %s\n",
1332                        2*sc->depth, "", colnames[i], best,
1333                        subret == 0 ? "no solutions" :
1334                        subret == 1 ? "one solution" : "multiple solutions");
1335             }
1336 #endif
1337
1338             /*
1339              * If this possibility turned up more than one valid
1340              * solution, or if it turned up one and we already had
1341              * one, we're definitely ambiguous.
1342              */
1343             if (subret == 2 || (subret == 1 && we_already_got_one)) {
1344                 ret = 2;
1345                 break;
1346             }
1347
1348             /*
1349              * If this possibility turned up one valid solution and
1350              * it's the first we've seen, copy it into the output.
1351              */
1352             if (subret == 1) {
1353                 memcpy(colouring, subcolouring, n * sizeof(int));
1354                 we_already_got_one = TRUE;
1355                 ret = 1;
1356             }
1357
1358             /*
1359              * Otherwise, this guess led to a contradiction, so we
1360              * do nothing.
1361              */
1362         }
1363
1364         sfree(subcolouring);
1365         free_scratch(rsc);
1366
1367 #ifdef SOLVER_DIAGNOSTICS
1368         if (verbose && sc->depth == 0) {
1369             printf("%*s%s found\n",
1370                    2*sc->depth, "",
1371                    ret == 0 ? "no solutions" :
1372                    ret == 1 ? "one solution" : "multiple solutions");
1373         }
1374 #endif
1375         return ret;
1376     }
1377 }
1378
1379 /* ----------------------------------------------------------------------
1380  * Game generation main function.
1381  */
1382
1383 static char *new_game_desc(game_params *params, random_state *rs,
1384                            char **aux, int interactive)
1385 {
1386     struct solver_scratch *sc = NULL;
1387     int *map, *graph, ngraph, *colouring, *colouring2, *regions;
1388     int i, j, w, h, n, solveret, cfreq[FOUR];
1389     int wh;
1390     int mindiff, tries;
1391 #ifdef GENERATION_DIAGNOSTICS
1392     int x, y;
1393 #endif
1394     char *ret, buf[80];
1395     int retlen, retsize;
1396
1397     w = params->w;
1398     h = params->h;
1399     n = params->n;
1400     wh = w*h;
1401
1402     *aux = NULL;
1403
1404     map = snewn(wh, int);
1405     graph = snewn(n*n, int);
1406     colouring = snewn(n, int);
1407     colouring2 = snewn(n, int);
1408     regions = snewn(n, int);
1409
1410     /*
1411      * This is the minimum difficulty below which we'll completely
1412      * reject a map design. Normally we set this to one below the
1413      * requested difficulty, ensuring that we have the right
1414      * result. However, for particularly dense maps or maps with
1415      * particularly few regions it might not be possible to get the
1416      * desired difficulty, so we will eventually drop this down to
1417      * -1 to indicate that any old map will do.
1418      */
1419     mindiff = params->diff;
1420     tries = 50;
1421
1422     while (1) {
1423
1424         /*
1425          * Create the map.
1426          */
1427         genmap(w, h, n, map, rs);
1428
1429 #ifdef GENERATION_DIAGNOSTICS
1430         for (y = 0; y < h; y++) {
1431             for (x = 0; x < w; x++) {
1432                 int v = map[y*w+x];
1433                 if (v >= 62)
1434                     putchar('!');
1435                 else if (v >= 36)
1436                     putchar('a' + v-36);
1437                 else if (v >= 10)
1438                     putchar('A' + v-10);
1439                 else
1440                     putchar('0' + v);
1441             }
1442             putchar('\n');
1443         }
1444 #endif
1445
1446         /*
1447          * Convert the map into a graph.
1448          */
1449         ngraph = gengraph(w, h, n, map, graph);
1450
1451 #ifdef GENERATION_DIAGNOSTICS
1452         for (i = 0; i < ngraph; i++)
1453             printf("%d-%d\n", graph[i]/n, graph[i]%n);
1454 #endif
1455
1456         /*
1457          * Colour the map.
1458          */
1459         fourcolour(graph, n, ngraph, colouring, rs);
1460
1461 #ifdef GENERATION_DIAGNOSTICS
1462         for (i = 0; i < n; i++)
1463             printf("%d: %d\n", i, colouring[i]);
1464
1465         for (y = 0; y < h; y++) {
1466             for (x = 0; x < w; x++) {
1467                 int v = colouring[map[y*w+x]];
1468                 if (v >= 36)
1469                     putchar('a' + v-36);
1470                 else if (v >= 10)
1471                     putchar('A' + v-10);
1472                 else
1473                     putchar('0' + v);
1474             }
1475             putchar('\n');
1476         }
1477 #endif
1478
1479         /*
1480          * Encode the solution as an aux string.
1481          */
1482         if (*aux)                      /* in case we've come round again */
1483             sfree(*aux);
1484         retlen = retsize = 0;
1485         ret = NULL;
1486         for (i = 0; i < n; i++) {
1487             int len;
1488
1489             if (colouring[i] < 0)
1490                 continue;
1491
1492             len = sprintf(buf, "%s%d:%d", i ? ";" : "S;", colouring[i], i);
1493             if (retlen + len >= retsize) {
1494                 retsize = retlen + len + 256;
1495                 ret = sresize(ret, retsize, char);
1496             }
1497             strcpy(ret + retlen, buf);
1498             retlen += len;
1499         }
1500         *aux = ret;
1501
1502         /*
1503          * Remove the region colours one by one, keeping
1504          * solubility. Also ensure that there always remains at
1505          * least one region of every colour, so that the user can
1506          * drag from somewhere.
1507          */
1508         for (i = 0; i < FOUR; i++)
1509             cfreq[i] = 0;
1510         for (i = 0; i < n; i++) {
1511             regions[i] = i;
1512             cfreq[colouring[i]]++;
1513         }
1514         for (i = 0; i < FOUR; i++)
1515             if (cfreq[i] == 0)
1516                 continue;
1517
1518         shuffle(regions, n, sizeof(*regions), rs);
1519
1520         if (sc) free_scratch(sc);
1521         sc = new_scratch(graph, n, ngraph);
1522
1523         for (i = 0; i < n; i++) {
1524             j = regions[i];
1525
1526             if (cfreq[colouring[j]] == 1)
1527                 continue;              /* can't remove last region of colour */
1528
1529             memcpy(colouring2, colouring, n*sizeof(int));
1530             colouring2[j] = -1;
1531             solveret = map_solver(sc, graph, n, ngraph, colouring2,
1532                                   params->diff);
1533             assert(solveret >= 0);             /* mustn't be impossible! */
1534             if (solveret == 1) {
1535                 cfreq[colouring[j]]--;
1536                 colouring[j] = -1;
1537             }
1538         }
1539
1540 #ifdef GENERATION_DIAGNOSTICS
1541         for (i = 0; i < n; i++)
1542             if (colouring[i] >= 0) {
1543                 if (i >= 62)
1544                     putchar('!');
1545                 else if (i >= 36)
1546                     putchar('a' + i-36);
1547                 else if (i >= 10)
1548                     putchar('A' + i-10);
1549                 else
1550                     putchar('0' + i);
1551                 printf(": %d\n", colouring[i]);
1552             }
1553 #endif
1554
1555         /*
1556          * Finally, check that the puzzle is _at least_ as hard as
1557          * required, and indeed that it isn't already solved.
1558          * (Calling map_solver with negative difficulty ensures the
1559          * latter - if a solver which _does nothing_ can solve it,
1560          * it's too easy!)
1561          */
1562         memcpy(colouring2, colouring, n*sizeof(int));
1563         if (map_solver(sc, graph, n, ngraph, colouring2,
1564                        mindiff - 1) == 1) {
1565             /*
1566              * Drop minimum difficulty if necessary.
1567              */
1568             if (mindiff > 0 && (n < 9 || n > 2*wh/3)) {
1569                 if (tries-- <= 0)
1570                     mindiff = 0;       /* give up and go for Easy */
1571             }
1572             continue;
1573         }
1574
1575         break;
1576     }
1577
1578     /*
1579      * Encode as a game ID. We do this by:
1580      * 
1581      *  - first going along the horizontal edges row by row, and
1582      *    then the vertical edges column by column
1583      *  - encoding the lengths of runs of edges and runs of
1584      *    non-edges
1585      *  - the decoder will reconstitute the region boundaries from
1586      *    this and automatically number them the same way we did
1587      *  - then we encode the initial region colours in a Slant-like
1588      *    fashion (digits 0-3 interspersed with letters giving
1589      *    lengths of runs of empty spaces).
1590      */
1591     retlen = retsize = 0;
1592     ret = NULL;
1593
1594     {
1595         int run, pv;
1596
1597         /*
1598          * Start with a notional non-edge, so that there'll be an
1599          * explicit `a' to distinguish the case where we start with
1600          * an edge.
1601          */
1602         run = 1;
1603         pv = 0;
1604
1605         for (i = 0; i < w*(h-1) + (w-1)*h; i++) {
1606             int x, y, dx, dy, v;
1607
1608             if (i < w*(h-1)) {
1609                 /* Horizontal edge. */
1610                 y = i / w;
1611                 x = i % w;
1612                 dx = 0;
1613                 dy = 1;
1614             } else {
1615                 /* Vertical edge. */
1616                 x = (i - w*(h-1)) / h;
1617                 y = (i - w*(h-1)) % h;
1618                 dx = 1;
1619                 dy = 0;
1620             }
1621
1622             if (retlen + 10 >= retsize) {
1623                 retsize = retlen + 256;
1624                 ret = sresize(ret, retsize, char);
1625             }
1626
1627             v = (map[y*w+x] != map[(y+dy)*w+(x+dx)]);
1628
1629             if (pv != v) {
1630                 ret[retlen++] = 'a'-1 + run;
1631                 run = 1;
1632                 pv = v;
1633             } else {
1634                 /*
1635                  * 'z' is a special case in this encoding. Rather
1636                  * than meaning a run of 26 and a state switch, it
1637                  * means a run of 25 and _no_ state switch, because
1638                  * otherwise there'd be no way to encode runs of
1639                  * more than 26.
1640                  */
1641                 if (run == 25) {
1642                     ret[retlen++] = 'z';
1643                     run = 0;
1644                 }
1645                 run++;
1646             }
1647         }
1648
1649         ret[retlen++] = 'a'-1 + run;
1650         ret[retlen++] = ',';
1651
1652         run = 0;
1653         for (i = 0; i < n; i++) {
1654             if (retlen + 10 >= retsize) {
1655                 retsize = retlen + 256;
1656                 ret = sresize(ret, retsize, char);
1657             }
1658
1659             if (colouring[i] < 0) {
1660                 /*
1661                  * In _this_ encoding, 'z' is a run of 26, since
1662                  * there's no implicit state switch after each run.
1663                  * Confusingly different, but more compact.
1664                  */
1665                 if (run == 26) {
1666                     ret[retlen++] = 'z';
1667                     run = 0;
1668                 }
1669                 run++;
1670             } else {
1671                 if (run > 0)
1672                     ret[retlen++] = 'a'-1 + run;
1673                 ret[retlen++] = '0' + colouring[i];
1674                 run = 0;
1675             }
1676         }
1677         if (run > 0)
1678             ret[retlen++] = 'a'-1 + run;
1679         ret[retlen] = '\0';
1680
1681         assert(retlen < retsize);
1682     }
1683
1684     free_scratch(sc);
1685     sfree(regions);
1686     sfree(colouring2);
1687     sfree(colouring);
1688     sfree(graph);
1689     sfree(map);
1690
1691     return ret;
1692 }
1693
1694 static char *parse_edge_list(game_params *params, char **desc, int *map)
1695 {
1696     int w = params->w, h = params->h, wh = w*h, n = params->n;
1697     int i, k, pos, state;
1698     char *p = *desc;
1699
1700     for (i = 0; i < wh; i++)
1701         map[wh+i] = i;
1702
1703     pos = -1;
1704     state = 0;
1705
1706     /*
1707      * Parse the game description to get the list of edges, and
1708      * build up a disjoint set forest as we go (by identifying
1709      * pairs of squares whenever the edge list shows a non-edge).
1710      */
1711     while (*p && *p != ',') {
1712         if (*p < 'a' || *p > 'z')
1713             return "Unexpected character in edge list";
1714         if (*p == 'z')
1715             k = 25;
1716         else
1717             k = *p - 'a' + 1;
1718         while (k-- > 0) {
1719             int x, y, dx, dy;
1720
1721             if (pos < 0) {
1722                 pos++;
1723                 continue;
1724             } else if (pos < w*(h-1)) {
1725                 /* Horizontal edge. */
1726                 y = pos / w;
1727                 x = pos % w;
1728                 dx = 0;
1729                 dy = 1;
1730             } else if (pos < 2*wh-w-h) {
1731                 /* Vertical edge. */
1732                 x = (pos - w*(h-1)) / h;
1733                 y = (pos - w*(h-1)) % h;
1734                 dx = 1;
1735                 dy = 0;
1736             } else
1737                 return "Too much data in edge list";
1738             if (!state)
1739                 dsf_merge(map+wh, y*w+x, (y+dy)*w+(x+dx));
1740
1741             pos++;
1742         }
1743         if (*p != 'z')
1744             state = !state;
1745         p++;
1746     }
1747     assert(pos <= 2*wh-w-h);
1748     if (pos < 2*wh-w-h)
1749         return "Too little data in edge list";
1750
1751     /*
1752      * Now go through again and allocate region numbers.
1753      */
1754     pos = 0;
1755     for (i = 0; i < wh; i++)
1756         map[i] = -1;
1757     for (i = 0; i < wh; i++) {
1758         k = dsf_canonify(map+wh, i);
1759         if (map[k] < 0)
1760             map[k] = pos++;
1761         map[i] = map[k];
1762     }
1763     if (pos != n)
1764         return "Edge list defines the wrong number of regions";
1765
1766     *desc = p;
1767
1768     return NULL;
1769 }
1770
1771 static char *validate_desc(game_params *params, char *desc)
1772 {
1773     int w = params->w, h = params->h, wh = w*h, n = params->n;
1774     int area;
1775     int *map;
1776     char *ret;
1777
1778     map = snewn(2*wh, int);
1779     ret = parse_edge_list(params, &desc, map);
1780     if (ret)
1781         return ret;
1782     sfree(map);
1783
1784     if (*desc != ',')
1785         return "Expected comma before clue list";
1786     desc++;                            /* eat comma */
1787
1788     area = 0;
1789     while (*desc) {
1790         if (*desc >= '0' && *desc < '0'+FOUR)
1791             area++;
1792         else if (*desc >= 'a' && *desc <= 'z')
1793             area += *desc - 'a' + 1;
1794         else
1795             return "Unexpected character in clue list";
1796         desc++;
1797     }
1798     if (area < n)
1799         return "Too little data in clue list";
1800     else if (area > n)
1801         return "Too much data in clue list";
1802
1803     return NULL;
1804 }
1805
1806 static game_state *new_game(midend *me, game_params *params, char *desc)
1807 {
1808     int w = params->w, h = params->h, wh = w*h, n = params->n;
1809     int i, pos;
1810     char *p;
1811     game_state *state = snew(game_state);
1812
1813     state->p = *params;
1814     state->colouring = snewn(n, int);
1815     for (i = 0; i < n; i++)
1816         state->colouring[i] = -1;
1817     state->pencil = snewn(n, int);
1818     for (i = 0; i < n; i++)
1819         state->pencil[i] = 0;
1820
1821     state->completed = state->cheated = FALSE;
1822
1823     state->map = snew(struct map);
1824     state->map->refcount = 1;
1825     state->map->map = snewn(wh*4, int);
1826     state->map->graph = snewn(n*n, int);
1827     state->map->n = n;
1828     state->map->immutable = snewn(n, int);
1829     for (i = 0; i < n; i++)
1830         state->map->immutable[i] = FALSE;
1831
1832     p = desc;
1833
1834     {
1835         char *ret;
1836         ret = parse_edge_list(params, &p, state->map->map);
1837         assert(!ret);
1838     }
1839
1840     /*
1841      * Set up the other three quadrants in `map'.
1842      */
1843     for (i = wh; i < 4*wh; i++)
1844         state->map->map[i] = state->map->map[i % wh];
1845
1846     assert(*p == ',');
1847     p++;
1848
1849     /*
1850      * Now process the clue list.
1851      */
1852     pos = 0;
1853     while (*p) {
1854         if (*p >= '0' && *p < '0'+FOUR) {
1855             state->colouring[pos] = *p - '0';
1856             state->map->immutable[pos] = TRUE;
1857             pos++;
1858         } else {
1859             assert(*p >= 'a' && *p <= 'z');
1860             pos += *p - 'a' + 1;
1861         }
1862         p++;
1863     }
1864     assert(pos == n);
1865
1866     state->map->ngraph = gengraph(w, h, n, state->map->map, state->map->graph);
1867
1868     /*
1869      * Attempt to smooth out some of the more jagged region
1870      * outlines by the judicious use of diagonally divided squares.
1871      */
1872     {
1873         random_state *rs = random_init(desc, strlen(desc));
1874         int *squares = snewn(wh, int);
1875         int done_something;
1876
1877         for (i = 0; i < wh; i++)
1878             squares[i] = i;
1879         shuffle(squares, wh, sizeof(*squares), rs);
1880
1881         do {
1882             done_something = FALSE;
1883             for (i = 0; i < wh; i++) {
1884                 int y = squares[i] / w, x = squares[i] % w;
1885                 int c = state->map->map[y*w+x];
1886                 int tc, bc, lc, rc;
1887
1888                 if (x == 0 || x == w-1 || y == 0 || y == h-1)
1889                     continue;
1890
1891                 if (state->map->map[TE * wh + y*w+x] !=
1892                     state->map->map[BE * wh + y*w+x])
1893                     continue;
1894
1895                 tc = state->map->map[BE * wh + (y-1)*w+x];
1896                 bc = state->map->map[TE * wh + (y+1)*w+x];
1897                 lc = state->map->map[RE * wh + y*w+(x-1)];
1898                 rc = state->map->map[LE * wh + y*w+(x+1)];
1899
1900                 /*
1901                  * If this square is adjacent on two sides to one
1902                  * region and on the other two sides to the other
1903                  * region, and is itself one of the two regions, we can
1904                  * adjust it so that it's a diagonal.
1905                  */
1906                 if (tc != bc && (tc == c || bc == c)) {
1907                     if ((lc == tc && rc == bc) ||
1908                         (lc == bc && rc == tc)) {
1909                         state->map->map[TE * wh + y*w+x] = tc;
1910                         state->map->map[BE * wh + y*w+x] = bc;
1911                         state->map->map[LE * wh + y*w+x] = lc;
1912                         state->map->map[RE * wh + y*w+x] = rc;
1913                         done_something = TRUE;
1914                     }
1915                 }
1916             }
1917         } while (done_something);
1918         sfree(squares);
1919         random_free(rs);
1920     }
1921
1922     /*
1923      * Analyse the map to find a canonical line segment
1924      * corresponding to each edge, and a canonical point
1925      * corresponding to each region. The former are where we'll
1926      * eventually put error markers; the latter are where we'll put
1927      * per-region flags such as numbers (when in diagnostic mode).
1928      */
1929     {
1930         int *bestx, *besty, *an, pass;
1931         float *ax, *ay, *best;
1932
1933         ax = snewn(state->map->ngraph + n, float);
1934         ay = snewn(state->map->ngraph + n, float);
1935         an = snewn(state->map->ngraph + n, int);
1936         bestx = snewn(state->map->ngraph + n, int);
1937         besty = snewn(state->map->ngraph + n, int);
1938         best = snewn(state->map->ngraph + n, float);
1939
1940         for (i = 0; i < state->map->ngraph + n; i++) {
1941             bestx[i] = besty[i] = -1;
1942             best[i] = 2*(w+h)+1;
1943             ax[i] = ay[i] = 0.0F;
1944             an[i] = 0;
1945         }
1946
1947         /*
1948          * We make two passes over the map, finding all the line
1949          * segments separating regions and all the suitable points
1950          * within regions. In the first pass, we compute the
1951          * _average_ x and y coordinate of all the points in a
1952          * given class; in the second pass, for each such average
1953          * point, we find the candidate closest to it and call that
1954          * canonical.
1955          * 
1956          * Line segments are considered to have coordinates in
1957          * their centre. Thus, at least one coordinate for any line
1958          * segment is always something-and-a-half; so we store our
1959          * coordinates as twice their normal value.
1960          */
1961         for (pass = 0; pass < 2; pass++) {
1962             int x, y;
1963
1964             for (y = 0; y < h; y++)
1965                 for (x = 0; x < w; x++) {
1966                     int ex[4], ey[4], ea[4], eb[4], en = 0;
1967
1968                     /*
1969                      * Look for an edge to the right of this
1970                      * square, an edge below it, and an edge in the
1971                      * middle of it. Also look to see if the point
1972                      * at the bottom right of this square is on an
1973                      * edge (and isn't a place where more than two
1974                      * regions meet).
1975                      */
1976                     if (x+1 < w) {
1977                         /* right edge */
1978                         ea[en] = state->map->map[RE * wh + y*w+x];
1979                         eb[en] = state->map->map[LE * wh + y*w+(x+1)];
1980                         ex[en] = (x+1)*2;
1981                         ey[en] = y*2+1;
1982                         en++;
1983                     }
1984                     if (y+1 < h) {
1985                         /* bottom edge */
1986                         ea[en] = state->map->map[BE * wh + y*w+x];
1987                         eb[en] = state->map->map[TE * wh + (y+1)*w+x];
1988                         ex[en] = x*2+1;
1989                         ey[en] = (y+1)*2;
1990                         en++;
1991                     }
1992                     /* diagonal edge */
1993                     ea[en] = state->map->map[TE * wh + y*w+x];
1994                     eb[en] = state->map->map[BE * wh + y*w+x];
1995                     ex[en] = x*2+1;
1996                     ey[en] = y*2+1;
1997                     en++;
1998
1999                     if (x+1 < w && y+1 < h) {
2000                         /* bottom right corner */
2001                         int oct[8], othercol, nchanges;
2002                         oct[0] = state->map->map[RE * wh + y*w+x];
2003                         oct[1] = state->map->map[LE * wh + y*w+(x+1)];
2004                         oct[2] = state->map->map[BE * wh + y*w+(x+1)];
2005                         oct[3] = state->map->map[TE * wh + (y+1)*w+(x+1)];
2006                         oct[4] = state->map->map[LE * wh + (y+1)*w+(x+1)];
2007                         oct[5] = state->map->map[RE * wh + (y+1)*w+x];
2008                         oct[6] = state->map->map[TE * wh + (y+1)*w+x];
2009                         oct[7] = state->map->map[BE * wh + y*w+x];
2010
2011                         othercol = -1;
2012                         nchanges = 0;
2013                         for (i = 0; i < 8; i++) {
2014                             if (oct[i] != oct[0]) {
2015                                 if (othercol < 0)
2016                                     othercol = oct[i];
2017                                 else if (othercol != oct[i])
2018                                     break;   /* three colours at this point */
2019                             }
2020                             if (oct[i] != oct[(i+1) & 7])
2021                                 nchanges++;
2022                         }
2023
2024                         /*
2025                          * Now if there are exactly two regions at
2026                          * this point (not one, and not three or
2027                          * more), and only two changes around the
2028                          * loop, then this is a valid place to put
2029                          * an error marker.
2030                          */
2031                         if (i == 8 && othercol >= 0 && nchanges == 2) {
2032                             ea[en] = oct[0];
2033                             eb[en] = othercol;
2034                             ex[en] = (x+1)*2;
2035                             ey[en] = (y+1)*2;
2036                             en++;
2037                         }
2038
2039                         /*
2040                          * If there's exactly _one_ region at this
2041                          * point, on the other hand, it's a valid
2042                          * place to put a region centre.
2043                          */
2044                         if (othercol < 0) {
2045                             ea[en] = eb[en] = oct[0];
2046                             ex[en] = (x+1)*2;
2047                             ey[en] = (y+1)*2;
2048                             en++;
2049                         }
2050                     }
2051
2052                     /*
2053                      * Now process the points we've found, one by
2054                      * one.
2055                      */
2056                     for (i = 0; i < en; i++) {
2057                         int emin = min(ea[i], eb[i]);
2058                         int emax = max(ea[i], eb[i]);
2059                         int gindex;
2060
2061                         if (emin != emax) {
2062                             /* Graph edge */
2063                             gindex =
2064                                 graph_edge_index(state->map->graph, n,
2065                                                  state->map->ngraph, emin,
2066                                                  emax);
2067                         } else {
2068                             /* Region number */
2069                             gindex = state->map->ngraph + emin;
2070                         }
2071
2072                         assert(gindex >= 0);
2073
2074                         if (pass == 0) {
2075                             /*
2076                              * In pass 0, accumulate the values
2077                              * we'll use to compute the average
2078                              * positions.
2079                              */
2080                             ax[gindex] += ex[i];
2081                             ay[gindex] += ey[i];
2082                             an[gindex] += 1.0F;
2083                         } else {
2084                             /*
2085                              * In pass 1, work out whether this
2086                              * point is closer to the average than
2087                              * the last one we've seen.
2088                              */
2089                             float dx, dy, d;
2090
2091                             assert(an[gindex] > 0);
2092                             dx = ex[i] - ax[gindex];
2093                             dy = ey[i] - ay[gindex];
2094                             d = sqrt(dx*dx + dy*dy);
2095                             if (d < best[gindex]) {
2096                                 best[gindex] = d;
2097                                 bestx[gindex] = ex[i];
2098                                 besty[gindex] = ey[i];
2099                             }
2100                         }
2101                     }
2102                 }
2103
2104             if (pass == 0) {
2105                 for (i = 0; i < state->map->ngraph + n; i++)
2106                     if (an[i] > 0) {
2107                         ax[i] /= an[i];
2108                         ay[i] /= an[i];
2109                     }
2110             }
2111         }
2112
2113         state->map->edgex = snewn(state->map->ngraph, int);
2114         state->map->edgey = snewn(state->map->ngraph, int);
2115         memcpy(state->map->edgex, bestx, state->map->ngraph * sizeof(int));
2116         memcpy(state->map->edgey, besty, state->map->ngraph * sizeof(int));
2117
2118         state->map->regionx = snewn(n, int);
2119         state->map->regiony = snewn(n, int);
2120         memcpy(state->map->regionx, bestx + state->map->ngraph, n*sizeof(int));
2121         memcpy(state->map->regiony, besty + state->map->ngraph, n*sizeof(int));
2122
2123         for (i = 0; i < state->map->ngraph; i++)
2124             if (state->map->edgex[i] < 0) {
2125                 /* Find the other representation of this edge. */
2126                 int e = state->map->graph[i];
2127                 int iprime = graph_edge_index(state->map->graph, n,
2128                                               state->map->ngraph, e%n, e/n);
2129                 assert(state->map->edgex[iprime] >= 0);
2130                 state->map->edgex[i] = state->map->edgex[iprime];
2131                 state->map->edgey[i] = state->map->edgey[iprime];
2132             }
2133
2134         sfree(ax);
2135         sfree(ay);
2136         sfree(an);
2137         sfree(best);
2138         sfree(bestx);
2139         sfree(besty);
2140     }
2141
2142     return state;
2143 }
2144
2145 static game_state *dup_game(game_state *state)
2146 {
2147     game_state *ret = snew(game_state);
2148
2149     ret->p = state->p;
2150     ret->colouring = snewn(state->p.n, int);
2151     memcpy(ret->colouring, state->colouring, state->p.n * sizeof(int));
2152     ret->pencil = snewn(state->p.n, int);
2153     memcpy(ret->pencil, state->pencil, state->p.n * sizeof(int));
2154     ret->map = state->map;
2155     ret->map->refcount++;
2156     ret->completed = state->completed;
2157     ret->cheated = state->cheated;
2158
2159     return ret;
2160 }
2161
2162 static void free_game(game_state *state)
2163 {
2164     if (--state->map->refcount <= 0) {
2165         sfree(state->map->map);
2166         sfree(state->map->graph);
2167         sfree(state->map->immutable);
2168         sfree(state->map->edgex);
2169         sfree(state->map->edgey);
2170         sfree(state->map->regionx);
2171         sfree(state->map->regiony);
2172         sfree(state->map);
2173     }
2174     sfree(state->colouring);
2175     sfree(state);
2176 }
2177
2178 static char *solve_game(game_state *state, game_state *currstate,
2179                         char *aux, char **error)
2180 {
2181     if (!aux) {
2182         /*
2183          * Use the solver.
2184          */
2185         int *colouring;
2186         struct solver_scratch *sc;
2187         int sret;
2188         int i;
2189         char *ret, buf[80];
2190         int retlen, retsize;
2191
2192         colouring = snewn(state->map->n, int);
2193         memcpy(colouring, state->colouring, state->map->n * sizeof(int));
2194
2195         sc = new_scratch(state->map->graph, state->map->n, state->map->ngraph);
2196         sret = map_solver(sc, state->map->graph, state->map->n,
2197                          state->map->ngraph, colouring, DIFFCOUNT-1);
2198         free_scratch(sc);
2199
2200         if (sret != 1) {
2201             sfree(colouring);
2202             if (sret == 0)
2203                 *error = "Puzzle is inconsistent";
2204             else
2205                 *error = "Unable to find a unique solution for this puzzle";
2206             return NULL;
2207         }
2208
2209         retsize = 64;
2210         ret = snewn(retsize, char);
2211         strcpy(ret, "S");
2212         retlen = 1;
2213
2214         for (i = 0; i < state->map->n; i++) {
2215             int len;
2216
2217             assert(colouring[i] >= 0);
2218             if (colouring[i] == currstate->colouring[i])
2219                 continue;
2220             assert(!state->map->immutable[i]);
2221
2222             len = sprintf(buf, ";%d:%d", colouring[i], i);
2223             if (retlen + len >= retsize) {
2224                 retsize = retlen + len + 256;
2225                 ret = sresize(ret, retsize, char);
2226             }
2227             strcpy(ret + retlen, buf);
2228             retlen += len;
2229         }
2230
2231         sfree(colouring);
2232
2233         return ret;
2234     }
2235     return dupstr(aux);
2236 }
2237
2238 static char *game_text_format(game_state *state)
2239 {
2240     return NULL;
2241 }
2242
2243 struct game_ui {
2244     int drag_colour;                   /* -1 means no drag active */
2245     int dragx, dragy;
2246     int show_numbers;
2247 };
2248
2249 static game_ui *new_ui(game_state *state)
2250 {
2251     game_ui *ui = snew(game_ui);
2252     ui->dragx = ui->dragy = -1;
2253     ui->drag_colour = -2;
2254     ui->show_numbers = FALSE;
2255     return ui;
2256 }
2257
2258 static void free_ui(game_ui *ui)
2259 {
2260     sfree(ui);
2261 }
2262
2263 static char *encode_ui(game_ui *ui)
2264 {
2265     return NULL;
2266 }
2267
2268 static void decode_ui(game_ui *ui, char *encoding)
2269 {
2270 }
2271
2272 static void game_changed_state(game_ui *ui, game_state *oldstate,
2273                                game_state *newstate)
2274 {
2275 }
2276
2277 struct game_drawstate {
2278     int tilesize;
2279     unsigned long *drawn, *todraw;
2280     int started;
2281     int dragx, dragy, drag_visible;
2282     blitter *bl;
2283 };
2284
2285 /* Flags in `drawn'. */
2286 #define ERR_BASE      0x00800000L
2287 #define ERR_MASK      0xFF800000L
2288 #define PENCIL_T_BASE 0x00080000L
2289 #define PENCIL_T_MASK 0x00780000L
2290 #define PENCIL_B_BASE 0x00008000L
2291 #define PENCIL_B_MASK 0x00078000L
2292 #define PENCIL_MASK   0x007F8000L
2293 #define SHOW_NUMBERS  0x00004000L
2294
2295 #define TILESIZE (ds->tilesize)
2296 #define BORDER (TILESIZE)
2297 #define COORD(x)  ( (x) * TILESIZE + BORDER )
2298 #define FROMCOORD(x)  ( ((x) - BORDER + TILESIZE) / TILESIZE - 1 )
2299
2300 static int region_from_coords(game_state *state, game_drawstate *ds,
2301                               int x, int y)
2302 {
2303     int w = state->p.w, h = state->p.h, wh = w*h /*, n = state->p.n */;
2304     int tx = FROMCOORD(x), ty = FROMCOORD(y);
2305     int dx = x - COORD(tx), dy = y - COORD(ty);
2306     int quadrant;
2307
2308     if (tx < 0 || tx >= w || ty < 0 || ty >= h)
2309         return -1;                     /* border */
2310
2311     quadrant = 2 * (dx > dy) + (TILESIZE - dx > dy);
2312     quadrant = (quadrant == 0 ? BE :
2313                 quadrant == 1 ? LE :
2314                 quadrant == 2 ? RE : TE);
2315
2316     return state->map->map[quadrant * wh + ty*w+tx];
2317 }
2318
2319 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2320                             int x, int y, int button)
2321 {
2322     char buf[80];
2323
2324     /*
2325      * Enable or disable numeric labels on regions.
2326      */
2327     if (button == 'l' || button == 'L') {
2328         ui->show_numbers = !ui->show_numbers;
2329         return "";
2330     }
2331
2332     if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
2333         int r = region_from_coords(state, ds, x, y);
2334
2335         if (r >= 0)
2336             ui->drag_colour = state->colouring[r];
2337         else
2338             ui->drag_colour = -1;
2339         ui->dragx = x;
2340         ui->dragy = y;
2341         return "";
2342     }
2343
2344     if ((button == LEFT_DRAG || button == RIGHT_DRAG) &&
2345         ui->drag_colour > -2) {
2346         ui->dragx = x;
2347         ui->dragy = y;
2348         return "";
2349     }
2350
2351     if ((button == LEFT_RELEASE || button == RIGHT_RELEASE) &&
2352         ui->drag_colour > -2) {
2353         int r = region_from_coords(state, ds, x, y);
2354         int c = ui->drag_colour;
2355
2356         /*
2357          * Cancel the drag, whatever happens.
2358          */
2359         ui->drag_colour = -2;
2360         ui->dragx = ui->dragy = -1;
2361
2362         if (r < 0)
2363             return "";                 /* drag into border; do nothing else */
2364
2365         if (state->map->immutable[r])
2366             return "";                 /* can't change this region */
2367
2368         if (state->colouring[r] == c)
2369             return "";                 /* don't _need_ to change this region */
2370
2371         if (button == RIGHT_RELEASE && state->colouring[r] >= 0)
2372             return "";                 /* can't pencil on a coloured region */
2373
2374         sprintf(buf, "%s%c:%d", (button == RIGHT_RELEASE ? "p" : ""),
2375                 (int)(c < 0 ? 'C' : '0' + c), r);
2376         return dupstr(buf);
2377     }
2378
2379     return NULL;
2380 }
2381
2382 static game_state *execute_move(game_state *state, char *move)
2383 {
2384     int n = state->p.n;
2385     game_state *ret = dup_game(state);
2386     int c, k, adv, i;
2387
2388     while (*move) {
2389         int pencil = FALSE;
2390
2391         c = *move;
2392         if (c == 'p') {
2393             pencil = TRUE;
2394             c = *++move;
2395         }
2396         if ((c == 'C' || (c >= '0' && c < '0'+FOUR)) &&
2397             sscanf(move+1, ":%d%n", &k, &adv) == 1 &&
2398             k >= 0 && k < state->p.n) {
2399             move += 1 + adv;
2400             if (pencil) {
2401                 if (ret->colouring[k] >= 0) {
2402                     free_game(ret);
2403                     return NULL;
2404                 }
2405                 if (c == 'C')
2406                     ret->pencil[k] = 0;
2407                 else
2408                     ret->pencil[k] ^= 1 << (c - '0');
2409             } else {
2410                 ret->colouring[k] = (c == 'C' ? -1 : c - '0');
2411                 ret->pencil[k] = 0;
2412             }
2413         } else if (*move == 'S') {
2414             move++;
2415             ret->cheated = TRUE;
2416         } else {
2417             free_game(ret);
2418             return NULL;
2419         }
2420
2421         if (*move && *move != ';') {
2422             free_game(ret);
2423             return NULL;
2424         }
2425         if (*move)
2426             move++;
2427     }
2428
2429     /*
2430      * Check for completion.
2431      */
2432     if (!ret->completed) {
2433         int ok = TRUE;
2434
2435         for (i = 0; i < n; i++)
2436             if (ret->colouring[i] < 0) {
2437                 ok = FALSE;
2438                 break;
2439             }
2440
2441         if (ok) {
2442             for (i = 0; i < ret->map->ngraph; i++) {
2443                 int j = ret->map->graph[i] / n;
2444                 int k = ret->map->graph[i] % n;
2445                 if (ret->colouring[j] == ret->colouring[k]) {
2446                     ok = FALSE;
2447                     break;
2448                 }
2449             }
2450         }
2451
2452         if (ok)
2453             ret->completed = TRUE;
2454     }
2455
2456     return ret;
2457 }
2458
2459 /* ----------------------------------------------------------------------
2460  * Drawing routines.
2461  */
2462
2463 static void game_compute_size(game_params *params, int tilesize,
2464                               int *x, int *y)
2465 {
2466     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2467     struct { int tilesize; } ads, *ds = &ads;
2468     ads.tilesize = tilesize;
2469
2470     *x = params->w * TILESIZE + 2 * BORDER + 1;
2471     *y = params->h * TILESIZE + 2 * BORDER + 1;
2472 }
2473
2474 static void game_set_size(drawing *dr, game_drawstate *ds,
2475                           game_params *params, int tilesize)
2476 {
2477     ds->tilesize = tilesize;
2478
2479     if (ds->bl)
2480         blitter_free(dr, ds->bl);
2481     ds->bl = blitter_new(dr, TILESIZE+3, TILESIZE+3);
2482 }
2483
2484 const float map_colours[FOUR][3] = {
2485     {0.7F, 0.5F, 0.4F},
2486     {0.8F, 0.7F, 0.4F},
2487     {0.5F, 0.6F, 0.4F},
2488     {0.55F, 0.45F, 0.35F},
2489 };
2490 const int map_hatching[FOUR] = {
2491     HATCH_VERT, HATCH_SLASH, HATCH_HORIZ, HATCH_BACKSLASH
2492 };
2493
2494 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
2495 {
2496     float *ret = snewn(3 * NCOLOURS, float);
2497
2498     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2499
2500     ret[COL_GRID * 3 + 0] = 0.0F;
2501     ret[COL_GRID * 3 + 1] = 0.0F;
2502     ret[COL_GRID * 3 + 2] = 0.0F;
2503
2504     memcpy(ret + COL_0 * 3, map_colours[0], 3 * sizeof(float));
2505     memcpy(ret + COL_1 * 3, map_colours[1], 3 * sizeof(float));
2506     memcpy(ret + COL_2 * 3, map_colours[2], 3 * sizeof(float));
2507     memcpy(ret + COL_3 * 3, map_colours[3], 3 * sizeof(float));
2508
2509     ret[COL_ERROR * 3 + 0] = 1.0F;
2510     ret[COL_ERROR * 3 + 1] = 0.0F;
2511     ret[COL_ERROR * 3 + 2] = 0.0F;
2512
2513     ret[COL_ERRTEXT * 3 + 0] = 1.0F;
2514     ret[COL_ERRTEXT * 3 + 1] = 1.0F;
2515     ret[COL_ERRTEXT * 3 + 2] = 1.0F;
2516
2517     *ncolours = NCOLOURS;
2518     return ret;
2519 }
2520
2521 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2522 {
2523     struct game_drawstate *ds = snew(struct game_drawstate);
2524     int i;
2525
2526     ds->tilesize = 0;
2527     ds->drawn = snewn(state->p.w * state->p.h, unsigned long);
2528     for (i = 0; i < state->p.w * state->p.h; i++)
2529         ds->drawn[i] = 0xFFFFL;
2530     ds->todraw = snewn(state->p.w * state->p.h, unsigned long);
2531     ds->started = FALSE;
2532     ds->bl = NULL;
2533     ds->drag_visible = FALSE;
2534     ds->dragx = ds->dragy = -1;
2535
2536     return ds;
2537 }
2538
2539 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2540 {
2541     sfree(ds->drawn);
2542     sfree(ds->todraw);
2543     if (ds->bl)
2544         blitter_free(dr, ds->bl);
2545     sfree(ds);
2546 }
2547
2548 static void draw_error(drawing *dr, game_drawstate *ds, int x, int y)
2549 {
2550     int coords[8];
2551     int yext, xext;
2552
2553     /*
2554      * Draw a diamond.
2555      */
2556     coords[0] = x - TILESIZE*2/5;
2557     coords[1] = y;
2558     coords[2] = x;
2559     coords[3] = y - TILESIZE*2/5;
2560     coords[4] = x + TILESIZE*2/5;
2561     coords[5] = y;
2562     coords[6] = x;
2563     coords[7] = y + TILESIZE*2/5;
2564     draw_polygon(dr, coords, 4, COL_ERROR, COL_GRID);
2565
2566     /*
2567      * Draw an exclamation mark in the diamond. This turns out to
2568      * look unpleasantly off-centre if done via draw_text, so I do
2569      * it by hand on the basis that exclamation marks aren't that
2570      * difficult to draw...
2571      */
2572     xext = TILESIZE/16;
2573     yext = TILESIZE*2/5 - (xext*2+2);
2574     draw_rect(dr, x-xext, y-yext, xext*2+1, yext*2+1 - (xext*3),
2575               COL_ERRTEXT);
2576     draw_rect(dr, x-xext, y+yext-xext*2+1, xext*2+1, xext*2, COL_ERRTEXT);
2577 }
2578
2579 static void draw_square(drawing *dr, game_drawstate *ds,
2580                         game_params *params, struct map *map,
2581                         int x, int y, int v)
2582 {
2583     int w = params->w, h = params->h, wh = w*h;
2584     int tv, bv, xo, yo, errs, pencil, i, j, oldj;
2585     int show_numbers;
2586
2587     errs = v & ERR_MASK;
2588     v &= ~ERR_MASK;
2589     pencil = v & PENCIL_MASK;
2590     v &= ~PENCIL_MASK;
2591     show_numbers = v & SHOW_NUMBERS;
2592     v &= ~SHOW_NUMBERS;
2593     tv = v / FIVE;
2594     bv = v % FIVE;
2595
2596     clip(dr, COORD(x), COORD(y), TILESIZE, TILESIZE);
2597
2598     /*
2599      * Draw the region colour.
2600      */
2601     draw_rect(dr, COORD(x), COORD(y), TILESIZE, TILESIZE,
2602               (tv == FOUR ? COL_BACKGROUND : COL_0 + tv));
2603     /*
2604      * Draw the second region colour, if this is a diagonally
2605      * divided square.
2606      */
2607     if (map->map[TE * wh + y*w+x] != map->map[BE * wh + y*w+x]) {
2608         int coords[6];
2609         coords[0] = COORD(x)-1;
2610         coords[1] = COORD(y+1)+1;
2611         if (map->map[LE * wh + y*w+x] == map->map[TE * wh + y*w+x])
2612             coords[2] = COORD(x+1)+1;
2613         else
2614             coords[2] = COORD(x)-1;
2615         coords[3] = COORD(y)-1;
2616         coords[4] = COORD(x+1)+1;
2617         coords[5] = COORD(y+1)+1;
2618         draw_polygon(dr, coords, 3,
2619                      (bv == FOUR ? COL_BACKGROUND : COL_0 + bv), COL_GRID);
2620     }
2621
2622     /*
2623      * Draw `pencil marks'. Currently we arrange these in a square
2624      * formation, which means we may be in trouble if the value of
2625      * FOUR changes later...
2626      */
2627     assert(FOUR == 4);
2628     for (yo = 0; yo < 4; yo++)
2629         for (xo = 0; xo < 4; xo++) {
2630             int te = map->map[TE * wh + y*w+x];
2631             int e, ee, c;
2632
2633             e = (yo < xo && yo < 3-xo ? TE :
2634                  yo > xo && yo > 3-xo ? BE :
2635                  xo < 2 ? LE : RE);
2636             ee = map->map[e * wh + y*w+x];
2637
2638             c = (yo & 1) * 2 + (xo & 1);
2639
2640             if (!(pencil & ((ee == te ? PENCIL_T_BASE : PENCIL_B_BASE) << c)))
2641                 continue;
2642
2643             if (yo == xo &&
2644                 (map->map[TE * wh + y*w+x] != map->map[LE * wh + y*w+x]))
2645                 continue;              /* avoid TL-BR diagonal line */
2646             if (yo == 3-xo &&
2647                 (map->map[TE * wh + y*w+x] != map->map[RE * wh + y*w+x]))
2648                 continue;              /* avoid BL-TR diagonal line */
2649
2650             draw_rect(dr, COORD(x) + (5*xo+1)*TILESIZE/20,
2651                       COORD(y) + (5*yo+1)*TILESIZE/20,
2652                       4*TILESIZE/20, 4*TILESIZE/20, COL_0 + c);
2653         }
2654
2655     /*
2656      * Draw the grid lines, if required.
2657      */
2658     if (x <= 0 || map->map[RE*wh+y*w+(x-1)] != map->map[LE*wh+y*w+x])
2659         draw_rect(dr, COORD(x), COORD(y), 1, TILESIZE, COL_GRID);
2660     if (y <= 0 || map->map[BE*wh+(y-1)*w+x] != map->map[TE*wh+y*w+x])
2661         draw_rect(dr, COORD(x), COORD(y), TILESIZE, 1, COL_GRID);
2662     if (x <= 0 || y <= 0 ||
2663         map->map[RE*wh+(y-1)*w+(x-1)] != map->map[TE*wh+y*w+x] ||
2664         map->map[BE*wh+(y-1)*w+(x-1)] != map->map[LE*wh+y*w+x])
2665         draw_rect(dr, COORD(x), COORD(y), 1, 1, COL_GRID);
2666
2667     /*
2668      * Draw error markers.
2669      */
2670     for (yo = 0; yo < 3; yo++)
2671         for (xo = 0; xo < 3; xo++)
2672             if (errs & (ERR_BASE << (yo*3+xo)))
2673                 draw_error(dr, ds,
2674                            (COORD(x)*2+TILESIZE*xo)/2,
2675                            (COORD(y)*2+TILESIZE*yo)/2);
2676
2677     /*
2678      * Draw region numbers, if desired.
2679      */
2680     if (show_numbers) {
2681         oldj = -1;
2682         for (i = 0; i < 2; i++) {
2683             j = map->map[(i?BE:TE)*wh+y*w+x];
2684             if (oldj == j)
2685                 continue;
2686             oldj = j;
2687
2688             xo = map->regionx[j] - 2*x;
2689             yo = map->regiony[j] - 2*y;
2690             if (xo >= 0 && xo <= 2 && yo >= 0 && yo <= 2) {
2691                 char buf[80];
2692                 sprintf(buf, "%d", j);
2693                 draw_text(dr, (COORD(x)*2+TILESIZE*xo)/2,
2694                           (COORD(y)*2+TILESIZE*yo)/2,
2695                           FONT_VARIABLE, 3*TILESIZE/5,
2696                           ALIGN_HCENTRE|ALIGN_VCENTRE,
2697                           COL_GRID, buf);
2698             }
2699         }
2700     }
2701
2702     unclip(dr);
2703
2704     draw_update(dr, COORD(x), COORD(y), TILESIZE, TILESIZE);
2705 }
2706
2707 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2708                         game_state *state, int dir, game_ui *ui,
2709                         float animtime, float flashtime)
2710 {
2711     int w = state->p.w, h = state->p.h, wh = w*h, n = state->p.n;
2712     int x, y, i;
2713     int flash;
2714
2715     if (ds->drag_visible) {
2716         blitter_load(dr, ds->bl, ds->dragx, ds->dragy);
2717         draw_update(dr, ds->dragx, ds->dragy, TILESIZE + 3, TILESIZE + 3);
2718         ds->drag_visible = FALSE;
2719     }
2720
2721     /*
2722      * The initial contents of the window are not guaranteed and
2723      * can vary with front ends. To be on the safe side, all games
2724      * should start by drawing a big background-colour rectangle
2725      * covering the whole window.
2726      */
2727     if (!ds->started) {
2728         int ww, wh;
2729
2730         game_compute_size(&state->p, TILESIZE, &ww, &wh);
2731         draw_rect(dr, 0, 0, ww, wh, COL_BACKGROUND);
2732         draw_rect(dr, COORD(0), COORD(0), w*TILESIZE+1, h*TILESIZE+1,
2733                   COL_GRID);
2734
2735         draw_update(dr, 0, 0, ww, wh);
2736         ds->started = TRUE;
2737     }
2738
2739     if (flashtime) {
2740         if (flash_type == 1)
2741             flash = (int)(flashtime * FOUR / flash_length);
2742         else
2743             flash = 1 + (int)(flashtime * THREE / flash_length);
2744     } else
2745         flash = -1;
2746
2747     /*
2748      * Set up the `todraw' array.
2749      */
2750     for (y = 0; y < h; y++)
2751         for (x = 0; x < w; x++) {
2752             int tv = state->colouring[state->map->map[TE * wh + y*w+x]];
2753             int bv = state->colouring[state->map->map[BE * wh + y*w+x]];
2754             int v;
2755
2756             if (tv < 0)
2757                 tv = FOUR;
2758             if (bv < 0)
2759                 bv = FOUR;
2760
2761             if (flash >= 0) {
2762                 if (flash_type == 1) {
2763                     if (tv == flash)
2764                         tv = FOUR;
2765                     if (bv == flash)
2766                         bv = FOUR;
2767                 } else if (flash_type == 2) {
2768                     if (flash % 2)
2769                         tv = bv = FOUR;
2770                 } else {
2771                     if (tv != FOUR)
2772                         tv = (tv + flash) % FOUR;
2773                     if (bv != FOUR)
2774                         bv = (bv + flash) % FOUR;
2775                 }
2776             }
2777
2778             v = tv * FIVE + bv;
2779
2780             /*
2781              * Add pencil marks.
2782              */
2783             for (i = 0; i < FOUR; i++) {
2784                 if (state->colouring[state->map->map[TE * wh + y*w+x]] < 0 &&
2785                     (state->pencil[state->map->map[TE * wh + y*w+x]] & (1<<i)))
2786                     v |= PENCIL_T_BASE << i;
2787                 if (state->colouring[state->map->map[BE * wh + y*w+x]] < 0 &&
2788                     (state->pencil[state->map->map[BE * wh + y*w+x]] & (1<<i)))
2789                     v |= PENCIL_B_BASE << i;
2790             }
2791
2792             if (ui->show_numbers)
2793                 v |= SHOW_NUMBERS;
2794
2795             ds->todraw[y*w+x] = v;
2796         }
2797
2798     /*
2799      * Add error markers to the `todraw' array.
2800      */
2801     for (i = 0; i < state->map->ngraph; i++) {
2802         int v1 = state->map->graph[i] / n;
2803         int v2 = state->map->graph[i] % n;
2804         int xo, yo;
2805
2806         if (state->colouring[v1] < 0 || state->colouring[v2] < 0)
2807             continue;
2808         if (state->colouring[v1] != state->colouring[v2])
2809             continue;
2810
2811         x = state->map->edgex[i];
2812         y = state->map->edgey[i];
2813
2814         xo = x % 2; x /= 2;
2815         yo = y % 2; y /= 2;
2816
2817         ds->todraw[y*w+x] |= ERR_BASE << (yo*3+xo);
2818         if (xo == 0) {
2819             assert(x > 0);
2820             ds->todraw[y*w+(x-1)] |= ERR_BASE << (yo*3+2);
2821         }
2822         if (yo == 0) {
2823             assert(y > 0);
2824             ds->todraw[(y-1)*w+x] |= ERR_BASE << (2*3+xo);
2825         }
2826         if (xo == 0 && yo == 0) {
2827             assert(x > 0 && y > 0);
2828             ds->todraw[(y-1)*w+(x-1)] |= ERR_BASE << (2*3+2);
2829         }
2830     }
2831
2832     /*
2833      * Now actually draw everything.
2834      */
2835     for (y = 0; y < h; y++)
2836         for (x = 0; x < w; x++) {
2837             int v = ds->todraw[y*w+x];
2838             if (ds->drawn[y*w+x] != v) {
2839                 draw_square(dr, ds, &state->p, state->map, x, y, v);
2840                 ds->drawn[y*w+x] = v;
2841             }
2842         }
2843
2844     /*
2845      * Draw the dragged colour blob if any.
2846      */
2847     if (ui->drag_colour > -2) {
2848         ds->dragx = ui->dragx - TILESIZE/2 - 2;
2849         ds->dragy = ui->dragy - TILESIZE/2 - 2;
2850         blitter_save(dr, ds->bl, ds->dragx, ds->dragy);
2851         draw_circle(dr, ui->dragx, ui->dragy, TILESIZE/2,
2852                     (ui->drag_colour < 0 ? COL_BACKGROUND :
2853                      COL_0 + ui->drag_colour), COL_GRID);
2854         draw_update(dr, ds->dragx, ds->dragy, TILESIZE + 3, TILESIZE + 3);
2855         ds->drag_visible = TRUE;
2856     }
2857 }
2858
2859 static float game_anim_length(game_state *oldstate, game_state *newstate,
2860                               int dir, game_ui *ui)
2861 {
2862     return 0.0F;
2863 }
2864
2865 static float game_flash_length(game_state *oldstate, game_state *newstate,
2866                                int dir, game_ui *ui)
2867 {
2868     if (!oldstate->completed && newstate->completed &&
2869         !oldstate->cheated && !newstate->cheated) {
2870         if (flash_type < 0) {
2871             char *env = getenv("MAP_ALTERNATIVE_FLASH");
2872             if (env)
2873                 flash_type = atoi(env);
2874             else
2875                 flash_type = 0;
2876             flash_length = (flash_type == 1 ? 0.50 : 0.30);
2877         }
2878         return flash_length;
2879     } else
2880         return 0.0F;
2881 }
2882
2883 static int game_wants_statusbar(void)
2884 {
2885     return FALSE;
2886 }
2887
2888 static int game_timing_state(game_state *state, game_ui *ui)
2889 {
2890     return TRUE;
2891 }
2892
2893 static void game_print_size(game_params *params, float *x, float *y)
2894 {
2895     int pw, ph;
2896
2897     /*
2898      * I'll use 4mm squares by default, I think. Simplest way to
2899      * compute this size is to compute the pixel puzzle size at a
2900      * given tile size and then scale.
2901      */
2902     game_compute_size(params, 400, &pw, &ph);
2903     *x = pw / 100.0;
2904     *y = ph / 100.0;
2905 }
2906
2907 static void game_print(drawing *dr, game_state *state, int tilesize)
2908 {
2909     int w = state->p.w, h = state->p.h, wh = w*h, n = state->p.n;
2910     int ink, c[FOUR], i;
2911     int x, y, r;
2912     int *coords, ncoords, coordsize;
2913
2914     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2915     struct { int tilesize; } ads, *ds = &ads;
2916     ads.tilesize = tilesize;
2917
2918     ink = print_mono_colour(dr, 0);
2919     for (i = 0; i < FOUR; i++)
2920         c[i] = print_rgb_colour(dr, map_hatching[i], map_colours[i][0],
2921                                 map_colours[i][1], map_colours[i][2]);
2922
2923     coordsize = 0;
2924     coords = NULL;
2925
2926     print_line_width(dr, TILESIZE / 16);
2927
2928     /*
2929      * Draw a single filled polygon around each region.
2930      */
2931     for (r = 0; r < n; r++) {
2932         int octants[8], lastdir, d1, d2, ox, oy;
2933
2934         /*
2935          * Start by finding a point on the region boundary. Any
2936          * point will do. To do this, we'll search for a square
2937          * containing the region and then decide which corner of it
2938          * to use.
2939          */
2940         x = w;
2941         for (y = 0; y < h; y++) {
2942             for (x = 0; x < w; x++) {
2943                 if (state->map->map[wh*0+y*w+x] == r ||
2944                     state->map->map[wh*1+y*w+x] == r ||
2945                     state->map->map[wh*2+y*w+x] == r ||
2946                     state->map->map[wh*3+y*w+x] == r)
2947                     break;
2948             }
2949             if (x < w)
2950                 break;
2951         }
2952         assert(y < h && x < w);        /* we must have found one somewhere */
2953         /*
2954          * This is the first square in lexicographic order which
2955          * contains part of this region. Therefore, one of the top
2956          * two corners of the square must be what we're after. The
2957          * only case in which it isn't the top left one is if the
2958          * square is diagonally divided and the region is in the
2959          * bottom right half.
2960          */
2961         if (state->map->map[wh*TE+y*w+x] != r &&
2962             state->map->map[wh*LE+y*w+x] != r)
2963             x++;                       /* could just as well have done y++ */
2964
2965         /*
2966          * Now we have a point on the region boundary. Trace around
2967          * the region until we come back to this point,
2968          * accumulating coordinates for a polygon draw operation as
2969          * we go.
2970          */
2971         lastdir = -1;
2972         ox = x;
2973         oy = y;
2974         ncoords = 0;
2975
2976         do {
2977             /*
2978              * There are eight possible directions we could head in
2979              * from here. We identify them by octant numbers, and
2980              * we also use octant numbers to identify the spaces
2981              * between them:
2982              * 
2983              *   6   7   0
2984              *    \ 7|0 /
2985              *     \ | /
2986              *    6 \|/ 1
2987              * 5-----+-----1
2988              *    5 /|\ 2
2989              *     / | \
2990              *    / 4|3 \
2991              *   4   3   2
2992              */
2993             octants[0] = x<w && y>0 ? state->map->map[wh*LE+(y-1)*w+x] : -1;
2994             octants[1] = x<w && y>0 ? state->map->map[wh*BE+(y-1)*w+x] : -1;
2995             octants[2] = x<w && y<h ? state->map->map[wh*TE+y*w+x] : -1;
2996             octants[3] = x<w && y<h ? state->map->map[wh*LE+y*w+x] : -1;
2997             octants[4] = x>0 && y<h ? state->map->map[wh*RE+y*w+(x-1)] : -1;
2998             octants[5] = x>0 && y<h ? state->map->map[wh*TE+y*w+(x-1)] : -1;
2999             octants[6] = x>0 && y>0 ? state->map->map[wh*BE+(y-1)*w+(x-1)] :-1;
3000             octants[7] = x>0 && y>0 ? state->map->map[wh*RE+(y-1)*w+(x-1)] :-1;
3001
3002             d1 = d2 = -1;
3003             for (i = 0; i < 8; i++)
3004                 if ((octants[i] == r) ^ (octants[(i+1)%8] == r)) {
3005                     assert(d2 == -1);
3006                     if (d1 == -1)
3007                         d1 = i;
3008                     else
3009                         d2 = i;
3010                 }
3011
3012             assert(d1 != -1 && d2 != -1);
3013             if (d1 == lastdir)
3014                 d1 = d2;
3015
3016             /*
3017              * Now we're heading in direction d1. Save the current
3018              * coordinates.
3019              */
3020             if (ncoords + 2 > coordsize) {
3021                 coordsize += 128;
3022                 coords = sresize(coords, coordsize, int);
3023             }
3024             coords[ncoords++] = COORD(x);
3025             coords[ncoords++] = COORD(y);
3026
3027             /*
3028              * Compute the new coordinates.
3029              */
3030             x += (d1 % 4 == 3 ? 0 : d1 < 4 ? +1 : -1);
3031             y += (d1 % 4 == 1 ? 0 : d1 > 1 && d1 < 5 ? +1 : -1);
3032             assert(x >= 0 && x <= w && y >= 0 && y <= h);
3033
3034             lastdir = d1 ^ 4;
3035         } while (x != ox || y != oy);
3036
3037         draw_polygon(dr, coords, ncoords/2,
3038                      state->colouring[r] >= 0 ?
3039                      c[state->colouring[r]] : -1, ink);
3040     }
3041     sfree(coords);
3042 }
3043
3044 #ifdef COMBINED
3045 #define thegame map
3046 #endif
3047
3048 const struct game thegame = {
3049     "Map", "games.map",
3050     default_params,
3051     game_fetch_preset,
3052     decode_params,
3053     encode_params,
3054     free_params,
3055     dup_params,
3056     TRUE, game_configure, custom_params,
3057     validate_params,
3058     new_game_desc,
3059     validate_desc,
3060     new_game,
3061     dup_game,
3062     free_game,
3063     TRUE, solve_game,
3064     FALSE, game_text_format,
3065     new_ui,
3066     free_ui,
3067     encode_ui,
3068     decode_ui,
3069     game_changed_state,
3070     interpret_move,
3071     execute_move,
3072     20, game_compute_size, game_set_size,
3073     game_colours,
3074     game_new_drawstate,
3075     game_free_drawstate,
3076     game_redraw,
3077     game_anim_length,
3078     game_flash_length,
3079     TRUE, TRUE, game_print_size, game_print,
3080     game_wants_statusbar,
3081     FALSE, game_timing_state,
3082     0,                                 /* mouse_priorities */
3083 };
3084
3085 #ifdef STANDALONE_SOLVER
3086
3087 #include <stdarg.h>
3088
3089 void frontend_default_colour(frontend *fe, float *output) {}
3090 void draw_text(drawing *dr, int x, int y, int fonttype, int fontsize,
3091                int align, int colour, char *text) {}
3092 void draw_rect(drawing *dr, int x, int y, int w, int h, int colour) {}
3093 void draw_line(drawing *dr, int x1, int y1, int x2, int y2, int colour) {}
3094 void draw_polygon(drawing *dr, int *coords, int npoints,
3095                   int fillcolour, int outlinecolour) {}
3096 void draw_circle(drawing *dr, int cx, int cy, int radius,
3097                  int fillcolour, int outlinecolour) {}
3098 void clip(drawing *dr, int x, int y, int w, int h) {}
3099 void unclip(drawing *dr) {}
3100 void start_draw(drawing *dr) {}
3101 void draw_update(drawing *dr, int x, int y, int w, int h) {}
3102 void end_draw(drawing *dr) {}
3103 blitter *blitter_new(drawing *dr, int w, int h) {return NULL;}
3104 void blitter_free(drawing *dr, blitter *bl) {}
3105 void blitter_save(drawing *dr, blitter *bl, int x, int y) {}
3106 void blitter_load(drawing *dr, blitter *bl, int x, int y) {}
3107 int print_mono_colour(drawing *dr, int grey) { return 0; }
3108 int print_rgb_colour(drawing *dr, int hatch, float r, float g, float b)
3109 { return 0; }
3110 void print_line_width(drawing *dr, int width) {}
3111
3112 void fatal(char *fmt, ...)
3113 {
3114     va_list ap;
3115
3116     fprintf(stderr, "fatal error: ");
3117
3118     va_start(ap, fmt);
3119     vfprintf(stderr, fmt, ap);
3120     va_end(ap);
3121
3122     fprintf(stderr, "\n");
3123     exit(1);
3124 }
3125
3126 int main(int argc, char **argv)
3127 {
3128     game_params *p;
3129     game_state *s;
3130     char *id = NULL, *desc, *err;
3131     int grade = FALSE;
3132     int ret, diff, really_verbose = FALSE;
3133     struct solver_scratch *sc;
3134     int i;
3135
3136     while (--argc > 0) {
3137         char *p = *++argv;
3138         if (!strcmp(p, "-v")) {
3139             really_verbose = TRUE;
3140         } else if (!strcmp(p, "-g")) {
3141             grade = TRUE;
3142         } else if (*p == '-') {
3143             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
3144             return 1;
3145         } else {
3146             id = p;
3147         }
3148     }
3149
3150     if (!id) {
3151         fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
3152         return 1;
3153     }
3154
3155     desc = strchr(id, ':');
3156     if (!desc) {
3157         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
3158         return 1;
3159     }
3160     *desc++ = '\0';
3161
3162     p = default_params();
3163     decode_params(p, id);
3164     err = validate_desc(p, desc);
3165     if (err) {
3166         fprintf(stderr, "%s: %s\n", argv[0], err);
3167         return 1;
3168     }
3169     s = new_game(NULL, p, desc);
3170
3171     sc = new_scratch(s->map->graph, s->map->n, s->map->ngraph);
3172
3173     /*
3174      * When solving an Easy puzzle, we don't want to bother the
3175      * user with Hard-level deductions. For this reason, we grade
3176      * the puzzle internally before doing anything else.
3177      */
3178     ret = -1;                          /* placate optimiser */
3179     for (diff = 0; diff < DIFFCOUNT; diff++) {
3180         for (i = 0; i < s->map->n; i++)
3181             if (!s->map->immutable[i])
3182                 s->colouring[i] = -1;
3183         ret = map_solver(sc, s->map->graph, s->map->n, s->map->ngraph,
3184                          s->colouring, diff);
3185         if (ret < 2)
3186             break;
3187     }
3188
3189     if (diff == DIFFCOUNT) {
3190         if (grade)
3191             printf("Difficulty rating: harder than Hard, or ambiguous\n");
3192         else
3193             printf("Unable to find a unique solution\n");
3194     } else {
3195         if (grade) {
3196             if (ret == 0)
3197                 printf("Difficulty rating: impossible (no solution exists)\n");
3198             else if (ret == 1)
3199                 printf("Difficulty rating: %s\n", map_diffnames[diff]);
3200         } else {
3201             verbose = really_verbose;
3202             for (i = 0; i < s->map->n; i++)
3203                 if (!s->map->immutable[i])
3204                     s->colouring[i] = -1;
3205             ret = map_solver(sc, s->map->graph, s->map->n, s->map->ngraph,
3206                              s->colouring, diff);
3207             if (ret == 0)
3208                 printf("Puzzle is inconsistent\n");
3209             else {
3210                 int col = 0;
3211
3212                 for (i = 0; i < s->map->n; i++) {
3213                     printf("%5d <- %c%c", i, colnames[s->colouring[i]],
3214                            (col < 6 && i+1 < s->map->n ? ' ' : '\n'));
3215                     if (++col == 7)
3216                         col = 0;
3217                 }
3218             }
3219         }
3220     }
3221
3222     return 0;
3223 }
3224
3225 #endif