2 * map.c: Game involving four-colouring a map.
9 * - better four-colouring algorithm?
22 * In standalone solver mode, `verbose' is a variable which can be
23 * set by command-line option; in debugging mode it's simply always
26 #if defined STANDALONE_SOLVER
27 #define SOLVER_DIAGNOSTICS
29 #elif defined SOLVER_DIAGNOSTICS
34 * I don't seriously anticipate wanting to change the number of
35 * colours used in this game, but it doesn't cost much to use a
36 * #define just in case :-)
39 #define THREE (FOUR-1)
44 * Ghastly run-time configuration option, just for Gareth (again).
46 static int flash_type = -1;
47 static float flash_length;
50 * Difficulty levels. I do some macro ickery here to ensure that my
51 * enum and the various forms of my name list always match up.
57 A(RECURSE,Unreasonable,u)
58 #define ENUM(upper,title,lower) DIFF_ ## upper,
59 #define TITLE(upper,title,lower) #title,
60 #define ENCODE(upper,title,lower) #lower
61 #define CONFIG(upper,title,lower) ":" #title
62 enum { DIFFLIST(ENUM) DIFFCOUNT };
63 static char const *const map_diffnames[] = { DIFFLIST(TITLE) };
64 static char const map_diffchars[] = DIFFLIST(ENCODE);
65 #define DIFFCONFIG DIFFLIST(CONFIG)
67 enum { TE, BE, LE, RE }; /* top/bottom/left/right edges */
72 COL_0, COL_1, COL_2, COL_3,
73 COL_ERROR, COL_ERRTEXT,
88 int *edgex, *edgey; /* position of a point on each edge */
89 int *regionx, *regiony; /* position of a point in each region */
95 int *colouring, *pencil;
96 int completed, cheated;
99 static game_params *default_params(void)
101 game_params *ret = snew(game_params);
103 #ifdef PORTRAIT_SCREEN
111 ret->diff = DIFF_NORMAL;
116 static const struct game_params map_presets[] = {
117 #ifdef PORTRAIT_SCREEN
118 {16, 18, 30, DIFF_EASY},
119 {16, 18, 30, DIFF_NORMAL},
120 {16, 18, 30, DIFF_HARD},
121 {16, 18, 30, DIFF_RECURSE},
122 {25, 30, 75, DIFF_NORMAL},
123 {25, 30, 75, DIFF_HARD},
125 {20, 15, 30, DIFF_EASY},
126 {20, 15, 30, DIFF_NORMAL},
127 {20, 15, 30, DIFF_HARD},
128 {20, 15, 30, DIFF_RECURSE},
129 {30, 25, 75, DIFF_NORMAL},
130 {30, 25, 75, DIFF_HARD},
134 static int game_fetch_preset(int i, char **name, game_params **params)
139 if (i < 0 || i >= lenof(map_presets))
142 ret = snew(game_params);
143 *ret = map_presets[i];
145 sprintf(str, "%dx%d, %d regions, %s", ret->w, ret->h, ret->n,
146 map_diffnames[ret->diff]);
153 static void free_params(game_params *params)
158 static game_params *dup_params(const game_params *params)
160 game_params *ret = snew(game_params);
161 *ret = *params; /* structure copy */
165 static void decode_params(game_params *params, char const *string)
167 char const *p = string;
170 while (*p && isdigit((unsigned char)*p)) p++;
174 while (*p && isdigit((unsigned char)*p)) p++;
176 params->h = params->w;
181 while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
183 params->n = params->w * params->h / 8;
188 for (i = 0; i < DIFFCOUNT; i++)
189 if (*p == map_diffchars[i])
195 static char *encode_params(const game_params *params, int full)
199 sprintf(ret, "%dx%dn%d", params->w, params->h, params->n);
201 sprintf(ret + strlen(ret), "d%c", map_diffchars[params->diff]);
206 static config_item *game_configure(const game_params *params)
211 ret = snewn(5, config_item);
213 ret[0].name = "Width";
214 ret[0].type = C_STRING;
215 sprintf(buf, "%d", params->w);
216 ret[0].u.string.sval = dupstr(buf);
218 ret[1].name = "Height";
219 ret[1].type = C_STRING;
220 sprintf(buf, "%d", params->h);
221 ret[1].u.string.sval = dupstr(buf);
223 ret[2].name = "Regions";
224 ret[2].type = C_STRING;
225 sprintf(buf, "%d", params->n);
226 ret[2].u.string.sval = dupstr(buf);
228 ret[3].name = "Difficulty";
229 ret[3].type = C_CHOICES;
230 ret[3].u.choices.choicenames = DIFFCONFIG;
231 ret[3].u.choices.selected = params->diff;
239 static game_params *custom_params(const config_item *cfg)
241 game_params *ret = snew(game_params);
243 ret->w = atoi(cfg[0].u.string.sval);
244 ret->h = atoi(cfg[1].u.string.sval);
245 ret->n = atoi(cfg[2].u.string.sval);
246 ret->diff = cfg[3].u.choices.selected;
251 static const char *validate_params(const game_params *params, int full)
253 if (params->w < 2 || params->h < 2)
254 return "Width and height must be at least two";
256 return "Must have at least five regions";
257 if (params->n > params->w * params->h)
258 return "Too many regions to fit in grid";
262 /* ----------------------------------------------------------------------
263 * Cumulative frequency table functions.
267 * Initialise a cumulative frequency table. (Hardly worth writing
268 * this function; all it does is to initialise everything in the
271 static void cf_init(int *table, int n)
275 for (i = 0; i < n; i++)
280 * Increment the count of symbol `sym' by `count'.
282 static void cf_add(int *table, int n, int sym, int count)
299 * Cumulative frequency lookup: return the total count of symbols
300 * with value less than `sym'.
302 static int cf_clookup(int *table, int n, int sym)
304 int bit, index, limit, count;
309 assert(0 < sym && sym <= n);
311 count = table[0]; /* start with the whole table size */
321 * Find the least number with its lowest set bit in this
322 * position which is greater than or equal to sym.
324 index = ((sym + bit - 1) &~ (bit * 2 - 1)) + bit;
327 count -= table[index];
338 * Single frequency lookup: return the count of symbol `sym'.
340 static int cf_slookup(int *table, int n, int sym)
344 assert(0 <= sym && sym < n);
348 for (bit = 1; sym+bit < n && !(sym & bit); bit <<= 1)
349 count -= table[sym+bit];
355 * Return the largest symbol index such that the cumulative
356 * frequency up to that symbol is less than _or equal to_ count.
358 static int cf_whichsym(int *table, int n, int count) {
361 assert(count >= 0 && count < table[0]);
372 if (count >= top - table[sym+bit])
375 top -= table[sym+bit];
384 /* ----------------------------------------------------------------------
387 * FIXME: this isn't entirely optimal at present, because it
388 * inherently prioritises growing the largest region since there
389 * are more squares adjacent to it. This acts as a destabilising
390 * influence leading to a few large regions and mostly small ones.
391 * It might be better to do it some other way.
394 #define WEIGHT_INCREASED 2 /* for increased perimeter */
395 #define WEIGHT_DECREASED 4 /* for decreased perimeter */
396 #define WEIGHT_UNCHANGED 3 /* for unchanged perimeter */
399 * Look at a square and decide which colours can be extended into
402 * If called with index < 0, it adds together one of
403 * WEIGHT_INCREASED, WEIGHT_DECREASED or WEIGHT_UNCHANGED for each
404 * colour that has a valid extension (according to the effect that
405 * it would have on the perimeter of the region being extended) and
406 * returns the overall total.
408 * If called with index >= 0, it returns one of the possible
409 * colours depending on the value of index, in such a way that the
410 * number of possible inputs which would give rise to a given
411 * return value correspond to the weight of that value.
413 static int extend_options(int w, int h, int n, int *map,
414 int x, int y, int index)
420 if (map[y*w+x] >= 0) {
422 return 0; /* can't do this square at all */
426 * Fetch the eight neighbours of this square, in order around
429 for (dy = -1; dy <= +1; dy++)
430 for (dx = -1; dx <= +1; dx++) {
431 int index = (dy < 0 ? 6-dx : dy > 0 ? 2+dx : 2*(1+dx));
432 if (x+dx >= 0 && x+dx < w && y+dy >= 0 && y+dy < h)
433 col[index] = map[(y+dy)*w+(x+dx)];
439 * Iterate over each colour that might be feasible.
441 * FIXME: this routine currently has O(n) running time. We
442 * could turn it into O(FOUR) by only bothering to iterate over
443 * the colours mentioned in the four neighbouring squares.
446 for (c = 0; c < n; c++) {
447 int count, neighbours, runs;
450 * One of the even indices of col (representing the
451 * orthogonal neighbours of this square) must be equal to
452 * c, or else this square is not adjacent to region c and
453 * obviously cannot become an extension of it at this time.
456 for (i = 0; i < 8; i += 2)
463 * Now we know this square is adjacent to region c. The
464 * next question is, would extending it cause the region to
465 * become non-simply-connected? If so, we mustn't do it.
467 * We determine this by looking around col to see if we can
468 * find more than one separate run of colour c.
471 for (i = 0; i < 8; i++)
472 if (col[i] == c && col[(i+1) & 7] != c)
480 * This square is a possibility. Determine its effect on
481 * the region's perimeter (computed from the number of
482 * orthogonal neighbours - 1 means a perimeter increase, 3
483 * a decrease, 2 no change; 4 is impossible because the
484 * region would already not be simply connected) and we're
487 assert(neighbours > 0 && neighbours < 4);
488 count = (neighbours == 1 ? WEIGHT_INCREASED :
489 neighbours == 2 ? WEIGHT_UNCHANGED : WEIGHT_DECREASED);
492 if (index >= 0 && index < count)
503 static void genmap(int w, int h, int n, int *map, random_state *rs)
510 tmp = snewn(wh, int);
513 * Clear the map, and set up `tmp' as a list of grid indices.
515 for (i = 0; i < wh; i++) {
521 * Place the region seeds by selecting n members from `tmp'.
524 for (i = 0; i < n; i++) {
525 int j = random_upto(rs, k);
531 * Re-initialise `tmp' as a cumulative frequency table. This
532 * will store the number of possible region colours we can
533 * extend into each square.
538 * Go through the grid and set up the initial cumulative
541 for (y = 0; y < h; y++)
542 for (x = 0; x < w; x++)
543 cf_add(tmp, wh, y*w+x,
544 extend_options(w, h, n, map, x, y, -1));
547 * Now repeatedly choose a square we can extend a region into,
551 int k = random_upto(rs, tmp[0]);
556 sq = cf_whichsym(tmp, wh, k);
557 k -= cf_clookup(tmp, wh, sq);
560 colour = extend_options(w, h, n, map, x, y, k);
565 * Re-scan the nine cells around the one we've just
568 for (yy = max(y-1, 0); yy < min(y+2, h); yy++)
569 for (xx = max(x-1, 0); xx < min(x+2, w); xx++) {
570 cf_add(tmp, wh, yy*w+xx,
571 -cf_slookup(tmp, wh, yy*w+xx) +
572 extend_options(w, h, n, map, xx, yy, -1));
577 * Finally, go through and normalise the region labels into
578 * order, meaning that indistinguishable maps are actually
581 for (i = 0; i < n; i++)
584 for (i = 0; i < wh; i++) {
588 map[i] = tmp[map[i]];
594 /* ----------------------------------------------------------------------
595 * Functions to handle graphs.
599 * Having got a map in a square grid, convert it into a graph
602 static int gengraph(int w, int h, int n, int *map, int *graph)
607 * Start by setting the graph up as an adjacency matrix. We'll
608 * turn it into a list later.
610 for (i = 0; i < n*n; i++)
614 * Iterate over the map looking for all adjacencies.
616 for (y = 0; y < h; y++)
617 for (x = 0; x < w; x++) {
620 if (x+1 < w && (vx = map[y*w+(x+1)]) != v)
621 graph[v*n+vx] = graph[vx*n+v] = 1;
622 if (y+1 < h && (vy = map[(y+1)*w+x]) != v)
623 graph[v*n+vy] = graph[vy*n+v] = 1;
627 * Turn the matrix into a list.
629 for (i = j = 0; i < n*n; i++)
636 static int graph_edge_index(int *graph, int n, int ngraph, int i, int j)
643 while (top - bot > 1) {
644 mid = (top + bot) / 2;
647 else if (graph[mid] < v)
655 #define graph_adjacent(graph, n, ngraph, i, j) \
656 (graph_edge_index((graph), (n), (ngraph), (i), (j)) >= 0)
658 static int graph_vertex_start(int *graph, int n, int ngraph, int i)
665 while (top - bot > 1) {
666 mid = (top + bot) / 2;
675 /* ----------------------------------------------------------------------
676 * Generate a four-colouring of a graph.
678 * FIXME: it would be nice if we could convert this recursion into
679 * pseudo-recursion using some sort of explicit stack array, for
680 * the sake of the Palm port and its limited stack.
683 static int fourcolour_recurse(int *graph, int n, int ngraph,
684 int *colouring, int *scratch, random_state *rs)
686 int nfree, nvert, start, i, j, k, c, ci;
690 * Find the smallest number of free colours in any uncoloured
691 * vertex, and count the number of such vertices.
694 nfree = FIVE; /* start off bigger than FOUR! */
696 for (i = 0; i < n; i++)
697 if (colouring[i] < 0 && scratch[i*FIVE+FOUR] <= nfree) {
698 if (nfree > scratch[i*FIVE+FOUR]) {
699 nfree = scratch[i*FIVE+FOUR];
706 * If there aren't any uncoloured vertices at all, we're done.
709 return TRUE; /* we've got a colouring! */
712 * Pick a random vertex in that set.
714 j = random_upto(rs, nvert);
715 for (i = 0; i < n; i++)
716 if (colouring[i] < 0 && scratch[i*FIVE+FOUR] == nfree)
720 start = graph_vertex_start(graph, n, ngraph, i);
723 * Loop over the possible colours for i, and recurse for each
727 for (c = 0; c < FOUR; c++)
728 if (scratch[i*FIVE+c] == 0)
730 shuffle(cs, ci, sizeof(*cs), rs);
736 * Fill in this colour.
741 * Update the scratch space to reflect a new neighbour
742 * of this colour for each neighbour of vertex i.
744 for (j = start; j < ngraph && graph[j] < n*(i+1); j++) {
746 if (scratch[k*FIVE+c] == 0)
747 scratch[k*FIVE+FOUR]--;
754 if (fourcolour_recurse(graph, n, ngraph, colouring, scratch, rs))
755 return TRUE; /* got one! */
758 * If that didn't work, clean up and try again with a
761 for (j = start; j < ngraph && graph[j] < n*(i+1); j++) {
764 if (scratch[k*FIVE+c] == 0)
765 scratch[k*FIVE+FOUR]++;
771 * If we reach here, we were unable to find a colouring at all.
772 * (This doesn't necessarily mean the Four Colour Theorem is
773 * violated; it might just mean we've gone down a dead end and
774 * need to back up and look somewhere else. It's only an FCT
775 * violation if we get all the way back up to the top level and
781 static void fourcolour(int *graph, int n, int ngraph, int *colouring,
788 * For each vertex and each colour, we store the number of
789 * neighbours that have that colour. Also, we store the number
790 * of free colours for the vertex.
792 scratch = snewn(n * FIVE, int);
793 for (i = 0; i < n * FIVE; i++)
794 scratch[i] = (i % FIVE == FOUR ? FOUR : 0);
797 * Clear the colouring to start with.
799 for (i = 0; i < n; i++)
802 i = fourcolour_recurse(graph, n, ngraph, colouring, scratch, rs);
803 assert(i); /* by the Four Colour Theorem :-) */
808 /* ----------------------------------------------------------------------
809 * Non-recursive solver.
812 struct solver_scratch {
813 unsigned char *possible; /* bitmap of colours for each region */
821 #ifdef SOLVER_DIAGNOSTICS
828 static struct solver_scratch *new_scratch(int *graph, int n, int ngraph)
830 struct solver_scratch *sc;
832 sc = snew(struct solver_scratch);
836 sc->possible = snewn(n, unsigned char);
838 sc->bfsqueue = snewn(n, int);
839 sc->bfscolour = snewn(n, int);
840 #ifdef SOLVER_DIAGNOSTICS
841 sc->bfsprev = snewn(n, int);
847 static void free_scratch(struct solver_scratch *sc)
851 sfree(sc->bfscolour);
852 #ifdef SOLVER_DIAGNOSTICS
859 * Count the bits in a word. Only needs to cope with FOUR bits.
861 static int bitcount(int word)
863 assert(FOUR <= 4); /* or this needs changing */
864 word = ((word & 0xA) >> 1) + (word & 0x5);
865 word = ((word & 0xC) >> 2) + (word & 0x3);
869 #ifdef SOLVER_DIAGNOSTICS
870 static const char colnames[FOUR] = { 'R', 'Y', 'G', 'B' };
873 static int place_colour(struct solver_scratch *sc,
874 int *colouring, int index, int colour
875 #ifdef SOLVER_DIAGNOSTICS
880 int *graph = sc->graph, n = sc->n, ngraph = sc->ngraph;
883 if (!(sc->possible[index] & (1 << colour))) {
884 #ifdef SOLVER_DIAGNOSTICS
886 printf("%*scannot place %c in region %d\n", 2*sc->depth, "",
887 colnames[colour], index);
889 return FALSE; /* can't do it */
892 sc->possible[index] = 1 << colour;
893 colouring[index] = colour;
895 #ifdef SOLVER_DIAGNOSTICS
897 printf("%*s%s %c in region %d\n", 2*sc->depth, "",
898 verb, colnames[colour], index);
902 * Rule out this colour from all the region's neighbours.
904 for (j = graph_vertex_start(graph, n, ngraph, index);
905 j < ngraph && graph[j] < n*(index+1); j++) {
906 k = graph[j] - index*n;
907 #ifdef SOLVER_DIAGNOSTICS
908 if (verbose && (sc->possible[k] & (1 << colour)))
909 printf("%*s ruling out %c in region %d\n", 2*sc->depth, "",
910 colnames[colour], k);
912 sc->possible[k] &= ~(1 << colour);
918 #ifdef SOLVER_DIAGNOSTICS
919 static char *colourset(char *buf, int set)
925 for (i = 0; i < FOUR; i++)
926 if (set & (1 << i)) {
927 p += sprintf(p, "%s%c", sep, colnames[i]);
936 * Returns 0 for impossible, 1 for success, 2 for failure to
937 * converge (i.e. puzzle is either ambiguous or just too
940 static int map_solver(struct solver_scratch *sc,
941 int *graph, int n, int ngraph, int *colouring,
946 if (sc->depth == 0) {
948 * Initialise scratch space.
950 for (i = 0; i < n; i++)
951 sc->possible[i] = (1 << FOUR) - 1;
956 for (i = 0; i < n; i++)
957 if (colouring[i] >= 0) {
958 if (!place_colour(sc, colouring, i, colouring[i]
959 #ifdef SOLVER_DIAGNOSTICS
963 #ifdef SOLVER_DIAGNOSTICS
965 printf("%*sinitial clue set is inconsistent\n",
968 return 0; /* the clues aren't even consistent! */
974 * Now repeatedly loop until we find nothing further to do.
977 int done_something = FALSE;
979 if (difficulty < DIFF_EASY)
980 break; /* can't do anything at all! */
983 * Simplest possible deduction: find a region with only one
986 for (i = 0; i < n; i++) if (colouring[i] < 0) {
987 int p = sc->possible[i];
990 #ifdef SOLVER_DIAGNOSTICS
992 printf("%*sregion %d has no possible colours left\n",
995 return 0; /* puzzle is inconsistent */
998 if ((p & (p-1)) == 0) { /* p is a power of two */
1000 for (c = 0; c < FOUR; c++)
1004 ret = place_colour(sc, colouring, i, c
1005 #ifdef SOLVER_DIAGNOSTICS
1010 * place_colour() can only fail if colour c was not
1011 * even a _possibility_ for region i, and we're
1012 * pretty sure it was because we checked before
1013 * calling place_colour(). So we can safely assert
1014 * here rather than having to return a nice
1015 * friendly error code.
1018 done_something = TRUE;
1025 if (difficulty < DIFF_NORMAL)
1026 break; /* can't do anything harder */
1029 * Failing that, go up one level. Look for pairs of regions
1030 * which (a) both have the same pair of possible colours,
1031 * (b) are adjacent to one another, (c) are adjacent to the
1032 * same region, and (d) that region still thinks it has one
1033 * or both of those possible colours.
1035 * Simplest way to do this is by going through the graph
1036 * edge by edge, so that we start with property (b) and
1037 * then look for (a) and finally (c) and (d).
1039 for (i = 0; i < ngraph; i++) {
1040 int j1 = graph[i] / n, j2 = graph[i] % n;
1042 #ifdef SOLVER_DIAGNOSTICS
1043 int started = FALSE;
1047 continue; /* done it already, other way round */
1049 if (colouring[j1] >= 0 || colouring[j2] >= 0)
1050 continue; /* they're not undecided */
1052 if (sc->possible[j1] != sc->possible[j2])
1053 continue; /* they don't have the same possibles */
1055 v = sc->possible[j1];
1057 * See if v contains exactly two set bits.
1059 v2 = v & -v; /* find lowest set bit */
1060 v2 = v & ~v2; /* clear it */
1061 if (v2 == 0 || (v2 & (v2-1)) != 0) /* not power of 2 */
1065 * We've found regions j1 and j2 satisfying properties
1066 * (a) and (b): they have two possible colours between
1067 * them, and since they're adjacent to one another they
1068 * must use _both_ those colours between them.
1069 * Therefore, if they are both adjacent to any other
1070 * region then that region cannot be either colour.
1072 * Go through the neighbours of j1 and see if any are
1075 for (j = graph_vertex_start(graph, n, ngraph, j1);
1076 j < ngraph && graph[j] < n*(j1+1); j++) {
1077 k = graph[j] - j1*n;
1078 if (graph_adjacent(graph, n, ngraph, k, j2) &&
1079 (sc->possible[k] & v)) {
1080 #ifdef SOLVER_DIAGNOSTICS
1084 printf("%*sadjacent regions %d,%d share colours"
1085 " %s\n", 2*sc->depth, "", j1, j2,
1088 printf("%*s ruling out %s in region %d\n",2*sc->depth,
1089 "", colourset(buf, sc->possible[k] & v), k);
1092 sc->possible[k] &= ~v;
1093 done_something = TRUE;
1101 if (difficulty < DIFF_HARD)
1102 break; /* can't do anything harder */
1105 * Right; now we get creative. Now we're going to look for
1106 * `forcing chains'. A forcing chain is a path through the
1107 * graph with the following properties:
1109 * (a) Each vertex on the path has precisely two possible
1112 * (b) Each pair of vertices which are adjacent on the
1113 * path share at least one possible colour in common.
1115 * (c) Each vertex in the middle of the path shares _both_
1116 * of its colours with at least one of its neighbours
1117 * (not the same one with both neighbours).
1119 * These together imply that at least one of the possible
1120 * colour choices at one end of the path forces _all_ the
1121 * rest of the colours along the path. In order to make
1122 * real use of this, we need further properties:
1124 * (c) Ruling out some colour C from the vertex at one end
1125 * of the path forces the vertex at the other end to
1128 * (d) The two end vertices are mutually adjacent to some
1131 * (e) That third vertex currently has C as a possibility.
1133 * If we can find all of that lot, we can deduce that at
1134 * least one of the two ends of the forcing chain has
1135 * colour C, and that therefore the mutually adjacent third
1138 * To find forcing chains, we're going to start a bfs at
1139 * each suitable vertex of the graph, once for each of its
1140 * two possible colours.
1142 for (i = 0; i < n; i++) {
1145 if (colouring[i] >= 0 || bitcount(sc->possible[i]) != 2)
1148 for (c = 0; c < FOUR; c++)
1149 if (sc->possible[i] & (1 << c)) {
1150 int j, k, gi, origc, currc, head, tail;
1152 * Try a bfs from this vertex, ruling out
1155 * Within this loop, we work in colour bitmaps
1156 * rather than actual colours, because
1157 * converting back and forth is a needless
1158 * computational expense.
1163 for (j = 0; j < n; j++) {
1164 sc->bfscolour[j] = -1;
1165 #ifdef SOLVER_DIAGNOSTICS
1166 sc->bfsprev[j] = -1;
1170 sc->bfsqueue[tail++] = i;
1171 sc->bfscolour[i] = sc->possible[i] &~ origc;
1173 while (head < tail) {
1174 j = sc->bfsqueue[head++];
1175 currc = sc->bfscolour[j];
1178 * Try neighbours of j.
1180 for (gi = graph_vertex_start(graph, n, ngraph, j);
1181 gi < ngraph && graph[gi] < n*(j+1); gi++) {
1182 k = graph[gi] - j*n;
1185 * To continue with the bfs in vertex
1186 * k, we need k to be
1187 * (a) not already visited
1188 * (b) have two possible colours
1189 * (c) those colours include currc.
1192 if (sc->bfscolour[k] < 0 &&
1194 bitcount(sc->possible[k]) == 2 &&
1195 (sc->possible[k] & currc)) {
1196 sc->bfsqueue[tail++] = k;
1198 sc->possible[k] &~ currc;
1199 #ifdef SOLVER_DIAGNOSTICS
1205 * One other possibility is that k
1206 * might be the region in which we can
1207 * make a real deduction: if it's
1208 * adjacent to i, contains currc as a
1209 * possibility, and currc is equal to
1210 * the original colour we ruled out.
1212 if (currc == origc &&
1213 graph_adjacent(graph, n, ngraph, k, i) &&
1214 (sc->possible[k] & currc)) {
1215 #ifdef SOLVER_DIAGNOSTICS
1217 char buf[80], *sep = "";
1220 printf("%*sforcing chain, colour %s, ",
1222 colourset(buf, origc));
1223 for (r = j; r != -1; r = sc->bfsprev[r]) {
1224 printf("%s%d", sep, r);
1227 printf("\n%*s ruling out %s in region"
1228 " %d\n", 2*sc->depth, "",
1229 colourset(buf, origc), k);
1232 sc->possible[k] &= ~origc;
1233 done_something = TRUE;
1242 if (!done_something)
1247 * See if we've got a complete solution, and return if so.
1249 for (i = 0; i < n; i++)
1250 if (colouring[i] < 0)
1253 #ifdef SOLVER_DIAGNOSTICS
1255 printf("%*sone solution found\n", 2*sc->depth, "");
1257 return 1; /* success! */
1261 * If recursion is not permissible, we now give up.
1263 if (difficulty < DIFF_RECURSE) {
1264 #ifdef SOLVER_DIAGNOSTICS
1266 printf("%*sunable to proceed further without recursion\n",
1269 return 2; /* unable to complete */
1273 * Now we've got to do something recursive. So first hunt for a
1274 * currently-most-constrained region.
1278 struct solver_scratch *rsc;
1279 int *subcolouring, *origcolouring;
1281 int we_already_got_one;
1286 for (i = 0; i < n; i++) if (colouring[i] < 0) {
1287 int p = sc->possible[i];
1288 enum { compile_time_assertion = 1 / (FOUR <= 4) };
1291 /* Count the set bits. */
1292 c = (p & 5) + ((p >> 1) & 5);
1293 c = (c & 3) + ((c >> 2) & 3);
1294 assert(c > 1); /* or colouring[i] would be >= 0 */
1302 assert(best >= 0); /* or we'd be solved already */
1304 #ifdef SOLVER_DIAGNOSTICS
1306 printf("%*srecursing on region %d\n", 2*sc->depth, "", best);
1310 * Now iterate over the possible colours for this region.
1312 rsc = new_scratch(graph, n, ngraph);
1313 rsc->depth = sc->depth + 1;
1314 origcolouring = snewn(n, int);
1315 memcpy(origcolouring, colouring, n * sizeof(int));
1316 subcolouring = snewn(n, int);
1317 we_already_got_one = FALSE;
1320 for (i = 0; i < FOUR; i++) {
1321 if (!(sc->possible[best] & (1 << i)))
1324 memcpy(rsc->possible, sc->possible, n);
1325 memcpy(subcolouring, origcolouring, n * sizeof(int));
1327 place_colour(rsc, subcolouring, best, i
1328 #ifdef SOLVER_DIAGNOSTICS
1333 subret = map_solver(rsc, graph, n, ngraph,
1334 subcolouring, difficulty);
1336 #ifdef SOLVER_DIAGNOSTICS
1338 printf("%*sretracting %c in region %d; found %s\n",
1339 2*sc->depth, "", colnames[i], best,
1340 subret == 0 ? "no solutions" :
1341 subret == 1 ? "one solution" : "multiple solutions");
1346 * If this possibility turned up more than one valid
1347 * solution, or if it turned up one and we already had
1348 * one, we're definitely ambiguous.
1350 if (subret == 2 || (subret == 1 && we_already_got_one)) {
1356 * If this possibility turned up one valid solution and
1357 * it's the first we've seen, copy it into the output.
1360 memcpy(colouring, subcolouring, n * sizeof(int));
1361 we_already_got_one = TRUE;
1366 * Otherwise, this guess led to a contradiction, so we
1371 sfree(origcolouring);
1372 sfree(subcolouring);
1375 #ifdef SOLVER_DIAGNOSTICS
1376 if (verbose && sc->depth == 0) {
1377 printf("%*s%s found\n",
1379 ret == 0 ? "no solutions" :
1380 ret == 1 ? "one solution" : "multiple solutions");
1387 /* ----------------------------------------------------------------------
1388 * Game generation main function.
1391 static char *new_game_desc(const game_params *params, random_state *rs,
1392 char **aux, int interactive)
1394 struct solver_scratch *sc = NULL;
1395 int *map, *graph, ngraph, *colouring, *colouring2, *regions;
1396 int i, j, w, h, n, solveret, cfreq[FOUR];
1399 #ifdef GENERATION_DIAGNOSTICS
1403 int retlen, retsize;
1412 map = snewn(wh, int);
1413 graph = snewn(n*n, int);
1414 colouring = snewn(n, int);
1415 colouring2 = snewn(n, int);
1416 regions = snewn(n, int);
1419 * This is the minimum difficulty below which we'll completely
1420 * reject a map design. Normally we set this to one below the
1421 * requested difficulty, ensuring that we have the right
1422 * result. However, for particularly dense maps or maps with
1423 * particularly few regions it might not be possible to get the
1424 * desired difficulty, so we will eventually drop this down to
1425 * -1 to indicate that any old map will do.
1427 mindiff = params->diff;
1435 genmap(w, h, n, map, rs);
1437 #ifdef GENERATION_DIAGNOSTICS
1438 for (y = 0; y < h; y++) {
1439 for (x = 0; x < w; x++) {
1444 putchar('a' + v-36);
1446 putchar('A' + v-10);
1455 * Convert the map into a graph.
1457 ngraph = gengraph(w, h, n, map, graph);
1459 #ifdef GENERATION_DIAGNOSTICS
1460 for (i = 0; i < ngraph; i++)
1461 printf("%d-%d\n", graph[i]/n, graph[i]%n);
1467 fourcolour(graph, n, ngraph, colouring, rs);
1469 #ifdef GENERATION_DIAGNOSTICS
1470 for (i = 0; i < n; i++)
1471 printf("%d: %d\n", i, colouring[i]);
1473 for (y = 0; y < h; y++) {
1474 for (x = 0; x < w; x++) {
1475 int v = colouring[map[y*w+x]];
1477 putchar('a' + v-36);
1479 putchar('A' + v-10);
1488 * Encode the solution as an aux string.
1490 if (*aux) /* in case we've come round again */
1492 retlen = retsize = 0;
1494 for (i = 0; i < n; i++) {
1497 if (colouring[i] < 0)
1500 len = sprintf(buf, "%s%d:%d", i ? ";" : "S;", colouring[i], i);
1501 if (retlen + len >= retsize) {
1502 retsize = retlen + len + 256;
1503 ret = sresize(ret, retsize, char);
1505 strcpy(ret + retlen, buf);
1511 * Remove the region colours one by one, keeping
1512 * solubility. Also ensure that there always remains at
1513 * least one region of every colour, so that the user can
1514 * drag from somewhere.
1516 for (i = 0; i < FOUR; i++)
1518 for (i = 0; i < n; i++) {
1520 cfreq[colouring[i]]++;
1522 for (i = 0; i < FOUR; i++)
1526 shuffle(regions, n, sizeof(*regions), rs);
1528 if (sc) free_scratch(sc);
1529 sc = new_scratch(graph, n, ngraph);
1531 for (i = 0; i < n; i++) {
1534 if (cfreq[colouring[j]] == 1)
1535 continue; /* can't remove last region of colour */
1537 memcpy(colouring2, colouring, n*sizeof(int));
1539 solveret = map_solver(sc, graph, n, ngraph, colouring2,
1541 assert(solveret >= 0); /* mustn't be impossible! */
1542 if (solveret == 1) {
1543 cfreq[colouring[j]]--;
1548 #ifdef GENERATION_DIAGNOSTICS
1549 for (i = 0; i < n; i++)
1550 if (colouring[i] >= 0) {
1554 putchar('a' + i-36);
1556 putchar('A' + i-10);
1559 printf(": %d\n", colouring[i]);
1564 * Finally, check that the puzzle is _at least_ as hard as
1565 * required, and indeed that it isn't already solved.
1566 * (Calling map_solver with negative difficulty ensures the
1567 * latter - if a solver which _does nothing_ can solve it,
1570 memcpy(colouring2, colouring, n*sizeof(int));
1571 if (map_solver(sc, graph, n, ngraph, colouring2,
1572 mindiff - 1) == 1) {
1574 * Drop minimum difficulty if necessary.
1576 if (mindiff > 0 && (n < 9 || n > 2*wh/3)) {
1578 mindiff = 0; /* give up and go for Easy */
1587 * Encode as a game ID. We do this by:
1589 * - first going along the horizontal edges row by row, and
1590 * then the vertical edges column by column
1591 * - encoding the lengths of runs of edges and runs of
1593 * - the decoder will reconstitute the region boundaries from
1594 * this and automatically number them the same way we did
1595 * - then we encode the initial region colours in a Slant-like
1596 * fashion (digits 0-3 interspersed with letters giving
1597 * lengths of runs of empty spaces).
1599 retlen = retsize = 0;
1606 * Start with a notional non-edge, so that there'll be an
1607 * explicit `a' to distinguish the case where we start with
1613 for (i = 0; i < w*(h-1) + (w-1)*h; i++) {
1614 int x, y, dx, dy, v;
1617 /* Horizontal edge. */
1623 /* Vertical edge. */
1624 x = (i - w*(h-1)) / h;
1625 y = (i - w*(h-1)) % h;
1630 if (retlen + 10 >= retsize) {
1631 retsize = retlen + 256;
1632 ret = sresize(ret, retsize, char);
1635 v = (map[y*w+x] != map[(y+dy)*w+(x+dx)]);
1638 ret[retlen++] = 'a'-1 + run;
1643 * 'z' is a special case in this encoding. Rather
1644 * than meaning a run of 26 and a state switch, it
1645 * means a run of 25 and _no_ state switch, because
1646 * otherwise there'd be no way to encode runs of
1650 ret[retlen++] = 'z';
1657 ret[retlen++] = 'a'-1 + run;
1658 ret[retlen++] = ',';
1661 for (i = 0; i < n; i++) {
1662 if (retlen + 10 >= retsize) {
1663 retsize = retlen + 256;
1664 ret = sresize(ret, retsize, char);
1667 if (colouring[i] < 0) {
1669 * In _this_ encoding, 'z' is a run of 26, since
1670 * there's no implicit state switch after each run.
1671 * Confusingly different, but more compact.
1674 ret[retlen++] = 'z';
1680 ret[retlen++] = 'a'-1 + run;
1681 ret[retlen++] = '0' + colouring[i];
1686 ret[retlen++] = 'a'-1 + run;
1689 assert(retlen < retsize);
1702 static char *parse_edge_list(const game_params *params, const char **desc,
1705 int w = params->w, h = params->h, wh = w*h, n = params->n;
1706 int i, k, pos, state;
1707 const char *p = *desc;
1709 dsf_init(map+wh, wh);
1715 * Parse the game description to get the list of edges, and
1716 * build up a disjoint set forest as we go (by identifying
1717 * pairs of squares whenever the edge list shows a non-edge).
1719 while (*p && *p != ',') {
1720 if (*p < 'a' || *p > 'z')
1721 return "Unexpected character in edge list";
1732 } else if (pos < w*(h-1)) {
1733 /* Horizontal edge. */
1738 } else if (pos < 2*wh-w-h) {
1739 /* Vertical edge. */
1740 x = (pos - w*(h-1)) / h;
1741 y = (pos - w*(h-1)) % h;
1745 return "Too much data in edge list";
1747 dsf_merge(map+wh, y*w+x, (y+dy)*w+(x+dx));
1755 assert(pos <= 2*wh-w-h);
1757 return "Too little data in edge list";
1760 * Now go through again and allocate region numbers.
1763 for (i = 0; i < wh; i++)
1765 for (i = 0; i < wh; i++) {
1766 k = dsf_canonify(map+wh, i);
1772 return "Edge list defines the wrong number of regions";
1779 static const char *validate_desc(const game_params *params, const char *desc)
1781 int w = params->w, h = params->h, wh = w*h, n = params->n;
1786 map = snewn(2*wh, int);
1787 ret = parse_edge_list(params, &desc, map);
1793 return "Expected comma before clue list";
1794 desc++; /* eat comma */
1798 if (*desc >= '0' && *desc < '0'+FOUR)
1800 else if (*desc >= 'a' && *desc <= 'z')
1801 area += *desc - 'a' + 1;
1803 return "Unexpected character in clue list";
1807 return "Too little data in clue list";
1809 return "Too much data in clue list";
1814 static game_state *new_game(midend *me, const game_params *params,
1817 int w = params->w, h = params->h, wh = w*h, n = params->n;
1820 game_state *state = snew(game_state);
1823 state->colouring = snewn(n, int);
1824 for (i = 0; i < n; i++)
1825 state->colouring[i] = -1;
1826 state->pencil = snewn(n, int);
1827 for (i = 0; i < n; i++)
1828 state->pencil[i] = 0;
1830 state->completed = state->cheated = FALSE;
1832 state->map = snew(struct map);
1833 state->map->refcount = 1;
1834 state->map->map = snewn(wh*4, int);
1835 state->map->graph = snewn(n*n, int);
1837 state->map->immutable = snewn(n, int);
1838 for (i = 0; i < n; i++)
1839 state->map->immutable[i] = FALSE;
1845 ret = parse_edge_list(params, &p, state->map->map);
1850 * Set up the other three quadrants in `map'.
1852 for (i = wh; i < 4*wh; i++)
1853 state->map->map[i] = state->map->map[i % wh];
1859 * Now process the clue list.
1863 if (*p >= '0' && *p < '0'+FOUR) {
1864 state->colouring[pos] = *p - '0';
1865 state->map->immutable[pos] = TRUE;
1868 assert(*p >= 'a' && *p <= 'z');
1869 pos += *p - 'a' + 1;
1875 state->map->ngraph = gengraph(w, h, n, state->map->map, state->map->graph);
1878 * Attempt to smooth out some of the more jagged region
1879 * outlines by the judicious use of diagonally divided squares.
1882 random_state *rs = random_new(desc, strlen(desc));
1883 int *squares = snewn(wh, int);
1886 for (i = 0; i < wh; i++)
1888 shuffle(squares, wh, sizeof(*squares), rs);
1891 done_something = FALSE;
1892 for (i = 0; i < wh; i++) {
1893 int y = squares[i] / w, x = squares[i] % w;
1894 int c = state->map->map[y*w+x];
1897 if (x == 0 || x == w-1 || y == 0 || y == h-1)
1900 if (state->map->map[TE * wh + y*w+x] !=
1901 state->map->map[BE * wh + y*w+x])
1904 tc = state->map->map[BE * wh + (y-1)*w+x];
1905 bc = state->map->map[TE * wh + (y+1)*w+x];
1906 lc = state->map->map[RE * wh + y*w+(x-1)];
1907 rc = state->map->map[LE * wh + y*w+(x+1)];
1910 * If this square is adjacent on two sides to one
1911 * region and on the other two sides to the other
1912 * region, and is itself one of the two regions, we can
1913 * adjust it so that it's a diagonal.
1915 if (tc != bc && (tc == c || bc == c)) {
1916 if ((lc == tc && rc == bc) ||
1917 (lc == bc && rc == tc)) {
1918 state->map->map[TE * wh + y*w+x] = tc;
1919 state->map->map[BE * wh + y*w+x] = bc;
1920 state->map->map[LE * wh + y*w+x] = lc;
1921 state->map->map[RE * wh + y*w+x] = rc;
1922 done_something = TRUE;
1926 } while (done_something);
1932 * Analyse the map to find a canonical line segment
1933 * corresponding to each edge, and a canonical point
1934 * corresponding to each region. The former are where we'll
1935 * eventually put error markers; the latter are where we'll put
1936 * per-region flags such as numbers (when in diagnostic mode).
1939 int *bestx, *besty, *an, pass;
1940 float *ax, *ay, *best;
1942 ax = snewn(state->map->ngraph + n, float);
1943 ay = snewn(state->map->ngraph + n, float);
1944 an = snewn(state->map->ngraph + n, int);
1945 bestx = snewn(state->map->ngraph + n, int);
1946 besty = snewn(state->map->ngraph + n, int);
1947 best = snewn(state->map->ngraph + n, float);
1949 for (i = 0; i < state->map->ngraph + n; i++) {
1950 bestx[i] = besty[i] = -1;
1951 best[i] = (float)(2*(w+h)+1);
1952 ax[i] = ay[i] = 0.0F;
1957 * We make two passes over the map, finding all the line
1958 * segments separating regions and all the suitable points
1959 * within regions. In the first pass, we compute the
1960 * _average_ x and y coordinate of all the points in a
1961 * given class; in the second pass, for each such average
1962 * point, we find the candidate closest to it and call that
1965 * Line segments are considered to have coordinates in
1966 * their centre. Thus, at least one coordinate for any line
1967 * segment is always something-and-a-half; so we store our
1968 * coordinates as twice their normal value.
1970 for (pass = 0; pass < 2; pass++) {
1973 for (y = 0; y < h; y++)
1974 for (x = 0; x < w; x++) {
1975 int ex[4], ey[4], ea[4], eb[4], en = 0;
1978 * Look for an edge to the right of this
1979 * square, an edge below it, and an edge in the
1980 * middle of it. Also look to see if the point
1981 * at the bottom right of this square is on an
1982 * edge (and isn't a place where more than two
1987 ea[en] = state->map->map[RE * wh + y*w+x];
1988 eb[en] = state->map->map[LE * wh + y*w+(x+1)];
1995 ea[en] = state->map->map[BE * wh + y*w+x];
1996 eb[en] = state->map->map[TE * wh + (y+1)*w+x];
2002 ea[en] = state->map->map[TE * wh + y*w+x];
2003 eb[en] = state->map->map[BE * wh + y*w+x];
2008 if (x+1 < w && y+1 < h) {
2009 /* bottom right corner */
2010 int oct[8], othercol, nchanges;
2011 oct[0] = state->map->map[RE * wh + y*w+x];
2012 oct[1] = state->map->map[LE * wh + y*w+(x+1)];
2013 oct[2] = state->map->map[BE * wh + y*w+(x+1)];
2014 oct[3] = state->map->map[TE * wh + (y+1)*w+(x+1)];
2015 oct[4] = state->map->map[LE * wh + (y+1)*w+(x+1)];
2016 oct[5] = state->map->map[RE * wh + (y+1)*w+x];
2017 oct[6] = state->map->map[TE * wh + (y+1)*w+x];
2018 oct[7] = state->map->map[BE * wh + y*w+x];
2022 for (i = 0; i < 8; i++) {
2023 if (oct[i] != oct[0]) {
2026 else if (othercol != oct[i])
2027 break; /* three colours at this point */
2029 if (oct[i] != oct[(i+1) & 7])
2034 * Now if there are exactly two regions at
2035 * this point (not one, and not three or
2036 * more), and only two changes around the
2037 * loop, then this is a valid place to put
2040 if (i == 8 && othercol >= 0 && nchanges == 2) {
2049 * If there's exactly _one_ region at this
2050 * point, on the other hand, it's a valid
2051 * place to put a region centre.
2054 ea[en] = eb[en] = oct[0];
2062 * Now process the points we've found, one by
2065 for (i = 0; i < en; i++) {
2066 int emin = min(ea[i], eb[i]);
2067 int emax = max(ea[i], eb[i]);
2073 graph_edge_index(state->map->graph, n,
2074 state->map->ngraph, emin,
2078 gindex = state->map->ngraph + emin;
2081 assert(gindex >= 0);
2085 * In pass 0, accumulate the values
2086 * we'll use to compute the average
2089 ax[gindex] += ex[i];
2090 ay[gindex] += ey[i];
2094 * In pass 1, work out whether this
2095 * point is closer to the average than
2096 * the last one we've seen.
2100 assert(an[gindex] > 0);
2101 dx = ex[i] - ax[gindex];
2102 dy = ey[i] - ay[gindex];
2103 d = (float)sqrt(dx*dx + dy*dy);
2104 if (d < best[gindex]) {
2106 bestx[gindex] = ex[i];
2107 besty[gindex] = ey[i];
2114 for (i = 0; i < state->map->ngraph + n; i++)
2122 state->map->edgex = snewn(state->map->ngraph, int);
2123 state->map->edgey = snewn(state->map->ngraph, int);
2124 memcpy(state->map->edgex, bestx, state->map->ngraph * sizeof(int));
2125 memcpy(state->map->edgey, besty, state->map->ngraph * sizeof(int));
2127 state->map->regionx = snewn(n, int);
2128 state->map->regiony = snewn(n, int);
2129 memcpy(state->map->regionx, bestx + state->map->ngraph, n*sizeof(int));
2130 memcpy(state->map->regiony, besty + state->map->ngraph, n*sizeof(int));
2132 for (i = 0; i < state->map->ngraph; i++)
2133 if (state->map->edgex[i] < 0) {
2134 /* Find the other representation of this edge. */
2135 int e = state->map->graph[i];
2136 int iprime = graph_edge_index(state->map->graph, n,
2137 state->map->ngraph, e%n, e/n);
2138 assert(state->map->edgex[iprime] >= 0);
2139 state->map->edgex[i] = state->map->edgex[iprime];
2140 state->map->edgey[i] = state->map->edgey[iprime];
2154 static game_state *dup_game(const game_state *state)
2156 game_state *ret = snew(game_state);
2159 ret->colouring = snewn(state->p.n, int);
2160 memcpy(ret->colouring, state->colouring, state->p.n * sizeof(int));
2161 ret->pencil = snewn(state->p.n, int);
2162 memcpy(ret->pencil, state->pencil, state->p.n * sizeof(int));
2163 ret->map = state->map;
2164 ret->map->refcount++;
2165 ret->completed = state->completed;
2166 ret->cheated = state->cheated;
2171 static void free_game(game_state *state)
2173 if (--state->map->refcount <= 0) {
2174 sfree(state->map->map);
2175 sfree(state->map->graph);
2176 sfree(state->map->immutable);
2177 sfree(state->map->edgex);
2178 sfree(state->map->edgey);
2179 sfree(state->map->regionx);
2180 sfree(state->map->regiony);
2183 sfree(state->pencil);
2184 sfree(state->colouring);
2188 static char *solve_game(const game_state *state, const game_state *currstate,
2189 const char *aux, const char **error)
2196 struct solver_scratch *sc;
2200 int retlen, retsize;
2202 colouring = snewn(state->map->n, int);
2203 memcpy(colouring, state->colouring, state->map->n * sizeof(int));
2205 sc = new_scratch(state->map->graph, state->map->n, state->map->ngraph);
2206 sret = map_solver(sc, state->map->graph, state->map->n,
2207 state->map->ngraph, colouring, DIFFCOUNT-1);
2213 *error = "Puzzle is inconsistent";
2215 *error = "Unable to find a unique solution for this puzzle";
2220 ret = snewn(retsize, char);
2224 for (i = 0; i < state->map->n; i++) {
2227 assert(colouring[i] >= 0);
2228 if (colouring[i] == currstate->colouring[i])
2230 assert(!state->map->immutable[i]);
2232 len = sprintf(buf, ";%d:%d", colouring[i], i);
2233 if (retlen + len >= retsize) {
2234 retsize = retlen + len + 256;
2235 ret = sresize(ret, retsize, char);
2237 strcpy(ret + retlen, buf);
2248 static int game_can_format_as_text_now(const game_params *params)
2253 static char *game_text_format(const game_state *state)
2262 * - -2 means no drag currently active.
2263 * - >=0 means we're dragging a solid colour.
2264 * - -1 means we're dragging a blank space, and drag_pencil
2265 * might or might not add some pencil-mark stipples to that.
2272 int cur_x, cur_y, cur_visible, cur_moved, cur_lastmove;
2275 static game_ui *new_ui(const game_state *state)
2277 game_ui *ui = snew(game_ui);
2278 ui->dragx = ui->dragy = -1;
2279 ui->drag_colour = -2;
2280 ui->drag_pencil = 0;
2281 ui->show_numbers = FALSE;
2282 ui->cur_x = ui->cur_y = ui->cur_visible = ui->cur_moved = 0;
2283 ui->cur_lastmove = 0;
2287 static void free_ui(game_ui *ui)
2292 static char *encode_ui(const game_ui *ui)
2297 static void decode_ui(game_ui *ui, const char *encoding)
2301 static void game_changed_state(game_ui *ui, const game_state *oldstate,
2302 const game_state *newstate)
2306 struct game_drawstate {
2308 unsigned long *drawn, *todraw;
2310 int dragx, dragy, drag_visible;
2314 /* Flags in `drawn'. */
2315 #define ERR_BASE 0x00800000L
2316 #define ERR_MASK 0xFF800000L
2317 #define PENCIL_T_BASE 0x00080000L
2318 #define PENCIL_T_MASK 0x00780000L
2319 #define PENCIL_B_BASE 0x00008000L
2320 #define PENCIL_B_MASK 0x00078000L
2321 #define PENCIL_MASK 0x007F8000L
2322 #define SHOW_NUMBERS 0x00004000L
2324 #define TILESIZE (ds->tilesize)
2325 #define BORDER (TILESIZE)
2326 #define COORD(x) ( (x) * TILESIZE + BORDER )
2327 #define FROMCOORD(x) ( ((x) - BORDER + TILESIZE) / TILESIZE - 1 )
2330 * EPSILON_FOO are epsilons added to absolute cursor position by
2331 * cursor movement, such that in pathological cases (e.g. a very
2332 * small diamond-shaped area) it's relatively easy to select the
2333 * region you wanted.
2336 #define EPSILON_X(button) (((button) == CURSOR_RIGHT) ? +1 : \
2337 ((button) == CURSOR_LEFT) ? -1 : 0)
2338 #define EPSILON_Y(button) (((button) == CURSOR_DOWN) ? +1 : \
2339 ((button) == CURSOR_UP) ? -1 : 0)
2342 static int region_from_coords(const game_state *state,
2343 const game_drawstate *ds, int x, int y)
2345 int w = state->p.w, h = state->p.h, wh = w*h /*, n = state->p.n */;
2346 int tx = FROMCOORD(x), ty = FROMCOORD(y);
2347 int dx = x - COORD(tx), dy = y - COORD(ty);
2350 if (tx < 0 || tx >= w || ty < 0 || ty >= h)
2351 return -1; /* border */
2353 quadrant = 2 * (dx > dy) + (TILESIZE - dx > dy);
2354 quadrant = (quadrant == 0 ? BE :
2355 quadrant == 1 ? LE :
2356 quadrant == 2 ? RE : TE);
2358 return state->map->map[quadrant * wh + ty*w+tx];
2361 static char *interpret_move(const game_state *state, game_ui *ui,
2362 const game_drawstate *ds,
2363 int x, int y, int button)
2365 char *bufp, buf[256];
2369 * Enable or disable numeric labels on regions.
2371 if (button == 'l' || button == 'L') {
2372 ui->show_numbers = !ui->show_numbers;
2376 if (IS_CURSOR_MOVE(button)) {
2377 move_cursor(button, &ui->cur_x, &ui->cur_y, state->p.w, state->p.h, 0);
2378 ui->cur_visible = 1;
2380 ui->cur_lastmove = button;
2381 ui->dragx = COORD(ui->cur_x) + TILESIZE/2 + EPSILON_X(button);
2382 ui->dragy = COORD(ui->cur_y) + TILESIZE/2 + EPSILON_Y(button);
2385 if (IS_CURSOR_SELECT(button)) {
2386 if (!ui->cur_visible) {
2387 ui->dragx = COORD(ui->cur_x) + TILESIZE/2 + EPSILON_X(ui->cur_lastmove);
2388 ui->dragy = COORD(ui->cur_y) + TILESIZE/2 + EPSILON_Y(ui->cur_lastmove);
2389 ui->cur_visible = 1;
2392 if (ui->drag_colour == -2) { /* not currently cursor-dragging, start. */
2393 int r = region_from_coords(state, ds, ui->dragx, ui->dragy);
2395 ui->drag_colour = state->colouring[r];
2396 ui->drag_pencil = (ui->drag_colour >= 0) ? 0 : state->pencil[r];
2398 ui->drag_colour = -1;
2399 ui->drag_pencil = 0;
2403 } else { /* currently cursor-dragging; drop the colour in the new region. */
2404 x = COORD(ui->cur_x) + TILESIZE/2 + EPSILON_X(ui->cur_lastmove);
2405 y = COORD(ui->cur_y) + TILESIZE/2 + EPSILON_Y(ui->cur_lastmove);
2406 alt_button = (button == CURSOR_SELECT2) ? 1 : 0;
2407 /* Double-select removes current colour. */
2408 if (!ui->cur_moved) ui->drag_colour = -1;
2413 if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
2414 int r = region_from_coords(state, ds, x, y);
2417 ui->drag_colour = state->colouring[r];
2418 ui->drag_pencil = state->pencil[r];
2419 if (ui->drag_colour >= 0)
2420 ui->drag_pencil = 0; /* should be already, but double-check */
2422 ui->drag_colour = -1;
2423 ui->drag_pencil = 0;
2427 ui->cur_visible = 0;
2431 if ((button == LEFT_DRAG || button == RIGHT_DRAG) &&
2432 ui->drag_colour > -2) {
2438 if ((button == LEFT_RELEASE || button == RIGHT_RELEASE) &&
2439 ui->drag_colour > -2) {
2440 alt_button = (button == RIGHT_RELEASE) ? 1 : 0;
2448 int r = region_from_coords(state, ds, x, y);
2449 int c = ui->drag_colour;
2450 int p = ui->drag_pencil;
2454 * Cancel the drag, whatever happens.
2456 ui->drag_colour = -2;
2459 return UI_UPDATE; /* drag into border; do nothing else */
2461 if (state->map->immutable[r])
2462 return UI_UPDATE; /* can't change this region */
2464 if (state->colouring[r] == c && state->pencil[r] == p)
2465 return UI_UPDATE; /* don't _need_ to change this region */
2468 if (state->colouring[r] >= 0) {
2469 /* Can't pencil on a coloured region */
2471 } else if (c >= 0) {
2472 /* Right-dragging from colour to blank toggles one pencil */
2473 p = state->pencil[r] ^ (1 << c);
2476 /* Otherwise, right-dragging from blank to blank is equivalent
2477 * to left-dragging. */
2481 oldp = state->pencil[r];
2482 if (c != state->colouring[r]) {
2483 bufp += sprintf(bufp, ";%c:%d", (int)(c < 0 ? 'C' : '0' + c), r);
2489 for (i = 0; i < FOUR; i++)
2490 if ((oldp ^ p) & (1 << i))
2491 bufp += sprintf(bufp, ";p%c:%d", (int)('0' + i), r);
2494 return dupstr(buf+1); /* ignore first semicolon */
2498 static game_state *execute_move(const game_state *state, const char *move)
2501 game_state *ret = dup_game(state);
2512 if ((c == 'C' || (c >= '0' && c < '0'+FOUR)) &&
2513 sscanf(move+1, ":%d%n", &k, &adv) == 1 &&
2514 k >= 0 && k < state->p.n) {
2517 if (ret->colouring[k] >= 0) {
2524 ret->pencil[k] ^= 1 << (c - '0');
2526 ret->colouring[k] = (c == 'C' ? -1 : c - '0');
2529 } else if (*move == 'S') {
2531 ret->cheated = TRUE;
2537 if (*move && *move != ';') {
2546 * Check for completion.
2548 if (!ret->completed) {
2551 for (i = 0; i < n; i++)
2552 if (ret->colouring[i] < 0) {
2558 for (i = 0; i < ret->map->ngraph; i++) {
2559 int j = ret->map->graph[i] / n;
2560 int k = ret->map->graph[i] % n;
2561 if (ret->colouring[j] == ret->colouring[k]) {
2569 ret->completed = TRUE;
2575 /* ----------------------------------------------------------------------
2579 static void game_compute_size(const game_params *params, int tilesize,
2582 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2583 struct { int tilesize; } ads, *ds = &ads;
2584 ads.tilesize = tilesize;
2586 *x = params->w * TILESIZE + 2 * BORDER + 1;
2587 *y = params->h * TILESIZE + 2 * BORDER + 1;
2590 static void game_set_size(drawing *dr, game_drawstate *ds,
2591 const game_params *params, int tilesize)
2593 ds->tilesize = tilesize;
2595 assert(!ds->bl); /* set_size is never called twice */
2596 ds->bl = blitter_new(dr, TILESIZE+3, TILESIZE+3);
2599 const float map_colours[FOUR][3] = {
2600 #ifdef VIVID_COLOURS
2601 /* Use more vivid colours (e.g. on the Pocket PC) */
2602 {0.75F, 0.25F, 0.25F},
2605 {0.85F, 0.85F, 0.1F},
2610 {0.55F, 0.45F, 0.35F},
2613 const int map_hatching[FOUR] = {
2614 HATCH_VERT, HATCH_SLASH, HATCH_HORIZ, HATCH_BACKSLASH
2617 static float *game_colours(frontend *fe, int *ncolours)
2619 float *ret = snewn(3 * NCOLOURS, float);
2621 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2623 ret[COL_GRID * 3 + 0] = 0.0F;
2624 ret[COL_GRID * 3 + 1] = 0.0F;
2625 ret[COL_GRID * 3 + 2] = 0.0F;
2627 memcpy(ret + COL_0 * 3, map_colours[0], 3 * sizeof(float));
2628 memcpy(ret + COL_1 * 3, map_colours[1], 3 * sizeof(float));
2629 memcpy(ret + COL_2 * 3, map_colours[2], 3 * sizeof(float));
2630 memcpy(ret + COL_3 * 3, map_colours[3], 3 * sizeof(float));
2632 ret[COL_ERROR * 3 + 0] = 1.0F;
2633 ret[COL_ERROR * 3 + 1] = 0.0F;
2634 ret[COL_ERROR * 3 + 2] = 0.0F;
2636 ret[COL_ERRTEXT * 3 + 0] = 1.0F;
2637 ret[COL_ERRTEXT * 3 + 1] = 1.0F;
2638 ret[COL_ERRTEXT * 3 + 2] = 1.0F;
2640 *ncolours = NCOLOURS;
2644 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
2646 struct game_drawstate *ds = snew(struct game_drawstate);
2650 ds->drawn = snewn(state->p.w * state->p.h, unsigned long);
2651 for (i = 0; i < state->p.w * state->p.h; i++)
2652 ds->drawn[i] = 0xFFFFL;
2653 ds->todraw = snewn(state->p.w * state->p.h, unsigned long);
2654 ds->started = FALSE;
2656 ds->drag_visible = FALSE;
2657 ds->dragx = ds->dragy = -1;
2662 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2667 blitter_free(dr, ds->bl);
2671 static void draw_error(drawing *dr, game_drawstate *ds, int x, int y)
2679 coords[0] = x - TILESIZE*2/5;
2682 coords[3] = y - TILESIZE*2/5;
2683 coords[4] = x + TILESIZE*2/5;
2686 coords[7] = y + TILESIZE*2/5;
2687 draw_polygon(dr, coords, 4, COL_ERROR, COL_GRID);
2690 * Draw an exclamation mark in the diamond. This turns out to
2691 * look unpleasantly off-centre if done via draw_text, so I do
2692 * it by hand on the basis that exclamation marks aren't that
2693 * difficult to draw...
2696 yext = TILESIZE*2/5 - (xext*2+2);
2697 draw_rect(dr, x-xext, y-yext, xext*2+1, yext*2+1 - (xext*3),
2699 draw_rect(dr, x-xext, y+yext-xext*2+1, xext*2+1, xext*2, COL_ERRTEXT);
2702 static void draw_square(drawing *dr, game_drawstate *ds,
2703 const game_params *params, struct map *map,
2704 int x, int y, unsigned long v)
2706 int w = params->w, h = params->h, wh = w*h;
2707 int tv, bv, xo, yo, i, j, oldj;
2708 unsigned long errs, pencil, show_numbers;
2710 errs = v & ERR_MASK;
2712 pencil = v & PENCIL_MASK;
2714 show_numbers = v & SHOW_NUMBERS;
2719 clip(dr, COORD(x), COORD(y), TILESIZE, TILESIZE);
2722 * Draw the region colour.
2724 draw_rect(dr, COORD(x), COORD(y), TILESIZE, TILESIZE,
2725 (tv == FOUR ? COL_BACKGROUND : COL_0 + tv));
2727 * Draw the second region colour, if this is a diagonally
2730 if (map->map[TE * wh + y*w+x] != map->map[BE * wh + y*w+x]) {
2732 coords[0] = COORD(x)-1;
2733 coords[1] = COORD(y+1)+1;
2734 if (map->map[LE * wh + y*w+x] == map->map[TE * wh + y*w+x])
2735 coords[2] = COORD(x+1)+1;
2737 coords[2] = COORD(x)-1;
2738 coords[3] = COORD(y)-1;
2739 coords[4] = COORD(x+1)+1;
2740 coords[5] = COORD(y+1)+1;
2741 draw_polygon(dr, coords, 3,
2742 (bv == FOUR ? COL_BACKGROUND : COL_0 + bv), COL_GRID);
2746 * Draw `pencil marks'. Currently we arrange these in a square
2747 * formation, which means we may be in trouble if the value of
2748 * FOUR changes later...
2751 for (yo = 0; yo < 4; yo++)
2752 for (xo = 0; xo < 4; xo++) {
2753 int te = map->map[TE * wh + y*w+x];
2756 e = (yo < xo && yo < 3-xo ? TE :
2757 yo > xo && yo > 3-xo ? BE :
2759 ee = map->map[e * wh + y*w+x];
2761 if (xo != (yo * 2 + 1) % 5)
2765 if (!(pencil & ((ee == te ? PENCIL_T_BASE : PENCIL_B_BASE) << c)))
2769 (map->map[TE * wh + y*w+x] != map->map[LE * wh + y*w+x]))
2770 continue; /* avoid TL-BR diagonal line */
2772 (map->map[TE * wh + y*w+x] != map->map[RE * wh + y*w+x]))
2773 continue; /* avoid BL-TR diagonal line */
2775 draw_circle(dr, COORD(x) + (xo+1)*TILESIZE/5,
2776 COORD(y) + (yo+1)*TILESIZE/5,
2777 TILESIZE/7, COL_0 + c, COL_0 + c);
2781 * Draw the grid lines, if required.
2783 if (x <= 0 || map->map[RE*wh+y*w+(x-1)] != map->map[LE*wh+y*w+x])
2784 draw_rect(dr, COORD(x), COORD(y), 1, TILESIZE, COL_GRID);
2785 if (y <= 0 || map->map[BE*wh+(y-1)*w+x] != map->map[TE*wh+y*w+x])
2786 draw_rect(dr, COORD(x), COORD(y), TILESIZE, 1, COL_GRID);
2787 if (x <= 0 || y <= 0 ||
2788 map->map[RE*wh+(y-1)*w+(x-1)] != map->map[TE*wh+y*w+x] ||
2789 map->map[BE*wh+(y-1)*w+(x-1)] != map->map[LE*wh+y*w+x])
2790 draw_rect(dr, COORD(x), COORD(y), 1, 1, COL_GRID);
2793 * Draw error markers.
2795 for (yo = 0; yo < 3; yo++)
2796 for (xo = 0; xo < 3; xo++)
2797 if (errs & (ERR_BASE << (yo*3+xo)))
2799 (COORD(x)*2+TILESIZE*xo)/2,
2800 (COORD(y)*2+TILESIZE*yo)/2);
2803 * Draw region numbers, if desired.
2807 for (i = 0; i < 2; i++) {
2808 j = map->map[(i?BE:TE)*wh+y*w+x];
2813 xo = map->regionx[j] - 2*x;
2814 yo = map->regiony[j] - 2*y;
2815 if (xo >= 0 && xo <= 2 && yo >= 0 && yo <= 2) {
2817 sprintf(buf, "%d", j);
2818 draw_text(dr, (COORD(x)*2+TILESIZE*xo)/2,
2819 (COORD(y)*2+TILESIZE*yo)/2,
2820 FONT_VARIABLE, 3*TILESIZE/5,
2821 ALIGN_HCENTRE|ALIGN_VCENTRE,
2829 draw_update(dr, COORD(x), COORD(y), TILESIZE, TILESIZE);
2832 static void game_redraw(drawing *dr, game_drawstate *ds,
2833 const game_state *oldstate, const game_state *state,
2834 int dir, const game_ui *ui,
2835 float animtime, float flashtime)
2837 int w = state->p.w, h = state->p.h, wh = w*h, n = state->p.n;
2841 if (ds->drag_visible) {
2842 blitter_load(dr, ds->bl, ds->dragx, ds->dragy);
2843 draw_update(dr, ds->dragx, ds->dragy, TILESIZE + 3, TILESIZE + 3);
2844 ds->drag_visible = FALSE;
2848 * The initial contents of the window are not guaranteed and
2849 * can vary with front ends. To be on the safe side, all games
2850 * should start by drawing a big background-colour rectangle
2851 * covering the whole window.
2856 game_compute_size(&state->p, TILESIZE, &ww, &wh);
2857 draw_rect(dr, 0, 0, ww, wh, COL_BACKGROUND);
2858 draw_rect(dr, COORD(0), COORD(0), w*TILESIZE+1, h*TILESIZE+1,
2861 draw_update(dr, 0, 0, ww, wh);
2866 if (flash_type == 1)
2867 flash = (int)(flashtime * FOUR / flash_length);
2869 flash = 1 + (int)(flashtime * THREE / flash_length);
2874 * Set up the `todraw' array.
2876 for (y = 0; y < h; y++)
2877 for (x = 0; x < w; x++) {
2878 int tv = state->colouring[state->map->map[TE * wh + y*w+x]];
2879 int bv = state->colouring[state->map->map[BE * wh + y*w+x]];
2888 if (flash_type == 1) {
2893 } else if (flash_type == 2) {
2898 tv = (tv + flash) % FOUR;
2900 bv = (bv + flash) % FOUR;
2909 for (i = 0; i < FOUR; i++) {
2910 if (state->colouring[state->map->map[TE * wh + y*w+x]] < 0 &&
2911 (state->pencil[state->map->map[TE * wh + y*w+x]] & (1<<i)))
2912 v |= PENCIL_T_BASE << i;
2913 if (state->colouring[state->map->map[BE * wh + y*w+x]] < 0 &&
2914 (state->pencil[state->map->map[BE * wh + y*w+x]] & (1<<i)))
2915 v |= PENCIL_B_BASE << i;
2918 if (ui->show_numbers)
2921 ds->todraw[y*w+x] = v;
2925 * Add error markers to the `todraw' array.
2927 for (i = 0; i < state->map->ngraph; i++) {
2928 int v1 = state->map->graph[i] / n;
2929 int v2 = state->map->graph[i] % n;
2932 if (state->colouring[v1] < 0 || state->colouring[v2] < 0)
2934 if (state->colouring[v1] != state->colouring[v2])
2937 x = state->map->edgex[i];
2938 y = state->map->edgey[i];
2943 ds->todraw[y*w+x] |= ERR_BASE << (yo*3+xo);
2946 ds->todraw[y*w+(x-1)] |= ERR_BASE << (yo*3+2);
2950 ds->todraw[(y-1)*w+x] |= ERR_BASE << (2*3+xo);
2952 if (xo == 0 && yo == 0) {
2953 assert(x > 0 && y > 0);
2954 ds->todraw[(y-1)*w+(x-1)] |= ERR_BASE << (2*3+2);
2959 * Now actually draw everything.
2961 for (y = 0; y < h; y++)
2962 for (x = 0; x < w; x++) {
2963 unsigned long v = ds->todraw[y*w+x];
2964 if (ds->drawn[y*w+x] != v) {
2965 draw_square(dr, ds, &state->p, state->map, x, y, v);
2966 ds->drawn[y*w+x] = v;
2971 * Draw the dragged colour blob if any.
2973 if ((ui->drag_colour > -2) || ui->cur_visible) {
2975 if (ui->drag_colour >= 0)
2976 bg = COL_0 + ui->drag_colour;
2977 else if (ui->drag_colour == -1) {
2978 bg = COL_BACKGROUND;
2980 int r = region_from_coords(state, ds, ui->dragx, ui->dragy);
2981 int c = (r < 0) ? -1 : state->colouring[r];
2982 assert(ui->cur_visible);
2984 bg = (c < 0) ? COL_BACKGROUND : COL_0 + c;
2988 ds->dragx = ui->dragx - TILESIZE/2 - 2;
2989 ds->dragy = ui->dragy - TILESIZE/2 - 2;
2990 blitter_save(dr, ds->bl, ds->dragx, ds->dragy);
2991 draw_circle(dr, ui->dragx, ui->dragy,
2992 iscur ? TILESIZE/4 : TILESIZE/2, bg, COL_GRID);
2993 for (i = 0; i < FOUR; i++)
2994 if (ui->drag_pencil & (1 << i))
2995 draw_circle(dr, ui->dragx + ((i*4+2)%10-3) * TILESIZE/10,
2996 ui->dragy + (i*2-3) * TILESIZE/10,
2997 TILESIZE/8, COL_0 + i, COL_0 + i);
2998 draw_update(dr, ds->dragx, ds->dragy, TILESIZE + 3, TILESIZE + 3);
2999 ds->drag_visible = TRUE;
3003 static float game_anim_length(const game_state *oldstate,
3004 const game_state *newstate, int dir, game_ui *ui)
3009 static float game_flash_length(const game_state *oldstate,
3010 const game_state *newstate, int dir, game_ui *ui)
3012 if (!oldstate->completed && newstate->completed &&
3013 !oldstate->cheated && !newstate->cheated) {
3014 if (flash_type < 0) {
3015 char *env = getenv("MAP_ALTERNATIVE_FLASH");
3017 flash_type = atoi(env);
3020 flash_length = (flash_type == 1 ? 0.50F : 0.30F);
3022 return flash_length;
3027 static int game_status(const game_state *state)
3029 return state->completed ? +1 : 0;
3032 static int game_timing_state(const game_state *state, game_ui *ui)
3037 static void game_print_size(const game_params *params, float *x, float *y)
3042 * I'll use 4mm squares by default, I think. Simplest way to
3043 * compute this size is to compute the pixel puzzle size at a
3044 * given tile size and then scale.
3046 game_compute_size(params, 400, &pw, &ph);
3051 static void game_print(drawing *dr, const game_state *state, int tilesize)
3053 int w = state->p.w, h = state->p.h, wh = w*h, n = state->p.n;
3054 int ink, c[FOUR], i;
3056 int *coords, ncoords, coordsize;
3058 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3059 struct { int tilesize; } ads, *ds = &ads;
3060 /* We can't call game_set_size() here because we don't want a blitter */
3061 ads.tilesize = tilesize;
3063 ink = print_mono_colour(dr, 0);
3064 for (i = 0; i < FOUR; i++)
3065 c[i] = print_rgb_hatched_colour(dr, map_colours[i][0],
3066 map_colours[i][1], map_colours[i][2],
3072 print_line_width(dr, TILESIZE / 16);
3075 * Draw a single filled polygon around each region.
3077 for (r = 0; r < n; r++) {
3078 int octants[8], lastdir, d1, d2, ox, oy;
3081 * Start by finding a point on the region boundary. Any
3082 * point will do. To do this, we'll search for a square
3083 * containing the region and then decide which corner of it
3087 for (y = 0; y < h; y++) {
3088 for (x = 0; x < w; x++) {
3089 if (state->map->map[wh*0+y*w+x] == r ||
3090 state->map->map[wh*1+y*w+x] == r ||
3091 state->map->map[wh*2+y*w+x] == r ||
3092 state->map->map[wh*3+y*w+x] == r)
3098 assert(y < h && x < w); /* we must have found one somewhere */
3100 * This is the first square in lexicographic order which
3101 * contains part of this region. Therefore, one of the top
3102 * two corners of the square must be what we're after. The
3103 * only case in which it isn't the top left one is if the
3104 * square is diagonally divided and the region is in the
3105 * bottom right half.
3107 if (state->map->map[wh*TE+y*w+x] != r &&
3108 state->map->map[wh*LE+y*w+x] != r)
3109 x++; /* could just as well have done y++ */
3112 * Now we have a point on the region boundary. Trace around
3113 * the region until we come back to this point,
3114 * accumulating coordinates for a polygon draw operation as
3124 * There are eight possible directions we could head in
3125 * from here. We identify them by octant numbers, and
3126 * we also use octant numbers to identify the spaces
3139 octants[0] = x<w && y>0 ? state->map->map[wh*LE+(y-1)*w+x] : -1;
3140 octants[1] = x<w && y>0 ? state->map->map[wh*BE+(y-1)*w+x] : -1;
3141 octants[2] = x<w && y<h ? state->map->map[wh*TE+y*w+x] : -1;
3142 octants[3] = x<w && y<h ? state->map->map[wh*LE+y*w+x] : -1;
3143 octants[4] = x>0 && y<h ? state->map->map[wh*RE+y*w+(x-1)] : -1;
3144 octants[5] = x>0 && y<h ? state->map->map[wh*TE+y*w+(x-1)] : -1;
3145 octants[6] = x>0 && y>0 ? state->map->map[wh*BE+(y-1)*w+(x-1)] :-1;
3146 octants[7] = x>0 && y>0 ? state->map->map[wh*RE+(y-1)*w+(x-1)] :-1;
3149 for (i = 0; i < 8; i++)
3150 if ((octants[i] == r) ^ (octants[(i+1)%8] == r)) {
3158 assert(d1 != -1 && d2 != -1);
3163 * Now we're heading in direction d1. Save the current
3166 if (ncoords + 2 > coordsize) {
3168 coords = sresize(coords, coordsize, int);
3170 coords[ncoords++] = COORD(x);
3171 coords[ncoords++] = COORD(y);
3174 * Compute the new coordinates.
3176 x += (d1 % 4 == 3 ? 0 : d1 < 4 ? +1 : -1);
3177 y += (d1 % 4 == 1 ? 0 : d1 > 1 && d1 < 5 ? +1 : -1);
3178 assert(x >= 0 && x <= w && y >= 0 && y <= h);
3181 } while (x != ox || y != oy);
3183 draw_polygon(dr, coords, ncoords/2,
3184 state->colouring[r] >= 0 ?
3185 c[state->colouring[r]] : -1, ink);
3194 const struct game thegame = {
3195 "Map", "games.map", "map",
3197 game_fetch_preset, NULL,
3202 TRUE, game_configure, custom_params,
3210 FALSE, game_can_format_as_text_now, game_text_format,
3218 20, game_compute_size, game_set_size,
3221 game_free_drawstate,
3226 TRUE, TRUE, game_print_size, game_print,
3227 FALSE, /* wants_statusbar */
3228 FALSE, game_timing_state,
3232 #ifdef STANDALONE_SOLVER
3234 int main(int argc, char **argv)
3238 char *id = NULL, *desc;
3241 int ret, diff, really_verbose = FALSE;
3242 struct solver_scratch *sc;
3245 while (--argc > 0) {
3247 if (!strcmp(p, "-v")) {
3248 really_verbose = TRUE;
3249 } else if (!strcmp(p, "-g")) {
3251 } else if (*p == '-') {
3252 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
3260 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
3264 desc = strchr(id, ':');
3266 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
3271 p = default_params();
3272 decode_params(p, id);
3273 err = validate_desc(p, desc);
3275 fprintf(stderr, "%s: %s\n", argv[0], err);
3278 s = new_game(NULL, p, desc);
3280 sc = new_scratch(s->map->graph, s->map->n, s->map->ngraph);
3283 * When solving an Easy puzzle, we don't want to bother the
3284 * user with Hard-level deductions. For this reason, we grade
3285 * the puzzle internally before doing anything else.
3287 ret = -1; /* placate optimiser */
3288 for (diff = 0; diff < DIFFCOUNT; diff++) {
3289 for (i = 0; i < s->map->n; i++)
3290 if (!s->map->immutable[i])
3291 s->colouring[i] = -1;
3292 ret = map_solver(sc, s->map->graph, s->map->n, s->map->ngraph,
3293 s->colouring, diff);
3298 if (diff == DIFFCOUNT) {
3300 printf("Difficulty rating: harder than Hard, or ambiguous\n");
3302 printf("Unable to find a unique solution\n");
3306 printf("Difficulty rating: impossible (no solution exists)\n");
3308 printf("Difficulty rating: %s\n", map_diffnames[diff]);
3310 verbose = really_verbose;
3311 for (i = 0; i < s->map->n; i++)
3312 if (!s->map->immutable[i])
3313 s->colouring[i] = -1;
3314 ret = map_solver(sc, s->map->graph, s->map->n, s->map->ngraph,
3315 s->colouring, diff);
3317 printf("Puzzle is inconsistent\n");
3321 for (i = 0; i < s->map->n; i++) {
3322 printf("%5d <- %c%c", i, colnames[s->colouring[i]],
3323 (col < 6 && i+1 < s->map->n ? ' ' : '\n'));
3336 /* vim: set shiftwidth=4 tabstop=8: */