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[4], ey[4], ea[4], eb[4], en = 0;
1646 * Look for an edge to the right of this
1647 * square, an edge below it, and an edge in the
1648 * middle of it. Also look to see if the point
1649 * at the bottom right of this square is on an
1650 * edge (and isn't a place where more than two
1655 ea[en] = state->map->map[RE * wh + y*w+x];
1656 eb[en] = state->map->map[LE * wh + y*w+(x+1)];
1657 if (ea[en] != eb[en]) {
1665 ea[en] = state->map->map[BE * wh + y*w+x];
1666 eb[en] = state->map->map[TE * wh + (y+1)*w+x];
1667 if (ea[en] != eb[en]) {
1674 ea[en] = state->map->map[TE * wh + y*w+x];
1675 eb[en] = state->map->map[BE * wh + y*w+x];
1676 if (ea[en] != eb[en]) {
1681 if (x+1 < w && y+1 < h) {
1682 /* bottom right corner */
1683 int oct[8], othercol, nchanges;
1684 oct[0] = state->map->map[RE * wh + y*w+x];
1685 oct[1] = state->map->map[LE * wh + y*w+(x+1)];
1686 oct[2] = state->map->map[BE * wh + y*w+(x+1)];
1687 oct[3] = state->map->map[TE * wh + (y+1)*w+(x+1)];
1688 oct[4] = state->map->map[LE * wh + (y+1)*w+(x+1)];
1689 oct[5] = state->map->map[RE * wh + (y+1)*w+x];
1690 oct[6] = state->map->map[TE * wh + (y+1)*w+x];
1691 oct[7] = state->map->map[BE * wh + y*w+x];
1695 for (i = 0; i < 8; i++) {
1696 if (oct[i] != oct[0]) {
1699 else if (othercol != oct[i])
1700 break; /* three colours at this point */
1702 if (oct[i] != oct[(i+1) & 7])
1707 * Now if there are exactly two regions at
1708 * this point (not one, and not three or
1709 * more), and only two changes around the
1710 * loop, then this is a valid place to put
1713 if (i == 8 && othercol >= 0 && nchanges == 2) {
1723 * Now process the edges we've found, one by
1726 for (i = 0; i < en; i++) {
1727 int emin = min(ea[i], eb[i]);
1728 int emax = max(ea[i], eb[i]);
1730 graph_edge_index(state->map->graph, n,
1731 state->map->ngraph, emin, emax);
1733 assert(gindex >= 0);
1737 * In pass 0, accumulate the values
1738 * we'll use to compute the average
1741 ax[gindex] += ex[i];
1742 ay[gindex] += ey[i];
1746 * In pass 1, work out whether this
1747 * point is closer to the average than
1748 * the last one we've seen.
1752 assert(an[gindex] > 0);
1753 dx = ex[i] - ax[gindex];
1754 dy = ey[i] - ay[gindex];
1755 d = sqrt(dx*dx + dy*dy);
1756 if (d < best[gindex]) {
1758 bestx[gindex] = ex[i];
1759 besty[gindex] = ey[i];
1766 for (i = 0; i < state->map->ngraph; i++)
1774 state->map->edgex = bestx;
1775 state->map->edgey = besty;
1777 for (i = 0; i < state->map->ngraph; i++)
1778 if (state->map->edgex[i] < 0) {
1779 /* Find the other representation of this edge. */
1780 int e = state->map->graph[i];
1781 int iprime = graph_edge_index(state->map->graph, n,
1782 state->map->ngraph, e%n, e/n);
1783 assert(state->map->edgex[iprime] >= 0);
1784 state->map->edgex[i] = state->map->edgex[iprime];
1785 state->map->edgey[i] = state->map->edgey[iprime];
1797 static game_state *dup_game(game_state *state)
1799 game_state *ret = snew(game_state);
1802 ret->colouring = snewn(state->p.n, int);
1803 memcpy(ret->colouring, state->colouring, state->p.n * sizeof(int));
1804 ret->map = state->map;
1805 ret->map->refcount++;
1806 ret->completed = state->completed;
1807 ret->cheated = state->cheated;
1812 static void free_game(game_state *state)
1814 if (--state->map->refcount <= 0) {
1815 sfree(state->map->map);
1816 sfree(state->map->graph);
1817 sfree(state->map->immutable);
1818 sfree(state->map->edgex);
1819 sfree(state->map->edgey);
1822 sfree(state->colouring);
1826 static char *solve_game(game_state *state, game_state *currstate,
1827 char *aux, char **error)
1834 struct solver_scratch *sc;
1838 int retlen, retsize;
1840 colouring = snewn(state->map->n, int);
1841 memcpy(colouring, state->colouring, state->map->n * sizeof(int));
1843 sc = new_scratch(state->map->graph, state->map->n, state->map->ngraph);
1844 sret = map_solver(sc, state->map->graph, state->map->n,
1845 state->map->ngraph, colouring, DIFFCOUNT-1);
1851 *error = "Puzzle is inconsistent";
1853 *error = "Unable to find a unique solution for this puzzle";
1858 ret = snewn(retsize, char);
1862 for (i = 0; i < state->map->n; i++) {
1865 assert(colouring[i] >= 0);
1866 if (colouring[i] == currstate->colouring[i])
1868 assert(!state->map->immutable[i]);
1870 len = sprintf(buf, ";%d:%d", colouring[i], i);
1871 if (retlen + len >= retsize) {
1872 retsize = retlen + len + 256;
1873 ret = sresize(ret, retsize, char);
1875 strcpy(ret + retlen, buf);
1886 static char *game_text_format(game_state *state)
1892 int drag_colour; /* -1 means no drag active */
1896 static game_ui *new_ui(game_state *state)
1898 game_ui *ui = snew(game_ui);
1899 ui->dragx = ui->dragy = -1;
1900 ui->drag_colour = -2;
1904 static void free_ui(game_ui *ui)
1909 static char *encode_ui(game_ui *ui)
1914 static void decode_ui(game_ui *ui, char *encoding)
1918 static void game_changed_state(game_ui *ui, game_state *oldstate,
1919 game_state *newstate)
1923 struct game_drawstate {
1925 unsigned short *drawn, *todraw;
1927 int dragx, dragy, drag_visible;
1931 /* Flags in `drawn'. */
1932 #define ERR_BASE 0x0080
1933 #define ERR_MASK 0xFF80
1935 #define TILESIZE (ds->tilesize)
1936 #define BORDER (TILESIZE)
1937 #define COORD(x) ( (x) * TILESIZE + BORDER )
1938 #define FROMCOORD(x) ( ((x) - BORDER + TILESIZE) / TILESIZE - 1 )
1940 static int region_from_coords(game_state *state, game_drawstate *ds,
1943 int w = state->p.w, h = state->p.h, wh = w*h /*, n = state->p.n */;
1944 int tx = FROMCOORD(x), ty = FROMCOORD(y);
1945 int dx = x - COORD(tx), dy = y - COORD(ty);
1948 if (tx < 0 || tx >= w || ty < 0 || ty >= h)
1949 return -1; /* border */
1951 quadrant = 2 * (dx > dy) + (TILESIZE - dx > dy);
1952 quadrant = (quadrant == 0 ? BE :
1953 quadrant == 1 ? LE :
1954 quadrant == 2 ? RE : TE);
1956 return state->map->map[quadrant * wh + ty*w+tx];
1959 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
1960 int x, int y, int button)
1964 if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
1965 int r = region_from_coords(state, ds, x, y);
1968 ui->drag_colour = state->colouring[r];
1970 ui->drag_colour = -1;
1976 if ((button == LEFT_DRAG || button == RIGHT_DRAG) &&
1977 ui->drag_colour > -2) {
1983 if ((button == LEFT_RELEASE || button == RIGHT_RELEASE) &&
1984 ui->drag_colour > -2) {
1985 int r = region_from_coords(state, ds, x, y);
1986 int c = ui->drag_colour;
1989 * Cancel the drag, whatever happens.
1991 ui->drag_colour = -2;
1992 ui->dragx = ui->dragy = -1;
1995 return ""; /* drag into border; do nothing else */
1997 if (state->map->immutable[r])
1998 return ""; /* can't change this region */
2000 if (state->colouring[r] == c)
2001 return ""; /* don't _need_ to change this region */
2003 sprintf(buf, "%c:%d", (int)(c < 0 ? 'C' : '0' + c), r);
2010 static game_state *execute_move(game_state *state, char *move)
2013 game_state *ret = dup_game(state);
2018 if ((c == 'C' || (c >= '0' && c < '0'+FOUR)) &&
2019 sscanf(move+1, ":%d%n", &k, &adv) == 1 &&
2020 k >= 0 && k < state->p.n) {
2022 ret->colouring[k] = (c == 'C' ? -1 : c - '0');
2023 } else if (*move == 'S') {
2025 ret->cheated = TRUE;
2031 if (*move && *move != ';') {
2040 * Check for completion.
2042 if (!ret->completed) {
2045 for (i = 0; i < n; i++)
2046 if (ret->colouring[i] < 0) {
2052 for (i = 0; i < ret->map->ngraph; i++) {
2053 int j = ret->map->graph[i] / n;
2054 int k = ret->map->graph[i] % n;
2055 if (ret->colouring[j] == ret->colouring[k]) {
2063 ret->completed = TRUE;
2069 /* ----------------------------------------------------------------------
2073 static void game_compute_size(game_params *params, int tilesize,
2076 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2077 struct { int tilesize; } ads, *ds = &ads;
2078 ads.tilesize = tilesize;
2080 *x = params->w * TILESIZE + 2 * BORDER + 1;
2081 *y = params->h * TILESIZE + 2 * BORDER + 1;
2084 static void game_set_size(drawing *dr, game_drawstate *ds,
2085 game_params *params, int tilesize)
2087 ds->tilesize = tilesize;
2090 blitter_free(dr, ds->bl);
2091 ds->bl = blitter_new(dr, TILESIZE+3, TILESIZE+3);
2094 const float map_colours[FOUR][3] = {
2098 {0.55F, 0.45F, 0.35F},
2100 const int map_hatching[FOUR] = {
2101 HATCH_VERT, HATCH_SLASH, HATCH_HORIZ, HATCH_BACKSLASH
2104 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
2106 float *ret = snewn(3 * NCOLOURS, float);
2108 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2110 ret[COL_GRID * 3 + 0] = 0.0F;
2111 ret[COL_GRID * 3 + 1] = 0.0F;
2112 ret[COL_GRID * 3 + 2] = 0.0F;
2114 memcpy(ret + COL_0 * 3, map_colours[0], 3 * sizeof(float));
2115 memcpy(ret + COL_1 * 3, map_colours[1], 3 * sizeof(float));
2116 memcpy(ret + COL_2 * 3, map_colours[2], 3 * sizeof(float));
2117 memcpy(ret + COL_3 * 3, map_colours[3], 3 * sizeof(float));
2119 ret[COL_ERROR * 3 + 0] = 1.0F;
2120 ret[COL_ERROR * 3 + 1] = 0.0F;
2121 ret[COL_ERROR * 3 + 2] = 0.0F;
2123 ret[COL_ERRTEXT * 3 + 0] = 1.0F;
2124 ret[COL_ERRTEXT * 3 + 1] = 1.0F;
2125 ret[COL_ERRTEXT * 3 + 2] = 1.0F;
2127 *ncolours = NCOLOURS;
2131 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2133 struct game_drawstate *ds = snew(struct game_drawstate);
2137 ds->drawn = snewn(state->p.w * state->p.h, unsigned short);
2138 for (i = 0; i < state->p.w * state->p.h; i++)
2139 ds->drawn[i] = 0xFFFF;
2140 ds->todraw = snewn(state->p.w * state->p.h, unsigned short);
2141 ds->started = FALSE;
2143 ds->drag_visible = FALSE;
2144 ds->dragx = ds->dragy = -1;
2149 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2154 blitter_free(dr, ds->bl);
2158 static void draw_error(drawing *dr, game_drawstate *ds, int x, int y)
2166 coords[0] = x - TILESIZE*2/5;
2169 coords[3] = y - TILESIZE*2/5;
2170 coords[4] = x + TILESIZE*2/5;
2173 coords[7] = y + TILESIZE*2/5;
2174 draw_polygon(dr, coords, 4, COL_ERROR, COL_GRID);
2177 * Draw an exclamation mark in the diamond. This turns out to
2178 * look unpleasantly off-centre if done via draw_text, so I do
2179 * it by hand on the basis that exclamation marks aren't that
2180 * difficult to draw...
2183 yext = TILESIZE*2/5 - (xext*2+2);
2184 draw_rect(dr, x-xext, y-yext, xext*2+1, yext*2+1 - (xext*3),
2186 draw_rect(dr, x-xext, y+yext-xext*2+1, xext*2+1, xext*2, COL_ERRTEXT);
2189 static void draw_square(drawing *dr, game_drawstate *ds,
2190 game_params *params, struct map *map,
2191 int x, int y, int v)
2193 int w = params->w, h = params->h, wh = w*h;
2194 int tv, bv, xo, yo, errs;
2196 errs = v & ERR_MASK;
2201 clip(dr, COORD(x), COORD(y), TILESIZE, TILESIZE);
2204 * Draw the region colour.
2206 draw_rect(dr, COORD(x), COORD(y), TILESIZE, TILESIZE,
2207 (tv == FOUR ? COL_BACKGROUND : COL_0 + tv));
2209 * Draw the second region colour, if this is a diagonally
2212 if (map->map[TE * wh + y*w+x] != map->map[BE * wh + y*w+x]) {
2214 coords[0] = COORD(x)-1;
2215 coords[1] = COORD(y+1)+1;
2216 if (map->map[LE * wh + y*w+x] == map->map[TE * wh + y*w+x])
2217 coords[2] = COORD(x+1)+1;
2219 coords[2] = COORD(x)-1;
2220 coords[3] = COORD(y)-1;
2221 coords[4] = COORD(x+1)+1;
2222 coords[5] = COORD(y+1)+1;
2223 draw_polygon(dr, coords, 3,
2224 (bv == FOUR ? COL_BACKGROUND : COL_0 + bv), COL_GRID);
2228 * Draw the grid lines, if required.
2230 if (x <= 0 || map->map[RE*wh+y*w+(x-1)] != map->map[LE*wh+y*w+x])
2231 draw_rect(dr, COORD(x), COORD(y), 1, TILESIZE, COL_GRID);
2232 if (y <= 0 || map->map[BE*wh+(y-1)*w+x] != map->map[TE*wh+y*w+x])
2233 draw_rect(dr, COORD(x), COORD(y), TILESIZE, 1, COL_GRID);
2234 if (x <= 0 || y <= 0 ||
2235 map->map[RE*wh+(y-1)*w+(x-1)] != map->map[TE*wh+y*w+x] ||
2236 map->map[BE*wh+(y-1)*w+(x-1)] != map->map[LE*wh+y*w+x])
2237 draw_rect(dr, COORD(x), COORD(y), 1, 1, COL_GRID);
2240 * Draw error markers.
2242 for (yo = 0; yo < 3; yo++)
2243 for (xo = 0; xo < 3; xo++)
2244 if (errs & (ERR_BASE << (yo*3+xo)))
2246 (COORD(x)*2+TILESIZE*xo)/2,
2247 (COORD(y)*2+TILESIZE*yo)/2);
2251 draw_update(dr, COORD(x), COORD(y), TILESIZE, TILESIZE);
2254 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2255 game_state *state, int dir, game_ui *ui,
2256 float animtime, float flashtime)
2258 int w = state->p.w, h = state->p.h, wh = w*h, n = state->p.n;
2262 if (ds->drag_visible) {
2263 blitter_load(dr, ds->bl, ds->dragx, ds->dragy);
2264 draw_update(dr, ds->dragx, ds->dragy, TILESIZE + 3, TILESIZE + 3);
2265 ds->drag_visible = FALSE;
2269 * The initial contents of the window are not guaranteed and
2270 * can vary with front ends. To be on the safe side, all games
2271 * should start by drawing a big background-colour rectangle
2272 * covering the whole window.
2277 game_compute_size(&state->p, TILESIZE, &ww, &wh);
2278 draw_rect(dr, 0, 0, ww, wh, COL_BACKGROUND);
2279 draw_rect(dr, COORD(0), COORD(0), w*TILESIZE+1, h*TILESIZE+1,
2282 draw_update(dr, 0, 0, ww, wh);
2287 if (flash_type == 1)
2288 flash = (int)(flashtime * FOUR / flash_length);
2290 flash = 1 + (int)(flashtime * THREE / flash_length);
2295 * Set up the `todraw' array.
2297 for (y = 0; y < h; y++)
2298 for (x = 0; x < w; x++) {
2299 int tv = state->colouring[state->map->map[TE * wh + y*w+x]];
2300 int bv = state->colouring[state->map->map[BE * wh + y*w+x]];
2309 if (flash_type == 1) {
2314 } else if (flash_type == 2) {
2319 tv = (tv + flash) % FOUR;
2321 bv = (bv + flash) % FOUR;
2327 ds->todraw[y*w+x] = v;
2331 * Add error markers to the `todraw' array.
2333 for (i = 0; i < state->map->ngraph; i++) {
2334 int v1 = state->map->graph[i] / n;
2335 int v2 = state->map->graph[i] % n;
2338 if (state->colouring[v1] < 0 || state->colouring[v2] < 0)
2340 if (state->colouring[v1] != state->colouring[v2])
2343 x = state->map->edgex[i];
2344 y = state->map->edgey[i];
2349 ds->todraw[y*w+x] |= ERR_BASE << (yo*3+xo);
2352 ds->todraw[y*w+(x-1)] |= ERR_BASE << (yo*3+2);
2356 ds->todraw[(y-1)*w+x] |= ERR_BASE << (2*3+xo);
2358 if (xo == 0 && yo == 0) {
2359 assert(x > 0 && y > 0);
2360 ds->todraw[(y-1)*w+(x-1)] |= ERR_BASE << (2*3+2);
2365 * Now actually draw everything.
2367 for (y = 0; y < h; y++)
2368 for (x = 0; x < w; x++) {
2369 int v = ds->todraw[y*w+x];
2370 if (ds->drawn[y*w+x] != v) {
2371 draw_square(dr, ds, &state->p, state->map, x, y, v);
2372 ds->drawn[y*w+x] = v;
2377 * Draw the dragged colour blob if any.
2379 if (ui->drag_colour > -2) {
2380 ds->dragx = ui->dragx - TILESIZE/2 - 2;
2381 ds->dragy = ui->dragy - TILESIZE/2 - 2;
2382 blitter_save(dr, ds->bl, ds->dragx, ds->dragy);
2383 draw_circle(dr, ui->dragx, ui->dragy, TILESIZE/2,
2384 (ui->drag_colour < 0 ? COL_BACKGROUND :
2385 COL_0 + ui->drag_colour), COL_GRID);
2386 draw_update(dr, ds->dragx, ds->dragy, TILESIZE + 3, TILESIZE + 3);
2387 ds->drag_visible = TRUE;
2391 static float game_anim_length(game_state *oldstate, game_state *newstate,
2392 int dir, game_ui *ui)
2397 static float game_flash_length(game_state *oldstate, game_state *newstate,
2398 int dir, game_ui *ui)
2400 if (!oldstate->completed && newstate->completed &&
2401 !oldstate->cheated && !newstate->cheated) {
2402 if (flash_type < 0) {
2403 char *env = getenv("MAP_ALTERNATIVE_FLASH");
2405 flash_type = atoi(env);
2408 flash_length = (flash_type == 1 ? 0.50 : 0.30);
2410 return flash_length;
2415 static int game_wants_statusbar(void)
2420 static int game_timing_state(game_state *state, game_ui *ui)
2425 static void game_print_size(game_params *params, float *x, float *y)
2430 * I'll use 4mm squares by default, I think. Simplest way to
2431 * compute this size is to compute the pixel puzzle size at a
2432 * given tile size and then scale.
2434 game_compute_size(params, 400, &pw, &ph);
2439 static void game_print(drawing *dr, game_state *state, int tilesize)
2441 int w = state->p.w, h = state->p.h, wh = w*h, n = state->p.n;
2442 int ink, c[FOUR], i;
2444 int *coords, ncoords, coordsize;
2446 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2447 struct { int tilesize; } ads, *ds = &ads;
2448 ads.tilesize = tilesize;
2450 ink = print_mono_colour(dr, 0);
2451 for (i = 0; i < FOUR; i++)
2452 c[i] = print_rgb_colour(dr, map_hatching[i], map_colours[i][0],
2453 map_colours[i][1], map_colours[i][2]);
2458 print_line_width(dr, TILESIZE / 16);
2461 * Draw a single filled polygon around each region.
2463 for (r = 0; r < n; r++) {
2464 int octants[8], lastdir, d1, d2, ox, oy;
2467 * Start by finding a point on the region boundary. Any
2468 * point will do. To do this, we'll search for a square
2469 * containing the region and then decide which corner of it
2473 for (y = 0; y < h; y++) {
2474 for (x = 0; x < w; x++) {
2475 if (state->map->map[wh*0+y*w+x] == r ||
2476 state->map->map[wh*1+y*w+x] == r ||
2477 state->map->map[wh*2+y*w+x] == r ||
2478 state->map->map[wh*3+y*w+x] == r)
2484 assert(y < h && x < w); /* we must have found one somewhere */
2486 * This is the first square in lexicographic order which
2487 * contains part of this region. Therefore, one of the top
2488 * two corners of the square must be what we're after. The
2489 * only case in which it isn't the top left one is if the
2490 * square is diagonally divided and the region is in the
2491 * bottom right half.
2493 if (state->map->map[wh*TE+y*w+x] != r &&
2494 state->map->map[wh*LE+y*w+x] != r)
2495 x++; /* could just as well have done y++ */
2498 * Now we have a point on the region boundary. Trace around
2499 * the region until we come back to this point,
2500 * accumulating coordinates for a polygon draw operation as
2510 * There are eight possible directions we could head in
2511 * from here. We identify them by octant numbers, and
2512 * we also use octant numbers to identify the spaces
2525 octants[0] = x<w && y>0 ? state->map->map[wh*LE+(y-1)*w+x] : -1;
2526 octants[1] = x<w && y>0 ? state->map->map[wh*BE+(y-1)*w+x] : -1;
2527 octants[2] = x<w && y<h ? state->map->map[wh*TE+y*w+x] : -1;
2528 octants[3] = x<w && y<h ? state->map->map[wh*LE+y*w+x] : -1;
2529 octants[4] = x>0 && y<h ? state->map->map[wh*RE+y*w+(x-1)] : -1;
2530 octants[5] = x>0 && y<h ? state->map->map[wh*TE+y*w+(x-1)] : -1;
2531 octants[6] = x>0 && y>0 ? state->map->map[wh*BE+(y-1)*w+(x-1)] :-1;
2532 octants[7] = x>0 && y>0 ? state->map->map[wh*RE+(y-1)*w+(x-1)] :-1;
2535 for (i = 0; i < 8; i++)
2536 if ((octants[i] == r) ^ (octants[(i+1)%8] == r)) {
2543 /* printf("%% %d,%d r=%d: d1=%d d2=%d lastdir=%d\n", x, y, r, d1, d2, lastdir); */
2544 assert(d1 != -1 && d2 != -1);
2549 * Now we're heading in direction d1. Save the current
2552 if (ncoords + 2 > coordsize) {
2554 coords = sresize(coords, coordsize, int);
2556 coords[ncoords++] = COORD(x);
2557 coords[ncoords++] = COORD(y);
2560 * Compute the new coordinates.
2562 x += (d1 % 4 == 3 ? 0 : d1 < 4 ? +1 : -1);
2563 y += (d1 % 4 == 1 ? 0 : d1 > 1 && d1 < 5 ? +1 : -1);
2564 assert(x >= 0 && x <= w && y >= 0 && y <= h);
2567 } while (x != ox || y != oy);
2569 draw_polygon(dr, coords, ncoords/2,
2570 state->colouring[r] >= 0 ?
2571 c[state->colouring[r]] : -1, ink);
2580 const struct game thegame = {
2588 TRUE, game_configure, custom_params,
2596 FALSE, game_text_format,
2604 20, game_compute_size, game_set_size,
2607 game_free_drawstate,
2611 TRUE, TRUE, game_print_size, game_print,
2612 game_wants_statusbar,
2613 FALSE, game_timing_state,
2614 0, /* mouse_priorities */