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