2 * map.c: Game involving four-colouring a map.
9 * - more solver brains?
10 * - better four-colouring algorithm?
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 :-)
29 #define THREE (FOUR-1)
34 * Ghastly run-time configuration option, just for Gareth (again).
36 static int flash_type = -1;
37 static float flash_length;
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.
46 A(RECURSE,Unreasonable,u)
47 #define ENUM(upper,title,lower) DIFF_ ## upper,
48 #define TITLE(upper,title,lower) #title,
49 #define ENCODE(upper,title,lower) #lower
50 #define CONFIG(upper,title,lower) ":" #title
51 enum { DIFFLIST(ENUM) DIFFCOUNT };
52 static char const *const map_diffnames[] = { DIFFLIST(TITLE) };
53 static char const map_diffchars[] = DIFFLIST(ENCODE);
54 #define DIFFCONFIG DIFFLIST(CONFIG)
56 enum { TE, BE, LE, RE }; /* top/bottom/left/right edges */
61 COL_0, COL_1, COL_2, COL_3,
62 COL_ERROR, COL_ERRTEXT,
77 int *edgex, *edgey; /* positions of a point on each edge */
84 int completed, cheated;
87 static game_params *default_params(void)
89 game_params *ret = snew(game_params);
94 ret->diff = DIFF_NORMAL;
99 static const struct game_params map_presets[] = {
100 {20, 15, 30, DIFF_EASY},
101 {20, 15, 30, DIFF_NORMAL},
102 {30, 25, 75, DIFF_NORMAL},
105 static int game_fetch_preset(int i, char **name, game_params **params)
110 if (i < 0 || i >= lenof(map_presets))
113 ret = snew(game_params);
114 *ret = map_presets[i];
116 sprintf(str, "%dx%d, %d regions, %s", ret->w, ret->h, ret->n,
117 map_diffnames[ret->diff]);
124 static void free_params(game_params *params)
129 static game_params *dup_params(game_params *params)
131 game_params *ret = snew(game_params);
132 *ret = *params; /* structure copy */
136 static void decode_params(game_params *params, char const *string)
138 char const *p = string;
141 while (*p && isdigit((unsigned char)*p)) p++;
145 while (*p && isdigit((unsigned char)*p)) p++;
147 params->h = params->w;
152 while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
154 params->n = params->w * params->h / 8;
159 for (i = 0; i < DIFFCOUNT; i++)
160 if (*p == map_diffchars[i])
166 static char *encode_params(game_params *params, int full)
170 sprintf(ret, "%dx%dn%d", params->w, params->h, params->n);
172 sprintf(ret + strlen(ret), "d%c", map_diffchars[params->diff]);
177 static config_item *game_configure(game_params *params)
182 ret = snewn(5, config_item);
184 ret[0].name = "Width";
185 ret[0].type = C_STRING;
186 sprintf(buf, "%d", params->w);
187 ret[0].sval = dupstr(buf);
190 ret[1].name = "Height";
191 ret[1].type = C_STRING;
192 sprintf(buf, "%d", params->h);
193 ret[1].sval = dupstr(buf);
196 ret[2].name = "Regions";
197 ret[2].type = C_STRING;
198 sprintf(buf, "%d", params->n);
199 ret[2].sval = dupstr(buf);
202 ret[3].name = "Difficulty";
203 ret[3].type = C_CHOICES;
204 ret[3].sval = DIFFCONFIG;
205 ret[3].ival = params->diff;
215 static game_params *custom_params(config_item *cfg)
217 game_params *ret = snew(game_params);
219 ret->w = atoi(cfg[0].sval);
220 ret->h = atoi(cfg[1].sval);
221 ret->n = atoi(cfg[2].sval);
222 ret->diff = cfg[3].ival;
227 static char *validate_params(game_params *params, int full)
229 if (params->w < 2 || params->h < 2)
230 return "Width and height must be at least two";
232 return "Must have at least five regions";
233 if (params->n > params->w * params->h)
234 return "Too many regions to fit in grid";
238 /* ----------------------------------------------------------------------
239 * Cumulative frequency table functions.
243 * Initialise a cumulative frequency table. (Hardly worth writing
244 * this function; all it does is to initialise everything in the
247 static void cf_init(int *table, int n)
251 for (i = 0; i < n; i++)
256 * Increment the count of symbol `sym' by `count'.
258 static void cf_add(int *table, int n, int sym, int count)
275 * Cumulative frequency lookup: return the total count of symbols
276 * with value less than `sym'.
278 static int cf_clookup(int *table, int n, int sym)
280 int bit, index, limit, count;
285 assert(0 < sym && sym <= n);
287 count = table[0]; /* start with the whole table size */
297 * Find the least number with its lowest set bit in this
298 * position which is greater than or equal to sym.
300 index = ((sym + bit - 1) &~ (bit * 2 - 1)) + bit;
303 count -= table[index];
314 * Single frequency lookup: return the count of symbol `sym'.
316 static int cf_slookup(int *table, int n, int sym)
320 assert(0 <= sym && sym < n);
324 for (bit = 1; sym+bit < n && !(sym & bit); bit <<= 1)
325 count -= table[sym+bit];
331 * Return the largest symbol index such that the cumulative
332 * frequency up to that symbol is less than _or equal to_ count.
334 static int cf_whichsym(int *table, int n, int count) {
337 assert(count >= 0 && count < table[0]);
348 if (count >= top - table[sym+bit])
351 top -= table[sym+bit];
360 /* ----------------------------------------------------------------------
363 * FIXME: this isn't entirely optimal at present, because it
364 * inherently prioritises growing the largest region since there
365 * are more squares adjacent to it. This acts as a destabilising
366 * influence leading to a few large regions and mostly small ones.
367 * It might be better to do it some other way.
370 #define WEIGHT_INCREASED 2 /* for increased perimeter */
371 #define WEIGHT_DECREASED 4 /* for decreased perimeter */
372 #define WEIGHT_UNCHANGED 3 /* for unchanged perimeter */
375 * Look at a square and decide which colours can be extended into
378 * If called with index < 0, it adds together one of
379 * WEIGHT_INCREASED, WEIGHT_DECREASED or WEIGHT_UNCHANGED for each
380 * colour that has a valid extension (according to the effect that
381 * it would have on the perimeter of the region being extended) and
382 * returns the overall total.
384 * If called with index >= 0, it returns one of the possible
385 * colours depending on the value of index, in such a way that the
386 * number of possible inputs which would give rise to a given
387 * return value correspond to the weight of that value.
389 static int extend_options(int w, int h, int n, int *map,
390 int x, int y, int index)
396 if (map[y*w+x] >= 0) {
398 return 0; /* can't do this square at all */
402 * Fetch the eight neighbours of this square, in order around
405 for (dy = -1; dy <= +1; dy++)
406 for (dx = -1; dx <= +1; dx++) {
407 int index = (dy < 0 ? 6-dx : dy > 0 ? 2+dx : 2*(1+dx));
408 if (x+dx >= 0 && x+dx < w && y+dy >= 0 && y+dy < h)
409 col[index] = map[(y+dy)*w+(x+dx)];
415 * Iterate over each colour that might be feasible.
417 * FIXME: this routine currently has O(n) running time. We
418 * could turn it into O(FOUR) by only bothering to iterate over
419 * the colours mentioned in the four neighbouring squares.
422 for (c = 0; c < n; c++) {
423 int count, neighbours, runs;
426 * One of the even indices of col (representing the
427 * orthogonal neighbours of this square) must be equal to
428 * c, or else this square is not adjacent to region c and
429 * obviously cannot become an extension of it at this time.
432 for (i = 0; i < 8; i += 2)
439 * Now we know this square is adjacent to region c. The
440 * next question is, would extending it cause the region to
441 * become non-simply-connected? If so, we mustn't do it.
443 * We determine this by looking around col to see if we can
444 * find more than one separate run of colour c.
447 for (i = 0; i < 8; i++)
448 if (col[i] == c && col[(i+1) & 7] != c)
456 * This square is a possibility. Determine its effect on
457 * the region's perimeter (computed from the number of
458 * orthogonal neighbours - 1 means a perimeter increase, 3
459 * a decrease, 2 no change; 4 is impossible because the
460 * region would already not be simply connected) and we're
463 assert(neighbours > 0 && neighbours < 4);
464 count = (neighbours == 1 ? WEIGHT_INCREASED :
465 neighbours == 2 ? WEIGHT_UNCHANGED : WEIGHT_DECREASED);
468 if (index >= 0 && index < count)
479 static void genmap(int w, int h, int n, int *map, random_state *rs)
486 tmp = snewn(wh, int);
489 * Clear the map, and set up `tmp' as a list of grid indices.
491 for (i = 0; i < wh; i++) {
497 * Place the region seeds by selecting n members from `tmp'.
500 for (i = 0; i < n; i++) {
501 int j = random_upto(rs, k);
507 * Re-initialise `tmp' as a cumulative frequency table. This
508 * will store the number of possible region colours we can
509 * extend into each square.
514 * Go through the grid and set up the initial cumulative
517 for (y = 0; y < h; y++)
518 for (x = 0; x < w; x++)
519 cf_add(tmp, wh, y*w+x,
520 extend_options(w, h, n, map, x, y, -1));
523 * Now repeatedly choose a square we can extend a region into,
527 int k = random_upto(rs, tmp[0]);
532 sq = cf_whichsym(tmp, wh, k);
533 k -= cf_clookup(tmp, wh, sq);
536 colour = extend_options(w, h, n, map, x, y, k);
541 * Re-scan the nine cells around the one we've just
544 for (yy = max(y-1, 0); yy < min(y+2, h); yy++)
545 for (xx = max(x-1, 0); xx < min(x+2, w); xx++) {
546 cf_add(tmp, wh, yy*w+xx,
547 -cf_slookup(tmp, wh, yy*w+xx) +
548 extend_options(w, h, n, map, xx, yy, -1));
553 * Finally, go through and normalise the region labels into
554 * order, meaning that indistinguishable maps are actually
557 for (i = 0; i < n; i++)
560 for (i = 0; i < wh; i++) {
564 map[i] = tmp[map[i]];
570 /* ----------------------------------------------------------------------
571 * Functions to handle graphs.
575 * Having got a map in a square grid, convert it into a graph
578 static int gengraph(int w, int h, int n, int *map, int *graph)
583 * Start by setting the graph up as an adjacency matrix. We'll
584 * turn it into a list later.
586 for (i = 0; i < n*n; i++)
590 * Iterate over the map looking for all adjacencies.
592 for (y = 0; y < h; y++)
593 for (x = 0; x < w; x++) {
596 if (x+1 < w && (vx = map[y*w+(x+1)]) != v)
597 graph[v*n+vx] = graph[vx*n+v] = 1;
598 if (y+1 < h && (vy = map[(y+1)*w+x]) != v)
599 graph[v*n+vy] = graph[vy*n+v] = 1;
603 * Turn the matrix into a list.
605 for (i = j = 0; i < n*n; i++)
612 static int graph_edge_index(int *graph, int n, int ngraph, int i, int j)
619 while (top - bot > 1) {
620 mid = (top + bot) / 2;
623 else if (graph[mid] < v)
631 #define graph_adjacent(graph, n, ngraph, i, j) \
632 (graph_edge_index((graph), (n), (ngraph), (i), (j)) >= 0)
634 static int graph_vertex_start(int *graph, int n, int ngraph, int i)
641 while (top - bot > 1) {
642 mid = (top + bot) / 2;
651 /* ----------------------------------------------------------------------
652 * Generate a four-colouring of a graph.
654 * FIXME: it would be nice if we could convert this recursion into
655 * pseudo-recursion using some sort of explicit stack array, for
656 * the sake of the Palm port and its limited stack.
659 static int fourcolour_recurse(int *graph, int n, int ngraph,
660 int *colouring, int *scratch, random_state *rs)
662 int nfree, nvert, start, i, j, k, c, ci;
666 * Find the smallest number of free colours in any uncoloured
667 * vertex, and count the number of such vertices.
670 nfree = FIVE; /* start off bigger than FOUR! */
672 for (i = 0; i < n; i++)
673 if (colouring[i] < 0 && scratch[i*FIVE+FOUR] <= nfree) {
674 if (nfree > scratch[i*FIVE+FOUR]) {
675 nfree = scratch[i*FIVE+FOUR];
682 * If there aren't any uncoloured vertices at all, we're done.
685 return TRUE; /* we've got a colouring! */
688 * Pick a random vertex in that set.
690 j = random_upto(rs, nvert);
691 for (i = 0; i < n; i++)
692 if (colouring[i] < 0 && scratch[i*FIVE+FOUR] == nfree)
696 start = graph_vertex_start(graph, n, ngraph, i);
699 * Loop over the possible colours for i, and recurse for each
703 for (c = 0; c < FOUR; c++)
704 if (scratch[i*FIVE+c] == 0)
706 shuffle(cs, ci, sizeof(*cs), rs);
712 * Fill in this colour.
717 * Update the scratch space to reflect a new neighbour
718 * of this colour for each neighbour of vertex i.
720 for (j = start; j < ngraph && graph[j] < n*(i+1); j++) {
722 if (scratch[k*FIVE+c] == 0)
723 scratch[k*FIVE+FOUR]--;
730 if (fourcolour_recurse(graph, n, ngraph, colouring, scratch, rs))
731 return TRUE; /* got one! */
734 * If that didn't work, clean up and try again with a
737 for (j = start; j < ngraph && graph[j] < n*(i+1); j++) {
740 if (scratch[k*FIVE+c] == 0)
741 scratch[k*FIVE+FOUR]++;
747 * If we reach here, we were unable to find a colouring at all.
748 * (This doesn't necessarily mean the Four Colour Theorem is
749 * violated; it might just mean we've gone down a dead end and
750 * need to back up and look somewhere else. It's only an FCT
751 * violation if we get all the way back up to the top level and
757 static void fourcolour(int *graph, int n, int ngraph, int *colouring,
764 * For each vertex and each colour, we store the number of
765 * neighbours that have that colour. Also, we store the number
766 * of free colours for the vertex.
768 scratch = snewn(n * FIVE, int);
769 for (i = 0; i < n * FIVE; i++)
770 scratch[i] = (i % FIVE == FOUR ? FOUR : 0);
773 * Clear the colouring to start with.
775 for (i = 0; i < n; i++)
778 i = fourcolour_recurse(graph, n, ngraph, colouring, scratch, rs);
779 assert(i); /* by the Four Colour Theorem :-) */
784 /* ----------------------------------------------------------------------
785 * Non-recursive solver.
788 struct solver_scratch {
789 unsigned char *possible; /* bitmap of colours for each region */
796 static struct solver_scratch *new_scratch(int *graph, int n, int ngraph)
798 struct solver_scratch *sc;
800 sc = snew(struct solver_scratch);
804 sc->possible = snewn(n, unsigned char);
810 static void free_scratch(struct solver_scratch *sc)
816 static int place_colour(struct solver_scratch *sc,
817 int *colouring, int index, int colour)
819 int *graph = sc->graph, n = sc->n, ngraph = sc->ngraph;
822 if (!(sc->possible[index] & (1 << colour)))
823 return FALSE; /* can't do it */
825 sc->possible[index] = 1 << colour;
826 colouring[index] = colour;
829 * Rule out this colour from all the region's neighbours.
831 for (j = graph_vertex_start(graph, n, ngraph, index);
832 j < ngraph && graph[j] < n*(index+1); j++) {
833 k = graph[j] - index*n;
834 sc->possible[k] &= ~(1 << colour);
841 * Returns 0 for impossible, 1 for success, 2 for failure to
842 * converge (i.e. puzzle is either ambiguous or just too
845 static int map_solver(struct solver_scratch *sc,
846 int *graph, int n, int ngraph, int *colouring,
852 * Initialise scratch space.
854 for (i = 0; i < n; i++)
855 sc->possible[i] = (1 << FOUR) - 1;
860 for (i = 0; i < n; i++)
861 if (colouring[i] >= 0) {
862 if (!place_colour(sc, colouring, i, colouring[i]))
863 return 0; /* the clues aren't even consistent! */
867 * Now repeatedly loop until we find nothing further to do.
870 int done_something = FALSE;
872 if (difficulty < DIFF_EASY)
873 break; /* can't do anything at all! */
876 * Simplest possible deduction: find a region with only one
879 for (i = 0; i < n; i++) if (colouring[i] < 0) {
880 int p = sc->possible[i];
883 return 0; /* puzzle is inconsistent */
885 if ((p & (p-1)) == 0) { /* p is a power of two */
887 for (c = 0; c < FOUR; c++)
891 if (!place_colour(sc, colouring, i, c))
892 return 0; /* found puzzle to be inconsistent */
893 done_something = TRUE;
900 if (difficulty < DIFF_NORMAL)
901 break; /* can't do anything harder */
904 * Failing that, go up one level. Look for pairs of regions
905 * which (a) both have the same pair of possible colours,
906 * (b) are adjacent to one another, (c) are adjacent to the
907 * same region, and (d) that region still thinks it has one
908 * or both of those possible colours.
910 * Simplest way to do this is by going through the graph
911 * edge by edge, so that we start with property (b) and
912 * then look for (a) and finally (c) and (d).
914 for (i = 0; i < ngraph; i++) {
915 int j1 = graph[i] / n, j2 = graph[i] % n;
919 continue; /* done it already, other way round */
921 if (colouring[j1] >= 0 || colouring[j2] >= 0)
922 continue; /* they're not undecided */
924 if (sc->possible[j1] != sc->possible[j2])
925 continue; /* they don't have the same possibles */
927 v = sc->possible[j1];
929 * See if v contains exactly two set bits.
931 v2 = v & -v; /* find lowest set bit */
932 v2 = v & ~v2; /* clear it */
933 if (v2 == 0 || (v2 & (v2-1)) != 0) /* not power of 2 */
937 * We've found regions j1 and j2 satisfying properties
938 * (a) and (b): they have two possible colours between
939 * them, and since they're adjacent to one another they
940 * must use _both_ those colours between them.
941 * Therefore, if they are both adjacent to any other
942 * region then that region cannot be either colour.
944 * Go through the neighbours of j1 and see if any are
947 for (j = graph_vertex_start(graph, n, ngraph, j1);
948 j < ngraph && graph[j] < n*(j1+1); j++) {
950 if (graph_adjacent(graph, n, ngraph, k, j2) &&
951 (sc->possible[k] & v)) {
952 sc->possible[k] &= ~v;
953 done_something = TRUE;
963 * See if we've got a complete solution, and return if so.
965 for (i = 0; i < n; i++)
966 if (colouring[i] < 0)
969 return 1; /* success! */
972 * If recursion is not permissible, we now give up.
974 if (difficulty < DIFF_RECURSE)
975 return 2; /* unable to complete */
978 * Now we've got to do something recursive. So first hunt for a
979 * currently-most-constrained region.
983 struct solver_scratch *rsc;
984 int *subcolouring, *origcolouring;
986 int we_already_got_one;
991 for (i = 0; i < n; i++) if (colouring[i] < 0) {
992 int p = sc->possible[i];
993 enum { compile_time_assertion = 1 / (FOUR <= 4) };
996 /* Count the set bits. */
997 c = (p & 5) + ((p >> 1) & 5);
998 c = (c & 3) + ((c >> 2) & 3);
999 assert(c > 1); /* or colouring[i] would be >= 0 */
1007 assert(best >= 0); /* or we'd be solved already */
1010 * Now iterate over the possible colours for this region.
1012 rsc = new_scratch(graph, n, ngraph);
1013 rsc->depth = sc->depth + 1;
1014 origcolouring = snewn(n, int);
1015 memcpy(origcolouring, colouring, n * sizeof(int));
1016 subcolouring = snewn(n, int);
1017 we_already_got_one = FALSE;
1020 for (i = 0; i < FOUR; i++) {
1021 if (!(sc->possible[best] & (1 << i)))
1024 memcpy(subcolouring, origcolouring, n * sizeof(int));
1025 subcolouring[best] = i;
1026 subret = map_solver(rsc, graph, n, ngraph,
1027 subcolouring, difficulty);
1030 * If this possibility turned up more than one valid
1031 * solution, or if it turned up one and we already had
1032 * one, we're definitely ambiguous.
1034 if (subret == 2 || (subret == 1 && we_already_got_one)) {
1040 * If this possibility turned up one valid solution and
1041 * it's the first we've seen, copy it into the output.
1044 memcpy(colouring, subcolouring, n * sizeof(int));
1045 we_already_got_one = TRUE;
1050 * Otherwise, this guess led to a contradiction, so we
1055 sfree(subcolouring);
1062 /* ----------------------------------------------------------------------
1063 * Game generation main function.
1066 static char *new_game_desc(game_params *params, random_state *rs,
1067 char **aux, int interactive)
1069 struct solver_scratch *sc = NULL;
1070 int *map, *graph, ngraph, *colouring, *colouring2, *regions;
1071 int i, j, w, h, n, solveret, cfreq[FOUR];
1074 #ifdef GENERATION_DIAGNOSTICS
1078 int retlen, retsize;
1087 map = snewn(wh, int);
1088 graph = snewn(n*n, int);
1089 colouring = snewn(n, int);
1090 colouring2 = snewn(n, int);
1091 regions = snewn(n, int);
1094 * This is the minimum difficulty below which we'll completely
1095 * reject a map design. Normally we set this to one below the
1096 * requested difficulty, ensuring that we have the right
1097 * result. However, for particularly dense maps or maps with
1098 * particularly few regions it might not be possible to get the
1099 * desired difficulty, so we will eventually drop this down to
1100 * -1 to indicate that any old map will do.
1102 mindiff = params->diff;
1110 genmap(w, h, n, map, rs);
1112 #ifdef GENERATION_DIAGNOSTICS
1113 for (y = 0; y < h; y++) {
1114 for (x = 0; x < w; x++) {
1119 putchar('a' + v-36);
1121 putchar('A' + v-10);
1130 * Convert the map into a graph.
1132 ngraph = gengraph(w, h, n, map, graph);
1134 #ifdef GENERATION_DIAGNOSTICS
1135 for (i = 0; i < ngraph; i++)
1136 printf("%d-%d\n", graph[i]/n, graph[i]%n);
1142 fourcolour(graph, n, ngraph, colouring, rs);
1144 #ifdef GENERATION_DIAGNOSTICS
1145 for (i = 0; i < n; i++)
1146 printf("%d: %d\n", i, colouring[i]);
1148 for (y = 0; y < h; y++) {
1149 for (x = 0; x < w; x++) {
1150 int v = colouring[map[y*w+x]];
1152 putchar('a' + v-36);
1154 putchar('A' + v-10);
1163 * Encode the solution as an aux string.
1165 if (*aux) /* in case we've come round again */
1167 retlen = retsize = 0;
1169 for (i = 0; i < n; i++) {
1172 if (colouring[i] < 0)
1175 len = sprintf(buf, "%s%d:%d", i ? ";" : "S;", colouring[i], i);
1176 if (retlen + len >= retsize) {
1177 retsize = retlen + len + 256;
1178 ret = sresize(ret, retsize, char);
1180 strcpy(ret + retlen, buf);
1186 * Remove the region colours one by one, keeping
1187 * solubility. Also ensure that there always remains at
1188 * least one region of every colour, so that the user can
1189 * drag from somewhere.
1191 for (i = 0; i < FOUR; i++)
1193 for (i = 0; i < n; i++) {
1195 cfreq[colouring[i]]++;
1197 for (i = 0; i < FOUR; i++)
1201 shuffle(regions, n, sizeof(*regions), rs);
1203 if (sc) free_scratch(sc);
1204 sc = new_scratch(graph, n, ngraph);
1206 for (i = 0; i < n; i++) {
1209 if (cfreq[colouring[j]] == 1)
1210 continue; /* can't remove last region of colour */
1212 memcpy(colouring2, colouring, n*sizeof(int));
1214 solveret = map_solver(sc, graph, n, ngraph, colouring2,
1216 assert(solveret >= 0); /* mustn't be impossible! */
1217 if (solveret == 1) {
1218 cfreq[colouring[j]]--;
1223 #ifdef GENERATION_DIAGNOSTICS
1224 for (i = 0; i < n; i++)
1225 if (colouring[i] >= 0) {
1229 putchar('a' + i-36);
1231 putchar('A' + i-10);
1234 printf(": %d\n", colouring[i]);
1239 * Finally, check that the puzzle is _at least_ as hard as
1240 * required, and indeed that it isn't already solved.
1241 * (Calling map_solver with negative difficulty ensures the
1242 * latter - if a solver which _does nothing_ can't solve
1243 * it, it's too easy!)
1245 memcpy(colouring2, colouring, n*sizeof(int));
1246 if (map_solver(sc, graph, n, ngraph, colouring2,
1247 mindiff - 1) == 1) {
1249 * Drop minimum difficulty if necessary.
1251 if (mindiff > 0 && (n < 9 || n > 3*wh/2)) {
1253 mindiff = 0; /* give up and go for Easy */
1262 * Encode as a game ID. We do this by:
1264 * - first going along the horizontal edges row by row, and
1265 * then the vertical edges column by column
1266 * - encoding the lengths of runs of edges and runs of
1268 * - the decoder will reconstitute the region boundaries from
1269 * this and automatically number them the same way we did
1270 * - then we encode the initial region colours in a Slant-like
1271 * fashion (digits 0-3 interspersed with letters giving
1272 * lengths of runs of empty spaces).
1274 retlen = retsize = 0;
1281 * Start with a notional non-edge, so that there'll be an
1282 * explicit `a' to distinguish the case where we start with
1288 for (i = 0; i < w*(h-1) + (w-1)*h; i++) {
1289 int x, y, dx, dy, v;
1292 /* Horizontal edge. */
1298 /* Vertical edge. */
1299 x = (i - w*(h-1)) / h;
1300 y = (i - w*(h-1)) % h;
1305 if (retlen + 10 >= retsize) {
1306 retsize = retlen + 256;
1307 ret = sresize(ret, retsize, char);
1310 v = (map[y*w+x] != map[(y+dy)*w+(x+dx)]);
1313 ret[retlen++] = 'a'-1 + run;
1318 * 'z' is a special case in this encoding. Rather
1319 * than meaning a run of 26 and a state switch, it
1320 * means a run of 25 and _no_ state switch, because
1321 * otherwise there'd be no way to encode runs of
1325 ret[retlen++] = 'z';
1332 ret[retlen++] = 'a'-1 + run;
1333 ret[retlen++] = ',';
1336 for (i = 0; i < n; i++) {
1337 if (retlen + 10 >= retsize) {
1338 retsize = retlen + 256;
1339 ret = sresize(ret, retsize, char);
1342 if (colouring[i] < 0) {
1344 * In _this_ encoding, 'z' is a run of 26, since
1345 * there's no implicit state switch after each run.
1346 * Confusingly different, but more compact.
1349 ret[retlen++] = 'z';
1355 ret[retlen++] = 'a'-1 + run;
1356 ret[retlen++] = '0' + colouring[i];
1361 ret[retlen++] = 'a'-1 + run;
1364 assert(retlen < retsize);
1377 static char *parse_edge_list(game_params *params, char **desc, int *map)
1379 int w = params->w, h = params->h, wh = w*h, n = params->n;
1380 int i, k, pos, state;
1383 for (i = 0; i < wh; i++)
1390 * Parse the game description to get the list of edges, and
1391 * build up a disjoint set forest as we go (by identifying
1392 * pairs of squares whenever the edge list shows a non-edge).
1394 while (*p && *p != ',') {
1395 if (*p < 'a' || *p > 'z')
1396 return "Unexpected character in edge list";
1407 } else if (pos < w*(h-1)) {
1408 /* Horizontal edge. */
1413 } else if (pos < 2*wh-w-h) {
1414 /* Vertical edge. */
1415 x = (pos - w*(h-1)) / h;
1416 y = (pos - w*(h-1)) % h;
1420 return "Too much data in edge list";
1422 dsf_merge(map+wh, y*w+x, (y+dy)*w+(x+dx));
1430 assert(pos <= 2*wh-w-h);
1432 return "Too little data in edge list";
1435 * Now go through again and allocate region numbers.
1438 for (i = 0; i < wh; i++)
1440 for (i = 0; i < wh; i++) {
1441 k = dsf_canonify(map+wh, i);
1447 return "Edge list defines the wrong number of regions";
1454 static char *validate_desc(game_params *params, char *desc)
1456 int w = params->w, h = params->h, wh = w*h, n = params->n;
1461 map = snewn(2*wh, int);
1462 ret = parse_edge_list(params, &desc, map);
1468 return "Expected comma before clue list";
1469 desc++; /* eat comma */
1473 if (*desc >= '0' && *desc < '0'+FOUR)
1475 else if (*desc >= 'a' && *desc <= 'z')
1476 area += *desc - 'a' + 1;
1478 return "Unexpected character in clue list";
1482 return "Too little data in clue list";
1484 return "Too much data in clue list";
1489 static game_state *new_game(midend *me, game_params *params, char *desc)
1491 int w = params->w, h = params->h, wh = w*h, n = params->n;
1494 game_state *state = snew(game_state);
1497 state->colouring = snewn(n, int);
1498 for (i = 0; i < n; i++)
1499 state->colouring[i] = -1;
1501 state->completed = state->cheated = FALSE;
1503 state->map = snew(struct map);
1504 state->map->refcount = 1;
1505 state->map->map = snewn(wh*4, int);
1506 state->map->graph = snewn(n*n, int);
1508 state->map->immutable = snewn(n, int);
1509 for (i = 0; i < n; i++)
1510 state->map->immutable[i] = FALSE;
1516 ret = parse_edge_list(params, &p, state->map->map);
1521 * Set up the other three quadrants in `map'.
1523 for (i = wh; i < 4*wh; i++)
1524 state->map->map[i] = state->map->map[i % wh];
1530 * Now process the clue list.
1534 if (*p >= '0' && *p < '0'+FOUR) {
1535 state->colouring[pos] = *p - '0';
1536 state->map->immutable[pos] = TRUE;
1539 assert(*p >= 'a' && *p <= 'z');
1540 pos += *p - 'a' + 1;
1546 state->map->ngraph = gengraph(w, h, n, state->map->map, state->map->graph);
1549 * Attempt to smooth out some of the more jagged region
1550 * outlines by the judicious use of diagonally divided squares.
1553 random_state *rs = random_init(desc, strlen(desc));
1554 int *squares = snewn(wh, int);
1557 for (i = 0; i < wh; i++)
1559 shuffle(squares, wh, sizeof(*squares), rs);
1562 done_something = FALSE;
1563 for (i = 0; i < wh; i++) {
1564 int y = squares[i] / w, x = squares[i] % w;
1565 int c = state->map->map[y*w+x];
1568 if (x == 0 || x == w-1 || y == 0 || y == h-1)
1571 if (state->map->map[TE * wh + y*w+x] !=
1572 state->map->map[BE * wh + y*w+x])
1575 tc = state->map->map[BE * wh + (y-1)*w+x];
1576 bc = state->map->map[TE * wh + (y+1)*w+x];
1577 lc = state->map->map[RE * wh + y*w+(x-1)];
1578 rc = state->map->map[LE * wh + y*w+(x+1)];
1581 * If this square is adjacent on two sides to one
1582 * region and on the other two sides to the other
1583 * region, and is itself one of the two regions, we can
1584 * adjust it so that it's a diagonal.
1586 if (tc != bc && (tc == c || bc == c)) {
1587 if ((lc == tc && rc == bc) ||
1588 (lc == bc && rc == tc)) {
1589 state->map->map[TE * wh + y*w+x] = tc;
1590 state->map->map[BE * wh + y*w+x] = bc;
1591 state->map->map[LE * wh + y*w+x] = lc;
1592 state->map->map[RE * wh + y*w+x] = rc;
1593 done_something = TRUE;
1597 } while (done_something);
1603 * Analyse the map to find a canonical line segment
1604 * corresponding to each edge. These are where we'll eventually
1605 * put error markers.
1608 int *bestx, *besty, *an, pass;
1609 float *ax, *ay, *best;
1611 ax = snewn(state->map->ngraph, float);
1612 ay = snewn(state->map->ngraph, float);
1613 an = snewn(state->map->ngraph, int);
1614 bestx = snewn(state->map->ngraph, int);
1615 besty = snewn(state->map->ngraph, int);
1616 best = snewn(state->map->ngraph, float);
1618 for (i = 0; i < state->map->ngraph; i++) {
1619 bestx[i] = besty[i] = -1;
1620 best[i] = 2*(w+h)+1;
1621 ax[i] = ay[i] = 0.0F;
1626 * We make two passes over the map, finding all the line
1627 * segments separating regions. In the first pass, we
1628 * compute the _average_ x and y coordinate of all the line
1629 * segments separating each pair of regions; in the second
1630 * pass, for each such average point, we find the line
1631 * segment closest to it and call that canonical.
1633 * Line segments are considered to have coordinates in
1634 * their centre. Thus, at least one coordinate for any line
1635 * segment is always something-and-a-half; so we store our
1636 * coordinates as twice their normal value.
1638 for (pass = 0; pass < 2; pass++) {
1641 for (y = 0; y < h; y++)
1642 for (x = 0; x < w; x++) {
1643 int ex[3], ey[3], ea[3], eb[3], en = 0;
1646 * Look for an edge to the right of this
1647 * square, an edge below it, and an edge in the
1652 ea[en] = state->map->map[RE * wh + y*w+x];
1653 eb[en] = state->map->map[LE * wh + y*w+(x+1)];
1654 if (ea[en] != eb[en]) {
1662 ea[en] = state->map->map[BE * wh + y*w+x];
1663 eb[en] = state->map->map[TE * wh + (y+1)*w+x];
1664 if (ea[en] != eb[en]) {
1671 ea[en] = state->map->map[TE * wh + y*w+x];
1672 eb[en] = state->map->map[BE * wh + y*w+x];
1673 if (ea[en] != eb[en]) {
1680 * Now process the edges we've found, one by
1683 for (i = 0; i < en; i++) {
1684 int emin = min(ea[i], eb[i]);
1685 int emax = max(ea[i], eb[i]);
1687 graph_edge_index(state->map->graph, n,
1688 state->map->ngraph, emin, emax);
1690 assert(gindex >= 0);
1694 * In pass 0, accumulate the values
1695 * we'll use to compute the average
1698 ax[gindex] += ex[i];
1699 ay[gindex] += ey[i];
1703 * In pass 1, work out whether this
1704 * point is closer to the average than
1705 * the last one we've seen.
1709 assert(an[gindex] > 0);
1710 dx = ex[i] - ax[gindex];
1711 dy = ey[i] - ay[gindex];
1712 d = sqrt(dx*dx + dy*dy);
1713 if (d < best[gindex]) {
1715 bestx[gindex] = ex[i];
1716 besty[gindex] = ey[i];
1723 for (i = 0; i < state->map->ngraph; i++)
1731 state->map->edgex = bestx;
1732 state->map->edgey = besty;
1734 for (i = 0; i < state->map->ngraph; i++)
1735 if (state->map->edgex[i] < 0) {
1736 /* Find the other representation of this edge. */
1737 int e = state->map->graph[i];
1738 int iprime = graph_edge_index(state->map->graph, n,
1739 state->map->ngraph, e%n, e/n);
1740 assert(state->map->edgex[iprime] >= 0);
1741 state->map->edgex[i] = state->map->edgex[iprime];
1742 state->map->edgey[i] = state->map->edgey[iprime];
1754 static game_state *dup_game(game_state *state)
1756 game_state *ret = snew(game_state);
1759 ret->colouring = snewn(state->p.n, int);
1760 memcpy(ret->colouring, state->colouring, state->p.n * sizeof(int));
1761 ret->map = state->map;
1762 ret->map->refcount++;
1763 ret->completed = state->completed;
1764 ret->cheated = state->cheated;
1769 static void free_game(game_state *state)
1771 if (--state->map->refcount <= 0) {
1772 sfree(state->map->map);
1773 sfree(state->map->graph);
1774 sfree(state->map->immutable);
1775 sfree(state->map->edgex);
1776 sfree(state->map->edgey);
1779 sfree(state->colouring);
1783 static char *solve_game(game_state *state, game_state *currstate,
1784 char *aux, char **error)
1791 struct solver_scratch *sc;
1795 int retlen, retsize;
1797 colouring = snewn(state->map->n, int);
1798 memcpy(colouring, state->colouring, state->map->n * sizeof(int));
1800 sc = new_scratch(state->map->graph, state->map->n, state->map->ngraph);
1801 sret = map_solver(sc, state->map->graph, state->map->n,
1802 state->map->ngraph, colouring, DIFFCOUNT-1);
1808 *error = "Puzzle is inconsistent";
1810 *error = "Unable to find a unique solution for this puzzle";
1815 ret = snewn(retsize, char);
1819 for (i = 0; i < state->map->n; i++) {
1822 assert(colouring[i] >= 0);
1823 if (colouring[i] == currstate->colouring[i])
1825 assert(!state->map->immutable[i]);
1827 len = sprintf(buf, ";%d:%d", colouring[i], i);
1828 if (retlen + len >= retsize) {
1829 retsize = retlen + len + 256;
1830 ret = sresize(ret, retsize, char);
1832 strcpy(ret + retlen, buf);
1843 static char *game_text_format(game_state *state)
1849 int drag_colour; /* -1 means no drag active */
1853 static game_ui *new_ui(game_state *state)
1855 game_ui *ui = snew(game_ui);
1856 ui->dragx = ui->dragy = -1;
1857 ui->drag_colour = -2;
1861 static void free_ui(game_ui *ui)
1866 static char *encode_ui(game_ui *ui)
1871 static void decode_ui(game_ui *ui, char *encoding)
1875 static void game_changed_state(game_ui *ui, game_state *oldstate,
1876 game_state *newstate)
1880 struct game_drawstate {
1882 unsigned short *drawn, *todraw;
1884 int dragx, dragy, drag_visible;
1888 /* Flags in `drawn'. */
1889 #define ERR_T 0x0100
1890 #define ERR_B 0x0200
1891 #define ERR_L 0x0400
1892 #define ERR_R 0x0800
1893 #define ERR_C 0x1000
1894 #define ERR_MASK 0x1F00
1896 #define TILESIZE (ds->tilesize)
1897 #define BORDER (TILESIZE)
1898 #define COORD(x) ( (x) * TILESIZE + BORDER )
1899 #define FROMCOORD(x) ( ((x) - BORDER + TILESIZE) / TILESIZE - 1 )
1901 static int region_from_coords(game_state *state, game_drawstate *ds,
1904 int w = state->p.w, h = state->p.h, wh = w*h /*, n = state->p.n */;
1905 int tx = FROMCOORD(x), ty = FROMCOORD(y);
1906 int dx = x - COORD(tx), dy = y - COORD(ty);
1909 if (tx < 0 || tx >= w || ty < 0 || ty >= h)
1910 return -1; /* border */
1912 quadrant = 2 * (dx > dy) + (TILESIZE - dx > dy);
1913 quadrant = (quadrant == 0 ? BE :
1914 quadrant == 1 ? LE :
1915 quadrant == 2 ? RE : TE);
1917 return state->map->map[quadrant * wh + ty*w+tx];
1920 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
1921 int x, int y, int button)
1925 if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
1926 int r = region_from_coords(state, ds, x, y);
1929 ui->drag_colour = state->colouring[r];
1931 ui->drag_colour = -1;
1937 if ((button == LEFT_DRAG || button == RIGHT_DRAG) &&
1938 ui->drag_colour > -2) {
1944 if ((button == LEFT_RELEASE || button == RIGHT_RELEASE) &&
1945 ui->drag_colour > -2) {
1946 int r = region_from_coords(state, ds, x, y);
1947 int c = ui->drag_colour;
1950 * Cancel the drag, whatever happens.
1952 ui->drag_colour = -2;
1953 ui->dragx = ui->dragy = -1;
1956 return ""; /* drag into border; do nothing else */
1958 if (state->map->immutable[r])
1959 return ""; /* can't change this region */
1961 if (state->colouring[r] == c)
1962 return ""; /* don't _need_ to change this region */
1964 sprintf(buf, "%c:%d", (int)(c < 0 ? 'C' : '0' + c), r);
1971 static game_state *execute_move(game_state *state, char *move)
1974 game_state *ret = dup_game(state);
1979 if ((c == 'C' || (c >= '0' && c < '0'+FOUR)) &&
1980 sscanf(move+1, ":%d%n", &k, &adv) == 1 &&
1981 k >= 0 && k < state->p.n) {
1983 ret->colouring[k] = (c == 'C' ? -1 : c - '0');
1984 } else if (*move == 'S') {
1986 ret->cheated = TRUE;
1992 if (*move && *move != ';') {
2001 * Check for completion.
2003 if (!ret->completed) {
2006 for (i = 0; i < n; i++)
2007 if (ret->colouring[i] < 0) {
2013 for (i = 0; i < ret->map->ngraph; i++) {
2014 int j = ret->map->graph[i] / n;
2015 int k = ret->map->graph[i] % n;
2016 if (ret->colouring[j] == ret->colouring[k]) {
2024 ret->completed = TRUE;
2030 /* ----------------------------------------------------------------------
2034 static void game_compute_size(game_params *params, int tilesize,
2037 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2038 struct { int tilesize; } ads, *ds = &ads;
2039 ads.tilesize = tilesize;
2041 *x = params->w * TILESIZE + 2 * BORDER + 1;
2042 *y = params->h * TILESIZE + 2 * BORDER + 1;
2045 static void game_set_size(drawing *dr, game_drawstate *ds,
2046 game_params *params, int tilesize)
2048 ds->tilesize = tilesize;
2051 blitter_free(dr, ds->bl);
2052 ds->bl = blitter_new(dr, TILESIZE+3, TILESIZE+3);
2055 const float map_colours[FOUR][3] = {
2059 {0.55F, 0.45F, 0.35F},
2061 const int map_hatching[FOUR] = {
2062 HATCH_VERT, HATCH_SLASH, HATCH_HORIZ, HATCH_BACKSLASH
2065 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
2067 float *ret = snewn(3 * NCOLOURS, float);
2069 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2071 ret[COL_GRID * 3 + 0] = 0.0F;
2072 ret[COL_GRID * 3 + 1] = 0.0F;
2073 ret[COL_GRID * 3 + 2] = 0.0F;
2075 memcpy(ret + COL_0 * 3, map_colours[0], 3 * sizeof(float));
2076 memcpy(ret + COL_1 * 3, map_colours[1], 3 * sizeof(float));
2077 memcpy(ret + COL_2 * 3, map_colours[2], 3 * sizeof(float));
2078 memcpy(ret + COL_3 * 3, map_colours[3], 3 * sizeof(float));
2080 ret[COL_ERROR * 3 + 0] = 1.0F;
2081 ret[COL_ERROR * 3 + 1] = 0.0F;
2082 ret[COL_ERROR * 3 + 2] = 0.0F;
2084 ret[COL_ERRTEXT * 3 + 0] = 1.0F;
2085 ret[COL_ERRTEXT * 3 + 1] = 1.0F;
2086 ret[COL_ERRTEXT * 3 + 2] = 1.0F;
2088 *ncolours = NCOLOURS;
2092 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2094 struct game_drawstate *ds = snew(struct game_drawstate);
2098 ds->drawn = snewn(state->p.w * state->p.h, unsigned short);
2099 for (i = 0; i < state->p.w * state->p.h; i++)
2100 ds->drawn[i] = 0xFFFF;
2101 ds->todraw = snewn(state->p.w * state->p.h, unsigned short);
2102 ds->started = FALSE;
2104 ds->drag_visible = FALSE;
2105 ds->dragx = ds->dragy = -1;
2110 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2115 blitter_free(dr, ds->bl);
2119 static void draw_error(drawing *dr, game_drawstate *ds, int x, int y)
2127 coords[0] = x - TILESIZE*2/5;
2130 coords[3] = y - TILESIZE*2/5;
2131 coords[4] = x + TILESIZE*2/5;
2134 coords[7] = y + TILESIZE*2/5;
2135 draw_polygon(dr, coords, 4, COL_ERROR, COL_GRID);
2138 * Draw an exclamation mark in the diamond. This turns out to
2139 * look unpleasantly off-centre if done via draw_text, so I do
2140 * it by hand on the basis that exclamation marks aren't that
2141 * difficult to draw...
2144 yext = TILESIZE*2/5 - (xext*2+2);
2145 draw_rect(dr, x-xext, y-yext, xext*2+1, yext*2+1 - (xext*3+1),
2147 draw_rect(dr, x-xext, y+yext-xext*2, xext*2+1, xext*2+1, COL_ERRTEXT);
2150 static void draw_square(drawing *dr, game_drawstate *ds,
2151 game_params *params, struct map *map,
2152 int x, int y, int v)
2154 int w = params->w, h = params->h, wh = w*h;
2157 errs = v & ERR_MASK;
2162 clip(dr, COORD(x), COORD(y), TILESIZE, TILESIZE);
2165 * Draw the region colour.
2167 draw_rect(dr, COORD(x), COORD(y), TILESIZE, TILESIZE,
2168 (tv == FOUR ? COL_BACKGROUND : COL_0 + tv));
2170 * Draw the second region colour, if this is a diagonally
2173 if (map->map[TE * wh + y*w+x] != map->map[BE * wh + y*w+x]) {
2175 coords[0] = COORD(x)-1;
2176 coords[1] = COORD(y+1)+1;
2177 if (map->map[LE * wh + y*w+x] == map->map[TE * wh + y*w+x])
2178 coords[2] = COORD(x+1)+1;
2180 coords[2] = COORD(x)-1;
2181 coords[3] = COORD(y)-1;
2182 coords[4] = COORD(x+1)+1;
2183 coords[5] = COORD(y+1)+1;
2184 draw_polygon(dr, coords, 3,
2185 (bv == FOUR ? COL_BACKGROUND : COL_0 + bv), COL_GRID);
2189 * Draw the grid lines, if required.
2191 if (x <= 0 || map->map[RE*wh+y*w+(x-1)] != map->map[LE*wh+y*w+x])
2192 draw_rect(dr, COORD(x), COORD(y), 1, TILESIZE, COL_GRID);
2193 if (y <= 0 || map->map[BE*wh+(y-1)*w+x] != map->map[TE*wh+y*w+x])
2194 draw_rect(dr, COORD(x), COORD(y), TILESIZE, 1, COL_GRID);
2195 if (x <= 0 || y <= 0 ||
2196 map->map[RE*wh+(y-1)*w+(x-1)] != map->map[TE*wh+y*w+x] ||
2197 map->map[BE*wh+(y-1)*w+(x-1)] != map->map[LE*wh+y*w+x])
2198 draw_rect(dr, COORD(x), COORD(y), 1, 1, COL_GRID);
2201 * Draw error markers.
2204 draw_error(dr, ds, COORD(x)+TILESIZE/2, COORD(y));
2206 draw_error(dr, ds, COORD(x), COORD(y)+TILESIZE/2);
2208 draw_error(dr, ds, COORD(x)+TILESIZE/2, COORD(y+1));
2210 draw_error(dr, ds, COORD(x+1), COORD(y)+TILESIZE/2);
2212 draw_error(dr, ds, COORD(x)+TILESIZE/2, COORD(y)+TILESIZE/2);
2216 draw_update(dr, COORD(x), COORD(y), TILESIZE, TILESIZE);
2219 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2220 game_state *state, int dir, game_ui *ui,
2221 float animtime, float flashtime)
2223 int w = state->p.w, h = state->p.h, wh = w*h, n = state->p.n;
2227 if (ds->drag_visible) {
2228 blitter_load(dr, ds->bl, ds->dragx, ds->dragy);
2229 draw_update(dr, ds->dragx, ds->dragy, TILESIZE + 3, TILESIZE + 3);
2230 ds->drag_visible = FALSE;
2234 * The initial contents of the window are not guaranteed and
2235 * can vary with front ends. To be on the safe side, all games
2236 * should start by drawing a big background-colour rectangle
2237 * covering the whole window.
2242 game_compute_size(&state->p, TILESIZE, &ww, &wh);
2243 draw_rect(dr, 0, 0, ww, wh, COL_BACKGROUND);
2244 draw_rect(dr, COORD(0), COORD(0), w*TILESIZE+1, h*TILESIZE+1,
2247 draw_update(dr, 0, 0, ww, wh);
2252 if (flash_type == 1)
2253 flash = (int)(flashtime * FOUR / flash_length);
2255 flash = 1 + (int)(flashtime * THREE / flash_length);
2260 * Set up the `todraw' array.
2262 for (y = 0; y < h; y++)
2263 for (x = 0; x < w; x++) {
2264 int tv = state->colouring[state->map->map[TE * wh + y*w+x]];
2265 int bv = state->colouring[state->map->map[BE * wh + y*w+x]];
2274 if (flash_type == 1) {
2279 } else if (flash_type == 2) {
2284 tv = (tv + flash) % FOUR;
2286 bv = (bv + flash) % FOUR;
2292 ds->todraw[y*w+x] = v;
2296 * Add error markers to the `todraw' array.
2298 for (i = 0; i < state->map->ngraph; i++) {
2299 int v1 = state->map->graph[i] / n;
2300 int v2 = state->map->graph[i] % n;
2302 if (state->colouring[v1] < 0 || state->colouring[v2] < 0)
2304 if (state->colouring[v1] != state->colouring[v2])
2307 x = state->map->edgex[i];
2308 y = state->map->edgey[i];
2310 if (x % 2 && y % 2) {
2311 ds->todraw[(y/2)*w+(x/2)] |= ERR_C;
2313 ds->todraw[(y/2-1)*w+(x/2)] |= ERR_B;
2314 ds->todraw[(y/2)*w+(x/2)] |= ERR_T;
2317 ds->todraw[(y/2)*w+(x/2-1)] |= ERR_R;
2318 ds->todraw[(y/2)*w+(x/2)] |= ERR_L;
2323 * Now actually draw everything.
2325 for (y = 0; y < h; y++)
2326 for (x = 0; x < w; x++) {
2327 int v = ds->todraw[y*w+x];
2328 if (ds->drawn[y*w+x] != v) {
2329 draw_square(dr, ds, &state->p, state->map, x, y, v);
2330 ds->drawn[y*w+x] = v;
2335 * Draw the dragged colour blob if any.
2337 if (ui->drag_colour > -2) {
2338 ds->dragx = ui->dragx - TILESIZE/2 - 2;
2339 ds->dragy = ui->dragy - TILESIZE/2 - 2;
2340 blitter_save(dr, ds->bl, ds->dragx, ds->dragy);
2341 draw_circle(dr, ui->dragx, ui->dragy, TILESIZE/2,
2342 (ui->drag_colour < 0 ? COL_BACKGROUND :
2343 COL_0 + ui->drag_colour), COL_GRID);
2344 draw_update(dr, ds->dragx, ds->dragy, TILESIZE + 3, TILESIZE + 3);
2345 ds->drag_visible = TRUE;
2349 static float game_anim_length(game_state *oldstate, game_state *newstate,
2350 int dir, game_ui *ui)
2355 static float game_flash_length(game_state *oldstate, game_state *newstate,
2356 int dir, game_ui *ui)
2358 if (!oldstate->completed && newstate->completed &&
2359 !oldstate->cheated && !newstate->cheated) {
2360 if (flash_type < 0) {
2361 char *env = getenv("MAP_ALTERNATIVE_FLASH");
2363 flash_type = atoi(env);
2366 flash_length = (flash_type == 1 ? 0.50 : 0.30);
2368 return flash_length;
2373 static int game_wants_statusbar(void)
2378 static int game_timing_state(game_state *state, game_ui *ui)
2383 static void game_print_size(game_params *params, float *x, float *y)
2388 * I'll use 4mm squares by default, I think. Simplest way to
2389 * compute this size is to compute the pixel puzzle size at a
2390 * given tile size and then scale.
2392 game_compute_size(params, 400, &pw, &ph);
2397 static void game_print(drawing *dr, game_state *state, int tilesize)
2399 int w = state->p.w, h = state->p.h, wh = w*h, n = state->p.n;
2400 int ink, c[FOUR], i;
2402 int *coords, ncoords, coordsize;
2404 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2405 struct { int tilesize; } ads, *ds = &ads;
2406 ads.tilesize = tilesize;
2408 ink = print_mono_colour(dr, 0);
2409 for (i = 0; i < FOUR; i++)
2410 c[i] = print_rgb_colour(dr, map_hatching[i], map_colours[i][0],
2411 map_colours[i][1], map_colours[i][2]);
2416 print_line_width(dr, TILESIZE / 16);
2419 * Draw a single filled polygon around each region.
2421 for (r = 0; r < n; r++) {
2422 int octants[8], lastdir, d1, d2, ox, oy;
2425 * Start by finding a point on the region boundary. Any
2426 * point will do. To do this, we'll search for a square
2427 * containing the region and then decide which corner of it
2431 for (y = 0; y < h; y++) {
2432 for (x = 0; x < w; x++) {
2433 if (state->map->map[wh*0+y*w+x] == r ||
2434 state->map->map[wh*1+y*w+x] == r ||
2435 state->map->map[wh*2+y*w+x] == r ||
2436 state->map->map[wh*3+y*w+x] == r)
2442 assert(y < h && x < w); /* we must have found one somewhere */
2444 * This is the first square in lexicographic order which
2445 * contains part of this region. Therefore, one of the top
2446 * two corners of the square must be what we're after. The
2447 * only case in which it isn't the top left one is if the
2448 * square is diagonally divided and the region is in the
2449 * bottom right half.
2451 if (state->map->map[wh*TE+y*w+x] != r &&
2452 state->map->map[wh*LE+y*w+x] != r)
2453 x++; /* could just as well have done y++ */
2456 * Now we have a point on the region boundary. Trace around
2457 * the region until we come back to this point,
2458 * accumulating coordinates for a polygon draw operation as
2468 * There are eight possible directions we could head in
2469 * from here. We identify them by octant numbers, and
2470 * we also use octant numbers to identify the spaces
2483 octants[0] = x<w && y>0 ? state->map->map[wh*LE+(y-1)*w+x] : -1;
2484 octants[1] = x<w && y>0 ? state->map->map[wh*BE+(y-1)*w+x] : -1;
2485 octants[2] = x<w && y<h ? state->map->map[wh*TE+y*w+x] : -1;
2486 octants[3] = x<w && y<h ? state->map->map[wh*LE+y*w+x] : -1;
2487 octants[4] = x>0 && y<h ? state->map->map[wh*RE+y*w+(x-1)] : -1;
2488 octants[5] = x>0 && y<h ? state->map->map[wh*TE+y*w+(x-1)] : -1;
2489 octants[6] = x>0 && y>0 ? state->map->map[wh*BE+(y-1)*w+(x-1)] :-1;
2490 octants[7] = x>0 && y>0 ? state->map->map[wh*RE+(y-1)*w+(x-1)] :-1;
2493 for (i = 0; i < 8; i++)
2494 if ((octants[i] == r) ^ (octants[(i+1)%8] == r)) {
2501 /* printf("%% %d,%d r=%d: d1=%d d2=%d lastdir=%d\n", x, y, r, d1, d2, lastdir); */
2502 assert(d1 != -1 && d2 != -1);
2507 * Now we're heading in direction d1. Save the current
2510 if (ncoords + 2 > coordsize) {
2512 coords = sresize(coords, coordsize, int);
2514 coords[ncoords++] = COORD(x);
2515 coords[ncoords++] = COORD(y);
2518 * Compute the new coordinates.
2520 x += (d1 % 4 == 3 ? 0 : d1 < 4 ? +1 : -1);
2521 y += (d1 % 4 == 1 ? 0 : d1 > 1 && d1 < 5 ? +1 : -1);
2522 assert(x >= 0 && x <= w && y >= 0 && y <= h);
2525 } while (x != ox || y != oy);
2527 draw_polygon(dr, coords, ncoords/2,
2528 state->colouring[r] >= 0 ?
2529 c[state->colouring[r]] : -1, ink);
2538 const struct game thegame = {
2546 TRUE, game_configure, custom_params,
2554 FALSE, game_text_format,
2562 20, game_compute_size, game_set_size,
2565 game_free_drawstate,
2569 TRUE, TRUE, game_print_size, game_print,
2570 game_wants_statusbar,
2571 FALSE, game_timing_state,
2572 0, /* mouse_priorities */