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