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