2 * galaxies.c: implementation of 'Tentai Show' from Nikoli,
3 * also sometimes called 'Spiral Galaxies'.
7 * Grid is stored as size (2n-1), holding edges as well as spaces
8 * (and thus vertices too, at edge intersections).
10 * Any dot will thus be positioned at one of our grid points,
11 * which saves any faffing with half-of-a-square stuff.
13 * Edges have on/off state; obviously the actual edges of the
14 * board are fixed to on, and everything else starts as off.
18 * Think about how to display remote groups of tiles?
24 * Nikoli's example [web site has wrong highlighting]
25 * (at http://www.nikoli.co.jp/en/puzzles/astronomical_show/):
28 * The 'spiral galaxies puzzles are NP-complete' paper
29 * (at http://www.stetson.edu/~efriedma/papers/spiral.pdf):
30 * 7x7:chpgdqqqoezdddki
32 * Puzzle competition pdf examples
33 * (at http://www.puzzleratings.org/Yurekli2006puz.pdf):
34 * 6x6:EDbaMucCohbrecEi
35 * 10x10:beFbufEEzowDlxldibMHezBQzCdcFzjlci
36 * 13x13:dCemIHFFkJajjgDfdbdBzdzEgjccoPOcztHjBczLDjczqktJjmpreivvNcggFi
52 int solver_show_working;
53 #define solvep(x) do { if (solver_show_working) { printf x; } } while(0)
56 #ifdef STANDALONE_PICTURE_GENERATOR
58 * Dirty hack to enable the generator to construct a game ID which
59 * solves to a specified black-and-white bitmap. We define a global
60 * variable here which gives the desired colour of each square, and
61 * we arrange that the grid generator never merges squares of
64 * The bitmap as stored here is a simple int array (at these sizes
65 * it isn't worth doing fiddly bit-packing). picture[y*w+x] is 1
66 * iff the pixel at (x,y) is intended to be black.
68 * (It might be nice to be able to specify some pixels as
69 * don't-care, to give the generator more leeway. But that might be
90 A(UNREASONABLE,Unreasonable,u)
92 #define ENUM(upper,title,lower) DIFF_ ## upper,
93 #define TITLE(upper,title,lower) #title,
94 #define ENCODE(upper,title,lower) #lower
95 #define CONFIG(upper,title,lower) ":" #title
97 DIFF_IMPOSSIBLE, DIFF_AMBIGUOUS, DIFF_UNFINISHED, DIFF_MAX };
98 static char const *const galaxies_diffnames[] = {
99 DIFFLIST(TITLE) "Impossible", "Ambiguous", "Unfinished" };
100 static char const galaxies_diffchars[] = DIFFLIST(ENCODE);
101 #define DIFFCONFIG DIFFLIST(CONFIG)
104 /* X and Y is the area of the board as seen by
105 * the user, not the (2n+1) area the game uses. */
109 enum { s_tile, s_edge, s_vertex };
111 #define F_DOT 1 /* there's a dot here */
112 #define F_EDGE_SET 2 /* the edge is set */
113 #define F_TILE_ASSOC 4 /* this tile is associated with a dot. */
114 #define F_DOT_BLACK 8 /* (ui only) dot is black. */
115 #define F_MARK 16 /* scratch flag */
116 #define F_REACHABLE 32
118 #define F_MULTIPLE 128
119 #define F_DOT_HOLD 256
122 typedef struct space {
123 int x, y; /* its position */
126 int dotx, doty; /* if flags & F_TILE_ASSOC */
127 int nassoc; /* if flags & F_DOT */
130 #define INGRID(s,x,y) ((x) >= 0 && (y) >= 0 && \
131 (x) < (state)->sx && (y) < (state)->sy)
132 #define INUI(s,x,y) ((x) > 0 && (y) > 0 && \
133 (x) < ((state)->sx-1) && (y) < ((state)->sy-1))
135 #define GRID(s,g,x,y) ((s)->g[((y)*(s)->sx)+(x)])
136 #define SPACE(s,x,y) GRID(s,grid,x,y)
139 int w, h; /* size from params */
140 int sx, sy; /* allocated size, (2x-1)*(2y-1) */
142 int completed, used_solve;
146 midend *me; /* to call supersede_game_desc */
147 int cdiff; /* difficulty of current puzzle (for status bar),
151 static int check_complete(const game_state *state, int *dsf, int *colours);
152 static int solver_state(game_state *state, int maxdiff);
153 static int solver_obvious(game_state *state);
154 static int solver_obvious_dot(game_state *state, space *dot);
156 /* ----------------------------------------------------------
157 * Game parameters and presets
160 /* make up some sensible default sizes */
162 #define DEFAULT_PRESET 0
164 static const game_params galaxies_presets[] = {
165 { 7, 7, DIFF_NORMAL },
166 { 7, 7, DIFF_UNREASONABLE },
167 { 10, 10, DIFF_NORMAL },
168 { 15, 15, DIFF_NORMAL },
171 static int game_fetch_preset(int i, char **name, game_params **params)
176 if (i < 0 || i >= lenof(galaxies_presets))
179 ret = snew(game_params);
180 *ret = galaxies_presets[i]; /* structure copy */
182 sprintf(buf, "%dx%d %s", ret->w, ret->h,
183 galaxies_diffnames[ret->diff]);
185 if (name) *name = dupstr(buf);
190 static game_params *default_params(void)
193 game_fetch_preset(DEFAULT_PRESET, NULL, &ret);
197 static void free_params(game_params *params)
202 static game_params *dup_params(const game_params *params)
204 game_params *ret = snew(game_params);
205 *ret = *params; /* structure copy */
209 static void decode_params(game_params *params, char const *string)
211 params->h = params->w = atoi(string);
212 params->diff = DIFF_NORMAL;
213 while (*string && isdigit((unsigned char)*string)) string++;
214 if (*string == 'x') {
216 params->h = atoi(string);
217 while (*string && isdigit((unsigned char)*string)) string++;
219 if (*string == 'd') {
222 for (i = 0; i <= DIFF_UNREASONABLE; i++)
223 if (*string == galaxies_diffchars[i])
225 if (*string) string++;
229 static char *encode_params(const game_params *params, int full)
232 sprintf(str, "%dx%d", params->w, params->h);
234 sprintf(str + strlen(str), "d%c", galaxies_diffchars[params->diff]);
238 static config_item *game_configure(const game_params *params)
243 ret = snewn(4, config_item);
245 ret[0].name = "Width";
246 ret[0].type = C_STRING;
247 sprintf(buf, "%d", params->w);
248 ret[0].sval = dupstr(buf);
251 ret[1].name = "Height";
252 ret[1].type = C_STRING;
253 sprintf(buf, "%d", params->h);
254 ret[1].sval = dupstr(buf);
257 ret[2].name = "Difficulty";
258 ret[2].type = C_CHOICES;
259 ret[2].sval = DIFFCONFIG;
260 ret[2].ival = params->diff;
270 static game_params *custom_params(const config_item *cfg)
272 game_params *ret = snew(game_params);
274 ret->w = atoi(cfg[0].sval);
275 ret->h = atoi(cfg[1].sval);
276 ret->diff = cfg[2].ival;
281 static char *validate_params(const game_params *params, int full)
283 if (params->w < 3 || params->h < 3)
284 return "Width and height must both be at least 3";
286 * This shouldn't be able to happen at all, since decode_params
287 * and custom_params will never generate anything that isn't
290 assert(params->diff <= DIFF_UNREASONABLE);
295 /* ----------------------------------------------------------
296 * Game utility functions.
299 static void add_dot(space *space) {
300 assert(!(space->flags & F_DOT));
301 space->flags |= F_DOT;
305 static void remove_dot(space *space) {
306 assert(space->flags & F_DOT);
307 space->flags &= ~F_DOT;
310 static void remove_assoc(const game_state *state, space *tile) {
311 if (tile->flags & F_TILE_ASSOC) {
312 SPACE(state, tile->dotx, tile->doty).nassoc--;
313 tile->flags &= ~F_TILE_ASSOC;
319 static void add_assoc(const game_state *state, space *tile, space *dot) {
320 remove_assoc(state, tile);
322 #ifdef STANDALONE_PICTURE_GENERATOR
324 assert(!picture[(tile->y/2) * state->w + (tile->x/2)] ==
325 !(dot->flags & F_DOT_BLACK));
327 tile->flags |= F_TILE_ASSOC;
331 /*debug(("add_assoc sp %d %d --> dot %d,%d, new nassoc %d.\n",
332 tile->x, tile->y, dot->x, dot->y, dot->nassoc));*/
335 static space *sp2dot(const game_state *state, int x, int y)
337 space *sp = &SPACE(state, x, y);
338 if (!(sp->flags & F_TILE_ASSOC)) return NULL;
339 return &SPACE(state, sp->dotx, sp->doty);
342 #define IS_VERTICAL_EDGE(x) ((x % 2) == 0)
344 static int game_can_format_as_text_now(const game_params *params)
349 static char *game_text_format(const game_state *state)
351 int maxlen = (state->sx+1)*state->sy, x, y;
355 ret = snewn(maxlen+1, char);
358 for (y = 0; y < state->sy; y++) {
359 for (x = 0; x < state->sx; x++) {
360 sp = &SPACE(state, x, y);
361 if (sp->flags & F_DOT)
364 else if (sp->flags & (F_REACHABLE|F_MULTIPLE|F_MARK))
365 *p++ = (sp->flags & F_MULTIPLE) ? 'M' :
366 (sp->flags & F_REACHABLE) ? 'R' : 'X';
371 if (sp->flags & F_TILE_ASSOC) {
372 space *dot = sp2dot(state, sp->x, sp->y);
373 if (dot && dot->flags & F_DOT)
374 *p++ = (dot->flags & F_DOT_BLACK) ? 'B' : 'W';
376 *p++ = '?'; /* association with not-a-dot. */
386 if (sp->flags & F_EDGE_SET)
387 *p++ = (IS_VERTICAL_EDGE(x)) ? '|' : '-';
393 assert(!"shouldn't get here!");
400 assert(p - ret == maxlen);
406 static void dbg_state(const game_state *state)
409 char *temp = game_text_format(state);
410 debug(("%s\n", temp));
415 /* Space-enumeration callbacks should all return 1 for 'progress made',
416 * -1 for 'impossible', and 0 otherwise. */
417 typedef int (*space_cb)(game_state *state, space *sp, void *ctx);
419 #define IMPOSSIBLE_QUITS 1
421 static int foreach_sub(game_state *state, space_cb cb, unsigned int f,
422 void *ctx, int startx, int starty)
424 int x, y, progress = 0, impossible = 0, ret;
427 for (y = starty; y < state->sy; y += 2) {
428 sp = &SPACE(state, startx, y);
429 for (x = startx; x < state->sx; x += 2) {
430 ret = cb(state, sp, ctx);
432 if (f & IMPOSSIBLE_QUITS) return -1;
434 } else if (ret == 1) {
440 return impossible ? -1 : progress;
443 static int foreach_tile(game_state *state, space_cb cb, unsigned int f,
446 return foreach_sub(state, cb, f, ctx, 1, 1);
449 static int foreach_edge(game_state *state, space_cb cb, unsigned int f,
454 ret1 = foreach_sub(state, cb, f, ctx, 0, 1);
455 ret2 = foreach_sub(state, cb, f, ctx, 1, 0);
457 if (ret1 == -1 || ret2 == -1) return -1;
458 return (ret1 || ret2) ? 1 : 0;
462 static int foreach_vertex(game_state *state, space_cb cb, unsigned int f,
465 return foreach_sub(state, cb, f, ctx, 0, 0);
470 static int is_same_assoc(game_state *state,
471 int x1, int y1, int x2, int y2)
475 if (!INGRID(state, x1, y1) || !INGRID(state, x2, y2))
478 s1 = &SPACE(state, x1, y1);
479 s2 = &SPACE(state, x2, y2);
480 assert(s1->type == s_tile && s2->type == s_tile);
481 if ((s1->flags & F_TILE_ASSOC) && (s2->flags & F_TILE_ASSOC) &&
482 s1->dotx == s2->dotx && s1->doty == s2->doty)
484 return 0; /* 0 if not same or not both associated. */
489 static int edges_into_vertex(game_state *state,
492 int dx, dy, nx, ny, count = 0;
494 assert(SPACE(state, x, y).type == s_vertex);
495 for (dx = -1; dx <= 1; dx++) {
496 for (dy = -1; dy <= 1; dy++) {
497 if (dx != 0 && dy != 0) continue;
498 if (dx == 0 && dy == 0) continue;
500 nx = x+dx; ny = y+dy;
501 if (!INGRID(state, nx, ny)) continue;
502 assert(SPACE(state, nx, ny).type == s_edge);
503 if (SPACE(state, nx, ny).flags & F_EDGE_SET)
511 static space *space_opposite_dot(game_state *state, space *sp, space *dot)
520 if (!INGRID(state, tx, ty)) return NULL;
522 sp2 = &SPACE(state, tx, ty);
523 assert(sp2->type == sp->type);
527 static space *tile_opposite(game_state *state, space *sp)
531 assert(sp->flags & F_TILE_ASSOC);
532 dot = &SPACE(state, sp->dotx, sp->doty);
533 return space_opposite_dot(state, sp, dot);
536 static int dotfortile(game_state *state, space *tile, space *dot)
538 space *tile_opp = space_opposite_dot(state, tile, dot);
540 if (!tile_opp) return 0; /* opposite would be off grid */
541 if (tile_opp->flags & F_TILE_ASSOC &&
542 (tile_opp->dotx != dot->x || tile_opp->doty != dot->y))
543 return 0; /* opposite already associated with diff. dot */
547 static void adjacencies(game_state *state, space *sp, space **a1s, space **a2s)
549 int dxs[4] = {-1, 1, 0, 0}, dys[4] = {0, 0, -1, 1};
552 /* this function needs optimising. */
554 for (n = 0; n < 4; n++) {
558 if (INGRID(state, x, y)) {
559 a1s[n] = &SPACE(state, x, y);
561 x += dxs[n]; y += dys[n];
563 if (INGRID(state, x, y))
564 a2s[n] = &SPACE(state, x, y);
568 a1s[n] = a2s[n] = NULL;
573 static int outline_tile_fordot(game_state *state, space *tile, int mark)
575 space *tadj[4], *eadj[4];
576 int i, didsth = 0, edge, same;
578 assert(tile->type == s_tile);
579 adjacencies(state, tile, eadj, tadj);
580 for (i = 0; i < 4; i++) {
581 if (!eadj[i]) continue;
583 edge = (eadj[i]->flags & F_EDGE_SET) ? 1 : 0;
585 if (!(tile->flags & F_TILE_ASSOC))
586 same = (tadj[i]->flags & F_TILE_ASSOC) ? 0 : 1;
588 same = ((tadj[i]->flags & F_TILE_ASSOC) &&
589 tile->dotx == tadj[i]->dotx &&
590 tile->doty == tadj[i]->doty) ? 1 : 0;
594 if (!edge && !same) {
595 if (mark) eadj[i]->flags |= F_EDGE_SET;
597 } else if (edge && same) {
598 if (mark) eadj[i]->flags &= ~F_EDGE_SET;
605 static void tiles_from_edge(game_state *state, space *sp, space **ts)
609 if (IS_VERTICAL_EDGE(sp->x)) {
610 xs[0] = sp->x-1; ys[0] = sp->y;
611 xs[1] = sp->x+1; ys[1] = sp->y;
613 xs[0] = sp->x; ys[0] = sp->y-1;
614 xs[1] = sp->x; ys[1] = sp->y+1;
616 ts[0] = INGRID(state, xs[0], ys[0]) ? &SPACE(state, xs[0], ys[0]) : NULL;
617 ts[1] = INGRID(state, xs[1], ys[1]) ? &SPACE(state, xs[1], ys[1]) : NULL;
620 /* Returns a move string for use by 'solve', including the initial
621 * 'S' if issolve is true. */
622 static char *diff_game(const game_state *src, const game_state *dest,
625 int movelen = 0, movesize = 256, x, y, len;
626 char *move = snewn(movesize, char), buf[80], *sep = "";
627 char achar = issolve ? 'a' : 'A';
630 assert(src->sx == dest->sx && src->sy == dest->sy);
633 move[movelen++] = 'S';
636 move[movelen] = '\0';
637 for (x = 0; x < src->sx; x++) {
638 for (y = 0; y < src->sy; y++) {
639 sps = &SPACE(src, x, y);
640 spd = &SPACE(dest, x, y);
642 assert(sps->type == spd->type);
645 if (sps->type == s_tile) {
646 if ((sps->flags & F_TILE_ASSOC) &&
647 (spd->flags & F_TILE_ASSOC)) {
648 if (sps->dotx != spd->dotx ||
649 sps->doty != spd->doty)
650 /* Both associated; change association, if different */
651 len = sprintf(buf, "%s%c%d,%d,%d,%d", sep,
652 (int)achar, x, y, spd->dotx, spd->doty);
653 } else if (sps->flags & F_TILE_ASSOC)
654 /* Only src associated; remove. */
655 len = sprintf(buf, "%sU%d,%d", sep, x, y);
656 else if (spd->flags & F_TILE_ASSOC)
657 /* Only dest associated; add. */
658 len = sprintf(buf, "%s%c%d,%d,%d,%d", sep,
659 (int)achar, x, y, spd->dotx, spd->doty);
660 } else if (sps->type == s_edge) {
661 if ((sps->flags & F_EDGE_SET) != (spd->flags & F_EDGE_SET))
662 /* edge flags are different; flip them. */
663 len = sprintf(buf, "%sE%d,%d", sep, x, y);
666 if (movelen + len >= movesize) {
667 movesize = movelen + len + 256;
668 move = sresize(move, movesize, char);
670 strcpy(move + movelen, buf);
676 debug(("diff_game src then dest:\n"));
679 debug(("diff string %s\n", move));
683 /* Returns 1 if a dot here would not be too close to any other dots
684 * (and would avoid other game furniture). */
685 static int dot_is_possible(game_state *state, space *sp, int allow_assoc)
687 int bx = 0, by = 0, dx, dy;
689 #ifdef STANDALONE_PICTURE_GENERATOR
697 if (IS_VERTICAL_EDGE(sp->x)) {
707 for (dx = -bx; dx <= bx; dx++) {
708 for (dy = -by; dy <= by; dy++) {
709 if (!INGRID(state, sp->x+dx, sp->y+dy)) continue;
711 adj = &SPACE(state, sp->x+dx, sp->y+dy);
713 #ifdef STANDALONE_PICTURE_GENERATOR
715 * Check that all the squares we're looking at have the
719 if (adj->type == s_tile) {
720 int c = picture[(adj->y / 2) * state->w + (adj->x / 2)];
724 return 0; /* colour mismatch */
729 if (!allow_assoc && (adj->flags & F_TILE_ASSOC))
732 if (dx != 0 || dy != 0) {
733 /* Other than our own square, no dots nearby. */
734 if (adj->flags & (F_DOT))
738 /* We don't want edges within our rectangle
739 * (but don't care about edges on the edge) */
740 if (abs(dx) < bx && abs(dy) < by &&
741 adj->flags & F_EDGE_SET)
748 /* ----------------------------------------------------------
749 * Game generation, structure creation, and descriptions.
752 static game_state *blank_game(int w, int h)
754 game_state *state = snew(game_state);
762 state->grid = snewn(state->sx * state->sy, space);
763 state->completed = state->used_solve = 0;
765 for (x = 0; x < state->sx; x++) {
766 for (y = 0; y < state->sy; y++) {
767 space *sp = &SPACE(state, x, y);
768 memset(sp, 0, sizeof(space));
771 if ((x % 2) == 0 && (y % 2) == 0)
773 else if ((x % 2) == 0 || (y % 2) == 0) {
775 if (x == 0 || y == 0 || x == state->sx-1 || y == state->sy-1)
776 sp->flags |= F_EDGE_SET;
785 state->me = NULL; /* filled in by new_game. */
791 static void game_update_dots(game_state *state)
793 int i, n, sz = state->sx * state->sy;
795 if (state->dots) sfree(state->dots);
798 for (i = 0; i < sz; i++) {
799 if (state->grid[i].flags & F_DOT) state->ndots++;
801 state->dots = snewn(state->ndots, space *);
803 for (i = 0; i < sz; i++) {
804 if (state->grid[i].flags & F_DOT)
805 state->dots[n++] = &state->grid[i];
809 static void clear_game(game_state *state, int cleardots)
813 /* don't erase edge flags around outline! */
814 for (x = 1; x < state->sx-1; x++) {
815 for (y = 1; y < state->sy-1; y++) {
817 SPACE(state, x, y).flags = 0;
819 SPACE(state, x, y).flags &= (F_DOT|F_DOT_BLACK);
822 if (cleardots) game_update_dots(state);
825 static game_state *dup_game(const game_state *state)
827 game_state *ret = blank_game(state->w, state->h);
829 ret->completed = state->completed;
830 ret->used_solve = state->used_solve;
832 memcpy(ret->grid, state->grid,
833 ret->sx*ret->sy*sizeof(space));
835 game_update_dots(ret);
838 ret->cdiff = state->cdiff;
843 static void free_game(game_state *state)
845 if (state->dots) sfree(state->dots);
850 /* Game description is a sequence of letters representing the number
851 * of spaces (a = 0, y = 24) before the next dot; a-y for a white dot,
852 * and A-Y for a black dot. 'z' is 25 spaces (and no dot).
854 * I know it's a bitch to generate by hand, so we provide
858 static char *encode_game(game_state *state)
864 area = (state->sx-2) * (state->sy-2);
866 desc = snewn(area, char);
869 for (y = 1; y < state->sy-1; y++) {
870 for (x = 1; x < state->sx-1; x++) {
871 f = SPACE(state, x, y).flags;
873 /* a/A is 0 spaces between, b/B is 1 space, ...
874 * y/Y is 24 spaces, za/zA is 25 spaces, ...
875 * It's easier to count from 0 because we then
876 * don't have to special-case the top left-hand corner
877 * (which could be a dot with 0 spaces before it). */
885 *p++ = ((f & F_DOT_BLACK) ? 'A' : 'a') + run;
890 assert(p - desc < area);
892 desc = sresize(desc, p - desc, char);
899 space *olddot, *newdot;
902 enum { MD_CHECK, MD_MOVE };
904 static int movedot_cb(game_state *state, space *tile, void *vctx)
906 struct movedot *md = (struct movedot *)vctx;
907 space *newopp = NULL;
909 assert(tile->type == s_tile);
910 assert(md->olddot && md->newdot);
912 if (!(tile->flags & F_TILE_ASSOC)) return 0;
913 if (tile->dotx != md->olddot->x || tile->doty != md->olddot->y)
916 newopp = space_opposite_dot(state, tile, md->newdot);
920 /* If the tile is associated with the old dot, check its
921 * opposite wrt the _new_ dot is empty or same assoc. */
922 if (!newopp) return -1; /* no new opposite */
923 if (newopp->flags & F_TILE_ASSOC) {
924 if (newopp->dotx != md->olddot->x ||
925 newopp->doty != md->olddot->y)
926 return -1; /* associated, but wrong dot. */
928 #ifdef STANDALONE_PICTURE_GENERATOR
931 * Reject if either tile and the dot don't match in colour.
933 if (!(picture[(tile->y/2) * state->w + (tile->x/2)]) ^
934 !(md->newdot->flags & F_DOT_BLACK))
936 if (!(picture[(newopp->y/2) * state->w + (newopp->x/2)]) ^
937 !(md->newdot->flags & F_DOT_BLACK))
944 /* Move dot associations: anything that was associated
945 * with the old dot, and its opposite wrt the new dot,
946 * become associated with the new dot. */
948 debug(("Associating %d,%d and %d,%d with new dot %d,%d.\n",
949 tile->x, tile->y, newopp->x, newopp->y,
950 md->newdot->x, md->newdot->y));
951 add_assoc(state, tile, md->newdot);
952 add_assoc(state, newopp, md->newdot);
953 return 1; /* we did something! */
958 /* For the given dot, first see if we could expand it into all the given
959 * extra spaces (by checking for empty spaces on the far side), and then
960 * see if we can move the dot to shift the CoG to include the new spaces.
962 static int dot_expand_or_move(game_state *state, space *dot,
963 space **toadd, int nadd)
966 int i, ret, nnew, cx, cy;
969 debug(("dot_expand_or_move: %d tiles for dot %d,%d\n",
970 nadd, dot->x, dot->y));
971 for (i = 0; i < nadd; i++)
972 debug(("dot_expand_or_move: dot %d,%d\n",
973 toadd[i]->x, toadd[i]->y));
974 assert(dot->flags & F_DOT);
976 #ifdef STANDALONE_PICTURE_GENERATOR
979 * Reject the expansion totally if any of the new tiles are
982 for (i = 0; i < nadd; i++) {
983 if (!(picture[(toadd[i]->y/2) * state->w + (toadd[i]->x/2)]) ^
984 !(dot->flags & F_DOT_BLACK))
990 /* First off, could we just expand the current dot's tile to cover
991 * the space(s) passed in and their opposites? */
992 for (i = 0; i < nadd; i++) {
993 tileopp = space_opposite_dot(state, toadd[i], dot);
994 if (!tileopp) goto noexpand;
995 if (tileopp->flags & F_TILE_ASSOC) goto noexpand;
996 #ifdef STANDALONE_PICTURE_GENERATOR
999 * The opposite tiles have to be the right colour as well.
1001 if (!(picture[(tileopp->y/2) * state->w + (tileopp->x/2)]) ^
1002 !(dot->flags & F_DOT_BLACK))
1007 /* OK, all spaces have valid empty opposites: associate spaces and
1008 * opposites with our dot. */
1009 for (i = 0; i < nadd; i++) {
1010 tileopp = space_opposite_dot(state, toadd[i], dot);
1011 add_assoc(state, toadd[i], dot);
1012 add_assoc(state, tileopp, dot);
1013 debug(("Added associations %d,%d and %d,%d --> %d,%d\n",
1014 toadd[i]->x, toadd[i]->y,
1015 tileopp->x, tileopp->y,
1022 /* Otherwise, try to move dot so as to encompass given spaces: */
1023 /* first, calculate the 'centre of gravity' of the new dot. */
1024 nnew = dot->nassoc + nadd; /* number of tiles assoc. with new dot. */
1025 cx = dot->x * dot->nassoc;
1026 cy = dot->y * dot->nassoc;
1027 for (i = 0; i < nadd; i++) {
1031 /* If the CoG isn't a whole number, it's not possible. */
1032 if ((cx % nnew) != 0 || (cy % nnew) != 0) {
1033 debug(("Unable to move dot %d,%d, CoG not whole number.\n",
1037 cx /= nnew; cy /= nnew;
1039 /* Check whether all spaces in the old tile would have a good
1040 * opposite wrt the new dot. */
1042 md.newdot = &SPACE(state, cx, cy);
1044 ret = foreach_tile(state, movedot_cb, IMPOSSIBLE_QUITS, &md);
1046 debug(("Unable to move dot %d,%d, new dot not symmetrical.\n",
1050 /* Also check whether all spaces we're adding would have a good
1051 * opposite wrt the new dot. */
1052 for (i = 0; i < nadd; i++) {
1053 tileopp = space_opposite_dot(state, toadd[i], md.newdot);
1054 if (tileopp && (tileopp->flags & F_TILE_ASSOC) &&
1055 (tileopp->dotx != dot->x || tileopp->doty != dot->y)) {
1059 debug(("Unable to move dot %d,%d, new dot not symmetrical.\n",
1063 #ifdef STANDALONE_PICTURE_GENERATOR
1065 if (!(picture[(tileopp->y/2) * state->w + (tileopp->x/2)]) ^
1066 !(dot->flags & F_DOT_BLACK))
1072 /* If we've got here, we're ok. First, associate all of 'toadd'
1073 * with the _old_ dot (so they'll get fixed up, with their opposites,
1074 * in the next step). */
1075 for (i = 0; i < nadd; i++) {
1076 debug(("Associating to-add %d,%d with old dot %d,%d.\n",
1077 toadd[i]->x, toadd[i]->y, dot->x, dot->y));
1078 add_assoc(state, toadd[i], dot);
1081 /* Finally, move the dot and fix up all the old associations. */
1082 debug(("Moving dot at %d,%d to %d,%d\n",
1083 dot->x, dot->y, md.newdot->x, md.newdot->y));
1085 #ifdef STANDALONE_PICTURE_GENERATOR
1086 int f = dot->flags & F_DOT_BLACK;
1090 #ifdef STANDALONE_PICTURE_GENERATOR
1091 md.newdot->flags |= f;
1096 ret = foreach_tile(state, movedot_cb, 0, &md);
1103 /* Hard-code to a max. of 2x2 squares, for speed (less malloc) */
1105 #define MAX_OUTSIDE 8
1107 #define MAX_TILE_PERC 20
1109 static int generate_try_block(game_state *state, random_state *rs,
1110 int x1, int y1, int x2, int y2)
1112 int x, y, nadd = 0, nout = 0, i, maxsz;
1113 space *sp, *toadd[MAX_TOADD], *outside[MAX_OUTSIDE], *dot;
1115 if (!INGRID(state, x1, y1) || !INGRID(state, x2, y2)) return 0;
1117 /* We limit the maximum size of tiles to be ~2*sqrt(area); so,
1118 * a 5x5 grid shouldn't have anything >10 tiles, a 20x20 grid
1119 * nothing >40 tiles. */
1120 maxsz = (int)sqrt((double)(state->w * state->h)) * 2;
1121 debug(("generate_try_block, maxsz %d\n", maxsz));
1123 /* Make a static list of the spaces; if any space is already
1124 * associated then quit immediately. */
1125 for (x = x1; x <= x2; x += 2) {
1126 for (y = y1; y <= y2; y += 2) {
1127 assert(nadd < MAX_TOADD);
1128 sp = &SPACE(state, x, y);
1129 assert(sp->type == s_tile);
1130 if (sp->flags & F_TILE_ASSOC) return 0;
1135 /* Make a list of the spaces outside of our block, and shuffle it. */
1136 #define OUTSIDE(x, y) do { \
1137 if (INGRID(state, (x), (y))) { \
1138 assert(nout < MAX_OUTSIDE); \
1139 outside[nout++] = &SPACE(state, (x), (y)); \
1142 for (x = x1; x <= x2; x += 2) {
1146 for (y = y1; y <= y2; y += 2) {
1150 shuffle(outside, nout, sizeof(space *), rs);
1152 for (i = 0; i < nout; i++) {
1153 if (!(outside[i]->flags & F_TILE_ASSOC)) continue;
1154 dot = &SPACE(state, outside[i]->dotx, outside[i]->doty);
1155 if (dot->nassoc >= maxsz) {
1156 debug(("Not adding to dot %d,%d, large enough (%d) already.\n",
1157 dot->x, dot->y, dot->nassoc));
1160 if (dot_expand_or_move(state, dot, toadd, nadd)) return 1;
1165 #ifdef STANDALONE_SOLVER
1167 #define MAXTRIES maxtries
1174 static void generate_pass(game_state *state, random_state *rs, int *scratch,
1175 int perc, unsigned int flags)
1177 int sz = state->sx*state->sy, nspc, i, ret;
1179 shuffle(scratch, sz, sizeof(int), rs);
1181 /* This bug took me a, er, little while to track down. On PalmOS,
1182 * which has 16-bit signed ints, puzzles over about 9x9 started
1183 * failing to generate because the nspc calculation would start
1184 * to overflow, causing the dots not to be filled in properly. */
1185 nspc = (int)(((long)perc * (long)sz) / 100L);
1186 debug(("generate_pass: %d%% (%d of %dx%d) squares, flags 0x%x\n",
1187 perc, nspc, state->sx, state->sy, flags));
1189 for (i = 0; i < nspc; i++) {
1190 space *sp = &state->grid[scratch[i]];
1191 int x1 = sp->x, y1 = sp->y, x2 = sp->x, y2 = sp->y;
1193 if (sp->type == s_edge) {
1194 if (IS_VERTICAL_EDGE(sp->x)) {
1200 if (sp->type != s_vertex) {
1201 /* heuristic; expanding from vertices tends to generate lots of
1202 * too-big regions of tiles. */
1203 if (generate_try_block(state, rs, x1, y1, x2, y2))
1204 continue; /* we expanded successfully. */
1207 if (!(flags & GP_DOTS)) continue;
1209 if ((sp->type == s_edge) && (i % 2)) {
1210 debug(("Omitting edge %d,%d as half-of.\n", sp->x, sp->y));
1214 /* If we've got here we might want to put a dot down. Check
1215 * if we can, and add one if so. */
1216 if (dot_is_possible(state, sp, 0)) {
1218 #ifdef STANDALONE_PICTURE_GENERATOR
1220 if (picture[(sp->y/2) * state->w + (sp->x/2)])
1221 sp->flags |= F_DOT_BLACK;
1224 ret = solver_obvious_dot(state, sp);
1226 debug(("Added dot (and obvious associations) at %d,%d\n",
1234 static char *new_game_desc(const game_params *params, random_state *rs,
1235 char **aux, int interactive)
1237 game_state *state = blank_game(params->w, params->h), *copy;
1239 int *scratch, sz = state->sx*state->sy, i;
1240 int diff, ntries = 0, cc;
1242 /* Random list of squares to try and process, one-by-one. */
1243 scratch = snewn(sz, int);
1244 for (i = 0; i < sz; i++) scratch[i] = i;
1247 clear_game(state, 1);
1250 /* generate_pass(state, rs, scratch, 10, GP_DOTS); */
1251 /* generate_pass(state, rs, scratch, 100, 0); */
1252 generate_pass(state, rs, scratch, 100, GP_DOTS);
1254 game_update_dots(state);
1258 char *tmp = encode_game(state);
1259 debug(("new_game_desc state %dx%d:%s\n", params->w, params->h, tmp));
1264 for (i = 0; i < state->sx*state->sy; i++)
1265 if (state->grid[i].type == s_tile)
1266 outline_tile_fordot(state, &state->grid[i], TRUE);
1267 cc = check_complete(state, NULL, NULL);
1270 copy = dup_game(state);
1271 clear_game(copy, 0);
1273 diff = solver_state(copy, params->diff);
1276 assert(diff != DIFF_IMPOSSIBLE);
1277 if (diff != params->diff) {
1279 * We'll grudgingly accept a too-easy puzzle, but we must
1280 * _not_ permit a too-hard one (one which the solver
1281 * couldn't handle at all).
1283 if (diff > params->diff ||
1284 ntries < MAXTRIES) goto generate;
1287 #ifdef STANDALONE_PICTURE_GENERATOR
1289 * Postprocessing pass to prevent excessive numbers of adjacent
1290 * singletons. Iterate over all edges in random shuffled order;
1291 * for each edge that separates two regions, investigate
1292 * whether removing that edge and merging the regions would
1293 * still yield a valid and soluble puzzle. (The two regions
1294 * must also be the same colour, of course.) If so, do it.
1296 * This postprocessing pass is slow (due to repeated solver
1297 * invocations), and seems to be unnecessary during normal
1298 * unconstrained game generation. However, when generating a
1299 * game under colour constraints, excessive singletons seem to
1300 * turn up more often, so it's worth doing this.
1307 nposns = params->w * (params->h+1) + params->h * (params->w+1);
1308 posns = snewn(nposns, int);
1309 for (i = j = 0; i < state->sx*state->sy; i++)
1310 if (state->grid[i].type == s_edge)
1312 assert(j == nposns);
1314 shuffle(posns, nposns, sizeof(*posns), rs);
1316 for (i = 0; i < nposns; i++) {
1317 int x, y, x0, y0, x1, y1, cx, cy, cn, cx0, cy0, cx1, cy1, tx, ty;
1318 space *s0, *s1, *ts, *d0, *d1, *dn;
1321 /* Coordinates of edge space */
1322 x = posns[i] % state->sx;
1323 y = posns[i] / state->sx;
1325 /* Coordinates of square spaces on either side of edge */
1326 x0 = ((x+1) & ~1) - 1; /* round down to next odd number */
1327 y0 = ((y+1) & ~1) - 1;
1328 x1 = 2*x-x0; /* and reflect about x to get x1 */
1331 if (!INGRID(state, x0, y0) || !INGRID(state, x1, y1))
1332 continue; /* outermost edge of grid */
1333 s0 = &SPACE(state, x0, y0);
1334 s1 = &SPACE(state, x1, y1);
1335 assert(s0->type == s_tile && s1->type == s_tile);
1337 if (s0->dotx == s1->dotx && s0->doty == s1->doty)
1338 continue; /* tiles _already_ owned by same dot */
1340 d0 = &SPACE(state, s0->dotx, s0->doty);
1341 d1 = &SPACE(state, s1->dotx, s1->doty);
1343 if ((d0->flags ^ d1->flags) & F_DOT_BLACK)
1344 continue; /* different colours: cannot merge */
1347 * Work out where the centre of gravity of the new
1350 cx = d0->nassoc * d0->x + d1->nassoc * d1->x;
1351 cy = d0->nassoc * d0->y + d1->nassoc * d1->y;
1352 cn = d0->nassoc + d1->nassoc;
1353 if (cx % cn || cy % cn)
1354 continue; /* CoG not at integer coordinates */
1357 assert(INUI(state, cx, cy));
1360 * Ensure that the CoG would actually be _in_ the new
1361 * region, by verifying that all its surrounding tiles
1362 * belong to one or other of our two dots.
1364 cx0 = ((cx+1) & ~1) - 1; /* round down to next odd number */
1365 cy0 = ((cy+1) & ~1) - 1;
1366 cx1 = 2*cx-cx0; /* and reflect about cx to get cx1 */
1369 for (ty = cy0; ty <= cy1; ty += 2)
1370 for (tx = cx0; tx <= cx1; tx += 2) {
1371 ts = &SPACE(state, tx, ty);
1372 assert(ts->type == s_tile);
1373 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1374 (ts->dotx != d1->x || ts->doty != d1->y))
1381 * Verify that for every tile in either source region,
1382 * that tile's image in the new CoG is also in one of
1383 * the two source regions.
1385 for (ty = 1; ty < state->sy; ty += 2) {
1386 for (tx = 1; tx < state->sx; tx += 2) {
1389 ts = &SPACE(state, tx, ty);
1390 assert(ts->type == s_tile);
1391 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1392 (ts->dotx != d1->x || ts->doty != d1->y))
1393 continue; /* not part of these tiles anyway */
1396 if (!INGRID(state, tx1, ty1)) {
1400 ts = &SPACE(state, cx+cx-tx, cy+cy-ty);
1401 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1402 (ts->dotx != d1->x || ts->doty != d1->y)) {
1414 * Now we're clear to attempt the merge. We take a copy
1415 * of the game state first, so we can revert it easily
1416 * if the resulting puzzle turns out to have become
1419 copy2 = dup_game(state);
1423 dn = &SPACE(state, cx, cy);
1425 dn->flags |= (d0->flags & F_DOT_BLACK);
1426 for (ty = 1; ty < state->sy; ty += 2) {
1427 for (tx = 1; tx < state->sx; tx += 2) {
1428 ts = &SPACE(state, tx, ty);
1429 assert(ts->type == s_tile);
1430 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1431 (ts->dotx != d1->x || ts->doty != d1->y))
1432 continue; /* not part of these tiles anyway */
1433 add_assoc(state, ts, dn);
1437 copy = dup_game(state);
1438 clear_game(copy, 0);
1440 newdiff = solver_state(copy, params->diff);
1442 if (diff == newdiff) {
1443 /* Still just as soluble. Let the merge stand. */
1446 /* Became insoluble. Revert. */
1455 desc = encode_game(state);
1456 #ifndef STANDALONE_SOLVER
1457 debug(("new_game_desc generated: \n"));
1467 static int dots_too_close(game_state *state)
1469 /* Quick-and-dirty check, using half the solver:
1470 * solver_obvious will only fail if the dots are
1471 * too close together, so dot-proximity associations
1473 game_state *tmp = dup_game(state);
1474 int ret = solver_obvious(tmp);
1476 return (ret == -1) ? 1 : 0;
1479 static game_state *load_game(const game_params *params, const char *desc,
1482 game_state *state = blank_game(params->w, params->h);
1494 if (n >= 'a' && n <= 'y') {
1497 } else if (n >= 'A' && n <= 'Y') {
1501 why = "Invalid characters in game description"; goto fail;
1503 /* if we got here we incremented i and have a dot to add. */
1504 y = (i / (state->sx-2)) + 1;
1505 x = (i % (state->sx-2)) + 1;
1506 if (!INUI(state, x, y)) {
1507 why = "Too much data to fit in grid"; goto fail;
1509 add_dot(&SPACE(state, x, y));
1510 SPACE(state, x, y).flags |= df;
1513 game_update_dots(state);
1515 if (dots_too_close(state)) {
1516 why = "Dots too close together"; goto fail;
1523 if (why_r) *why_r = why;
1527 static char *validate_desc(const game_params *params, const char *desc)
1530 game_state *dummy = load_game(params, desc, &why);
1539 static game_state *new_game(midend *me, const game_params *params,
1542 game_state *state = load_game(params, desc, NULL);
1544 assert("Unable to load ?validated game.");
1553 /* ----------------------------------------------------------
1554 * Solver and all its little wizards.
1557 int solver_recurse_depth;
1559 typedef struct solver_ctx {
1561 int sz; /* state->sx * state->sy */
1562 space **scratch; /* size sz */
1566 static solver_ctx *new_solver(game_state *state)
1568 solver_ctx *sctx = snew(solver_ctx);
1569 sctx->state = state;
1570 sctx->sz = state->sx*state->sy;
1571 sctx->scratch = snewn(sctx->sz, space *);
1575 static void free_solver(solver_ctx *sctx)
1577 sfree(sctx->scratch);
1581 /* Solver ideas so far:
1583 * For any empty space, work out how many dots it could associate
1585 * it needs line-of-sight
1586 * it needs an empty space on the far side
1587 * any adjacent lines need corresponding line possibilities.
1590 /* The solver_ctx should keep a list of dot positions, for quicker looping.
1592 * Solver techniques, in order of difficulty:
1593 * obvious adjacency to dots
1594 * transferring tiles to opposite side
1595 * transferring lines to opposite side
1596 * one possible dot for a given tile based on opposite availability
1597 * tile with 3 definite edges next to an associated tile must associate
1600 * one possible dot for a given tile based on line-of-sight
1603 static int solver_add_assoc(game_state *state, space *tile, int dx, int dy,
1606 space *dot, *tile_opp;
1608 dot = &SPACE(state, dx, dy);
1609 tile_opp = space_opposite_dot(state, tile, dot);
1611 assert(tile->type == s_tile);
1612 if (tile->flags & F_TILE_ASSOC) {
1613 if ((tile->dotx != dx) || (tile->doty != dy)) {
1614 solvep(("%*sSet %d,%d --> %d,%d (%s) impossible; "
1615 "already --> %d,%d.\n",
1616 solver_recurse_depth*4, "",
1617 tile->x, tile->y, dx, dy, why,
1618 tile->dotx, tile->doty));
1621 return 0; /* no-op */
1624 solvep(("%*s%d,%d --> %d,%d impossible, no opposite tile.\n",
1625 solver_recurse_depth*4, "", tile->x, tile->y, dx, dy));
1628 if (tile_opp->flags & F_TILE_ASSOC &&
1629 (tile_opp->dotx != dx || tile_opp->doty != dy)) {
1630 solvep(("%*sSet %d,%d --> %d,%d (%s) impossible; "
1631 "opposite already --> %d,%d.\n",
1632 solver_recurse_depth*4, "",
1633 tile->x, tile->y, dx, dy, why,
1634 tile_opp->dotx, tile_opp->doty));
1638 add_assoc(state, tile, dot);
1639 add_assoc(state, tile_opp, dot);
1640 solvep(("%*sSetting %d,%d --> %d,%d (%s).\n",
1641 solver_recurse_depth*4, "",
1642 tile->x, tile->y,dx, dy, why));
1643 solvep(("%*sSetting %d,%d --> %d,%d (%s, opposite).\n",
1644 solver_recurse_depth*4, "",
1645 tile_opp->x, tile_opp->y, dx, dy, why));
1649 static int solver_obvious_dot(game_state *state, space *dot)
1651 int dx, dy, ret, didsth = 0;
1654 debug(("%*ssolver_obvious_dot for %d,%d.\n",
1655 solver_recurse_depth*4, "", dot->x, dot->y));
1657 assert(dot->flags & F_DOT);
1658 for (dx = -1; dx <= 1; dx++) {
1659 for (dy = -1; dy <= 1; dy++) {
1660 if (!INGRID(state, dot->x+dx, dot->y+dy)) continue;
1662 tile = &SPACE(state, dot->x+dx, dot->y+dy);
1663 if (tile->type == s_tile) {
1664 ret = solver_add_assoc(state, tile, dot->x, dot->y,
1666 if (ret < 0) return -1;
1667 if (ret > 0) didsth = 1;
1674 static int solver_obvious(game_state *state)
1676 int i, didsth = 0, ret;
1678 debug(("%*ssolver_obvious.\n", solver_recurse_depth*4, ""));
1680 for (i = 0; i < state->ndots; i++) {
1681 ret = solver_obvious_dot(state, state->dots[i]);
1682 if (ret < 0) return -1;
1683 if (ret > 0) didsth = 1;
1688 static int solver_lines_opposite_cb(game_state *state, space *edge, void *ctx)
1690 int didsth = 0, n, dx, dy;
1691 space *tiles[2], *tile_opp, *edge_opp;
1693 assert(edge->type == s_edge);
1695 tiles_from_edge(state, edge, tiles);
1697 /* if tiles[0] && tiles[1] && they're both associated
1698 * and they're both associated with different dots,
1699 * ensure the line is set. */
1700 if (!(edge->flags & F_EDGE_SET) &&
1701 tiles[0] && tiles[1] &&
1702 (tiles[0]->flags & F_TILE_ASSOC) &&
1703 (tiles[1]->flags & F_TILE_ASSOC) &&
1704 (tiles[0]->dotx != tiles[1]->dotx ||
1705 tiles[0]->doty != tiles[1]->doty)) {
1706 /* No edge, but the two adjacent tiles are both
1707 * associated with different dots; add the edge. */
1708 solvep(("%*sSetting edge %d,%d - tiles different dots.\n",
1709 solver_recurse_depth*4, "", edge->x, edge->y));
1710 edge->flags |= F_EDGE_SET;
1714 if (!(edge->flags & F_EDGE_SET)) return didsth;
1715 for (n = 0; n < 2; n++) {
1716 if (!tiles[n]) continue;
1717 assert(tiles[n]->type == s_tile);
1718 if (!(tiles[n]->flags & F_TILE_ASSOC)) continue;
1720 tile_opp = tile_opposite(state, tiles[n]);
1722 solvep(("%*simpossible: edge %d,%d has assoc. tile %d,%d"
1723 " with no opposite.\n",
1724 solver_recurse_depth*4, "",
1725 edge->x, edge->y, tiles[n]->x, tiles[n]->y));
1726 /* edge of tile has no opposite edge (off grid?);
1727 * this is impossible. */
1731 dx = tiles[n]->x - edge->x;
1732 dy = tiles[n]->y - edge->y;
1733 assert(INGRID(state, tile_opp->x+dx, tile_opp->y+dy));
1734 edge_opp = &SPACE(state, tile_opp->x+dx, tile_opp->y+dy);
1735 if (!(edge_opp->flags & F_EDGE_SET)) {
1736 solvep(("%*sSetting edge %d,%d as opposite %d,%d\n",
1737 solver_recurse_depth*4, "",
1738 tile_opp->x-dx, tile_opp->y-dy, edge->x, edge->y));
1739 edge_opp->flags |= F_EDGE_SET;
1746 static int solver_spaces_oneposs_cb(game_state *state, space *tile, void *ctx)
1749 space *edgeadj[4], *tileadj[4];
1752 assert(tile->type == s_tile);
1753 if (tile->flags & F_TILE_ASSOC) return 0;
1755 adjacencies(state, tile, edgeadj, tileadj);
1757 /* Empty tile. If each edge is either set, or associated with
1758 * the same dot, we must also associate with dot. */
1759 eset = 0; dotx = -1; doty = -1;
1760 for (n = 0; n < 4; n++) {
1762 assert(edgeadj[n]->type == s_edge);
1763 if (edgeadj[n]->flags & F_EDGE_SET) {
1767 assert(tileadj[n]->type == s_tile);
1769 /* If an adjacent tile is empty we can't make any deductions.*/
1770 if (!(tileadj[n]->flags & F_TILE_ASSOC))
1773 /* If an adjacent tile is assoc. with a different dot
1774 * we can't make any deductions. */
1775 if (dotx != -1 && doty != -1 &&
1776 (tileadj[n]->dotx != dotx ||
1777 tileadj[n]->doty != doty))
1780 dotx = tileadj[n]->dotx;
1781 doty = tileadj[n]->doty;
1785 solvep(("%*simpossible: empty tile %d,%d has 4 edges\n",
1786 solver_recurse_depth*4, "",
1790 assert(dotx != -1 && doty != -1);
1792 ret = solver_add_assoc(state, tile, dotx, doty, "rest are edges");
1793 if (ret == -1) return -1;
1794 assert(ret != 0); /* really should have done something. */
1799 /* Improved algorithm for tracking line-of-sight from dots, and not spaces.
1801 * The solver_ctx already stores a list of dots: the algorithm proceeds by
1802 * expanding outwards from each dot in turn, expanding first to the boundary
1803 * of its currently-connected tile and then to all empty tiles that could see
1804 * it. Empty tiles will be flagged with a 'can see dot <x,y>' sticker.
1806 * Expansion will happen by (symmetrically opposite) pairs of squares; if
1807 * a square hasn't an opposite number there's no point trying to expand through
1808 * it. Empty tiles will therefore also be tagged in pairs.
1810 * If an empty tile already has a 'can see dot <x,y>' tag from a previous dot,
1811 * it (and its partner) gets untagged (or, rather, a 'can see two dots' tag)
1812 * because we're looking for single-dot possibilities.
1814 * Once we've gone through all the dots, any which still have a 'can see dot'
1815 * tag get associated with that dot (because it must have been the only one);
1816 * any without any tag (i.e. that could see _no_ dots) cause an impossibility
1819 * The expansion will happen each time with a stored list of (space *) pairs,
1820 * rather than a mark-and-sweep idea; that's horrifically inefficient.
1822 * expansion algorithm:
1824 * * allocate list of (space *) the size of s->sx*s->sy.
1825 * * allocate second grid for (flags, dotx, doty) size of sx*sy.
1827 * clear second grid (flags = 0, all dotx and doty = 0)
1828 * flags: F_REACHABLE, F_MULTIPLE
1831 * * for each dot, start with one pair of tiles that are associated with it --
1832 * * vertex --> (dx+1, dy+1), (dx-1, dy-1)
1833 * * edge --> (adj1, adj2)
1834 * * tile --> (tile, tile) ???
1835 * * mark that pair of tiles with F_MARK, clear all other F_MARKs.
1836 * * add two tiles to start of list.
1838 * set start = 0, end = next = 2
1840 * from (start to end-1, step 2) {
1841 * * we have two tiles (t1, t2), opposites wrt our dot.
1842 * * for each (at1) sensible adjacent tile to t1 (i.e. not past an edge):
1843 * * work out at2 as the opposite to at1
1844 * * assert at1 and at2 have the same F_MARK values.
1845 * * if at1 & F_MARK ignore it (we've been there on a previous sweep)
1846 * * if either are associated with a different dot
1847 * * mark both with F_MARK (so we ignore them later)
1848 * * otherwise (assoc. with our dot, or empty):
1849 * * mark both with F_MARK
1850 * * add their space * values to the end of the list, set next += 2.
1854 * * we didn't add any new squares; exit the loop.
1856 * * set start = next+1, end = next. go round again
1858 * We've finished expanding from the dot. Now, for each square we have
1859 * in our list (--> each square with F_MARK):
1860 * * if the tile is empty:
1861 * * if F_REACHABLE was already set
1864 * * set F_REACHABLE, set dotx and doty to our dot.
1866 * Then, continue the whole thing for each dot in turn.
1868 * Once we've done for each dot, go through the entire grid looking for
1869 * empty tiles: for each empty tile:
1870 * if F_REACHABLE and not F_MULTIPLE, set that dot (and its double)
1871 * if !F_REACHABLE, return as impossible.
1875 /* Returns 1 if this tile is either already associated with this dot,
1877 static int solver_expand_checkdot(space *tile, space *dot)
1879 if (!(tile->flags & F_TILE_ASSOC)) return 1;
1880 if (tile->dotx == dot->x && tile->doty == dot->y) return 1;
1884 static void solver_expand_fromdot(game_state *state, space *dot, solver_ctx *sctx)
1886 int i, j, x, y, start, end, next;
1889 /* Clear the grid of the (space) flags we'll use. */
1891 /* This is well optimised; analysis showed that:
1892 for (i = 0; i < sctx->sz; i++) state->grid[i].flags &= ~F_MARK;
1893 took up ~85% of the total function time! */
1894 for (y = 1; y < state->sy; y += 2) {
1895 sp = &SPACE(state, 1, y);
1896 for (x = 1; x < state->sx; x += 2, sp += 2)
1897 sp->flags &= ~F_MARK;
1900 /* Seed the list of marked squares with two that must be associated
1901 * with our dot (possibly the same space) */
1902 if (dot->type == s_tile) {
1903 sctx->scratch[0] = sctx->scratch[1] = dot;
1904 } else if (dot->type == s_edge) {
1905 tiles_from_edge(state, dot, sctx->scratch);
1906 } else if (dot->type == s_vertex) {
1907 /* pick two of the opposite ones arbitrarily. */
1908 sctx->scratch[0] = &SPACE(state, dot->x-1, dot->y-1);
1909 sctx->scratch[1] = &SPACE(state, dot->x+1, dot->y+1);
1911 assert(sctx->scratch[0]->flags & F_TILE_ASSOC);
1912 assert(sctx->scratch[1]->flags & F_TILE_ASSOC);
1914 sctx->scratch[0]->flags |= F_MARK;
1915 sctx->scratch[1]->flags |= F_MARK;
1917 debug(("%*sexpand from dot %d,%d seeded with %d,%d and %d,%d.\n",
1918 solver_recurse_depth*4, "", dot->x, dot->y,
1919 sctx->scratch[0]->x, sctx->scratch[0]->y,
1920 sctx->scratch[1]->x, sctx->scratch[1]->y));
1922 start = 0; end = 2; next = 2;
1925 debug(("%*sexpand: start %d, end %d, next %d\n",
1926 solver_recurse_depth*4, "", start, end, next));
1927 for (i = start; i < end; i += 2) {
1928 space *t1 = sctx->scratch[i]/*, *t2 = sctx->scratch[i+1]*/;
1929 space *edges[4], *tileadj[4], *tileadj2;
1931 adjacencies(state, t1, edges, tileadj);
1933 for (j = 0; j < 4; j++) {
1935 if (edges[j]->flags & F_EDGE_SET) continue;
1938 if (tileadj[j]->flags & F_MARK) continue; /* seen before. */
1940 /* We have a tile adjacent to t1; find its opposite. */
1941 tileadj2 = space_opposite_dot(state, tileadj[j], dot);
1943 debug(("%*sMarking %d,%d, no opposite.\n",
1944 solver_recurse_depth*4, "",
1945 tileadj[j]->x, tileadj[j]->y));
1946 tileadj[j]->flags |= F_MARK;
1947 continue; /* no opposite, so mark for next time. */
1949 /* If the tile had an opposite we should have either seen both of
1950 * these, or neither of these, before. */
1951 assert(!(tileadj2->flags & F_MARK));
1953 if (solver_expand_checkdot(tileadj[j], dot) &&
1954 solver_expand_checkdot(tileadj2, dot)) {
1955 /* Both tiles could associate with this dot; add them to
1957 debug(("%*sAdding %d,%d and %d,%d to possibles list.\n",
1958 solver_recurse_depth*4, "",
1959 tileadj[j]->x, tileadj[j]->y, tileadj2->x, tileadj2->y));
1960 sctx->scratch[next++] = tileadj[j];
1961 sctx->scratch[next++] = tileadj2;
1963 /* Either way, we've seen these tiles already so mark them. */
1964 debug(("%*sMarking %d,%d and %d,%d.\n",
1965 solver_recurse_depth*4, "",
1966 tileadj[j]->x, tileadj[j]->y, tileadj2->x, tileadj2->y));
1967 tileadj[j]->flags |= F_MARK;
1968 tileadj2->flags |= F_MARK;
1972 /* We added more squares; go back and try again. */
1973 start = end; end = next; goto expand;
1976 /* We've expanded as far as we can go. Now we update the main flags
1977 * on all tiles we've expanded into -- if they were empty, we have
1978 * found possible associations for this dot. */
1979 for (i = 0; i < end; i++) {
1980 if (sctx->scratch[i]->flags & F_TILE_ASSOC) continue;
1981 if (sctx->scratch[i]->flags & F_REACHABLE) {
1982 /* This is (at least) the second dot this tile could
1983 * associate with. */
1984 debug(("%*sempty tile %d,%d could assoc. other dot %d,%d\n",
1985 solver_recurse_depth*4, "",
1986 sctx->scratch[i]->x, sctx->scratch[i]->y, dot->x, dot->y));
1987 sctx->scratch[i]->flags |= F_MULTIPLE;
1989 /* This is the first (possibly only) dot. */
1990 debug(("%*sempty tile %d,%d could assoc. 1st dot %d,%d\n",
1991 solver_recurse_depth*4, "",
1992 sctx->scratch[i]->x, sctx->scratch[i]->y, dot->x, dot->y));
1993 sctx->scratch[i]->flags |= F_REACHABLE;
1994 sctx->scratch[i]->dotx = dot->x;
1995 sctx->scratch[i]->doty = dot->y;
2001 static int solver_expand_postcb(game_state *state, space *tile, void *ctx)
2003 assert(tile->type == s_tile);
2005 if (tile->flags & F_TILE_ASSOC) return 0;
2007 if (!(tile->flags & F_REACHABLE)) {
2008 solvep(("%*simpossible: space (%d,%d) can reach no dots.\n",
2009 solver_recurse_depth*4, "", tile->x, tile->y));
2012 if (tile->flags & F_MULTIPLE) return 0;
2014 return solver_add_assoc(state, tile, tile->dotx, tile->doty,
2015 "single possible dot after expansion");
2018 static int solver_expand_dots(game_state *state, solver_ctx *sctx)
2022 for (i = 0; i < sctx->sz; i++)
2023 state->grid[i].flags &= ~(F_REACHABLE|F_MULTIPLE);
2025 for (i = 0; i < state->ndots; i++)
2026 solver_expand_fromdot(state, state->dots[i], sctx);
2028 return foreach_tile(state, solver_expand_postcb, IMPOSSIBLE_QUITS, sctx);
2031 struct recurse_ctx {
2036 static int solver_recurse_cb(game_state *state, space *tile, void *ctx)
2038 struct recurse_ctx *rctx = (struct recurse_ctx *)ctx;
2041 assert(tile->type == s_tile);
2042 if (tile->flags & F_TILE_ASSOC) return 0;
2044 /* We're unassociated: count up all the dots we could associate with. */
2045 for (i = 0; i < state->ndots; i++) {
2046 if (dotfortile(state, tile, state->dots[i]))
2049 if (n > rctx->bestn) {
2056 #define MAXRECURSE 5
2058 static int solver_recurse(game_state *state, int maxdiff)
2060 int diff = DIFF_IMPOSSIBLE, ret, n, gsz = state->sx * state->sy;
2061 space *ingrid, *outgrid = NULL, *bestopp;
2062 struct recurse_ctx rctx;
2064 if (solver_recurse_depth >= MAXRECURSE) {
2065 solvep(("Limiting recursion to %d, returning.", MAXRECURSE));
2066 return DIFF_UNFINISHED;
2069 /* Work out the cell to recurse on; go through all unassociated tiles
2070 * and find which one has the most possible dots it could associate
2075 foreach_tile(state, solver_recurse_cb, 0, &rctx);
2076 if (rctx.bestn == 0) return DIFF_IMPOSSIBLE; /* or assert? */
2079 solvep(("%*sRecursing around %d,%d, with %d possible dots.\n",
2080 solver_recurse_depth*4, "",
2081 rctx.best->x, rctx.best->y, rctx.bestn));
2083 #ifdef STANDALONE_SOLVER
2084 solver_recurse_depth++;
2087 ingrid = snewn(gsz, space);
2088 memcpy(ingrid, state->grid, gsz * sizeof(space));
2090 for (n = 0; n < state->ndots; n++) {
2091 memcpy(state->grid, ingrid, gsz * sizeof(space));
2093 if (!dotfortile(state, rctx.best, state->dots[n])) continue;
2095 /* set cell (temporarily) pointing to that dot. */
2096 solver_add_assoc(state, rctx.best,
2097 state->dots[n]->x, state->dots[n]->y,
2098 "Attempting for recursion");
2100 ret = solver_state(state, maxdiff);
2102 if (diff == DIFF_IMPOSSIBLE && ret != DIFF_IMPOSSIBLE) {
2103 /* we found our first solved grid; copy it away. */
2105 outgrid = snewn(gsz, space);
2106 memcpy(outgrid, state->grid, gsz * sizeof(space));
2108 /* reset cell back to unassociated. */
2109 bestopp = tile_opposite(state, rctx.best);
2110 assert(bestopp && bestopp->flags & F_TILE_ASSOC);
2112 remove_assoc(state, rctx.best);
2113 remove_assoc(state, bestopp);
2115 if (ret == DIFF_AMBIGUOUS || ret == DIFF_UNFINISHED)
2117 else if (ret == DIFF_IMPOSSIBLE)
2120 /* precisely one solution */
2121 if (diff == DIFF_IMPOSSIBLE)
2122 diff = DIFF_UNREASONABLE;
2124 diff = DIFF_AMBIGUOUS;
2126 /* if we've found >1 solution, or ran out of recursion,
2127 * give up immediately. */
2128 if (diff == DIFF_AMBIGUOUS || diff == DIFF_UNFINISHED)
2132 #ifdef STANDALONE_SOLVER
2133 solver_recurse_depth--;
2137 /* we found (at least one) soln; copy it back to state */
2138 memcpy(state->grid, outgrid, gsz * sizeof(space));
2145 static int solver_state(game_state *state, int maxdiff)
2147 solver_ctx *sctx = new_solver(state);
2148 int ret, diff = DIFF_NORMAL;
2150 #ifdef STANDALONE_PICTURE_GENERATOR
2151 /* hack, hack: set picture to NULL during solving so that add_assoc
2152 * won't complain when we attempt recursive guessing and guess wrong */
2153 int *savepic = picture;
2157 ret = solver_obvious(state);
2159 diff = DIFF_IMPOSSIBLE;
2163 #define CHECKRET(d) do { \
2164 if (ret < 0) { diff = DIFF_IMPOSSIBLE; goto got_result; } \
2165 if (ret > 0) { diff = max(diff, (d)); goto cont; } \
2170 ret = foreach_edge(state, solver_lines_opposite_cb,
2171 IMPOSSIBLE_QUITS, sctx);
2172 CHECKRET(DIFF_NORMAL);
2174 ret = foreach_tile(state, solver_spaces_oneposs_cb,
2175 IMPOSSIBLE_QUITS, sctx);
2176 CHECKRET(DIFF_NORMAL);
2178 ret = solver_expand_dots(state, sctx);
2179 CHECKRET(DIFF_NORMAL);
2181 if (maxdiff <= DIFF_NORMAL)
2186 /* if we reach here, we've made no deductions, so we terminate. */
2190 if (check_complete(state, NULL, NULL)) goto got_result;
2192 diff = (maxdiff >= DIFF_UNREASONABLE) ?
2193 solver_recurse(state, maxdiff) : DIFF_UNFINISHED;
2197 #ifndef STANDALONE_SOLVER
2198 debug(("solver_state ends, diff %s:\n", galaxies_diffnames[diff]));
2202 #ifdef STANDALONE_PICTURE_GENERATOR
2210 static char *solve_game(const game_state *state, const game_state *currstate,
2211 const char *aux, char **error)
2213 game_state *tosolve;
2218 tosolve = dup_game(currstate);
2219 diff = solver_state(tosolve, DIFF_UNREASONABLE);
2220 if (diff != DIFF_UNFINISHED && diff != DIFF_IMPOSSIBLE) {
2221 debug(("solve_game solved with current state.\n"));
2226 tosolve = dup_game(state);
2227 diff = solver_state(tosolve, DIFF_UNREASONABLE);
2228 if (diff != DIFF_UNFINISHED && diff != DIFF_IMPOSSIBLE) {
2229 debug(("solve_game solved with original state.\n"));
2238 * Clear tile associations: the solution will only include the
2241 for (i = 0; i < tosolve->sx*tosolve->sy; i++)
2242 tosolve->grid[i].flags &= ~F_TILE_ASSOC;
2243 ret = diff_game(currstate, tosolve, 1);
2249 /* ----------------------------------------------------------
2255 int dx, dy; /* pixel coords of drag pos. */
2256 int dotx, doty; /* grid coords of dot we're dragging from. */
2257 int srcx, srcy; /* grid coords of drag start */
2258 int cur_x, cur_y, cur_visible;
2261 static game_ui *new_ui(const game_state *state)
2263 game_ui *ui = snew(game_ui);
2264 ui->dragging = FALSE;
2265 ui->cur_x = ui->cur_y = 1;
2266 ui->cur_visible = 0;
2270 static void free_ui(game_ui *ui)
2275 static char *encode_ui(const game_ui *ui)
2280 static void decode_ui(game_ui *ui, const char *encoding)
2284 static void game_changed_state(game_ui *ui, const game_state *oldstate,
2285 const game_state *newstate)
2289 #define FLASH_TIME 0.15F
2291 #define PREFERRED_TILE_SIZE 32
2292 #define TILE_SIZE (ds->tilesize)
2293 #define DOT_SIZE (TILE_SIZE / 4)
2294 #define EDGE_THICKNESS (max(TILE_SIZE / 16, 2))
2295 #define BORDER TILE_SIZE
2297 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
2298 #define SCOORD(x) ( ((x) * TILE_SIZE)/2 + BORDER )
2299 #define FROMCOORD(x) ( ((x) - BORDER) / TILE_SIZE )
2301 #define DRAW_WIDTH (BORDER * 2 + ds->w * TILE_SIZE)
2302 #define DRAW_HEIGHT (BORDER * 2 + ds->h * TILE_SIZE)
2304 #define CURSOR_SIZE DOT_SIZE
2306 struct game_drawstate {
2310 unsigned long *grid;
2314 int dragging, dragx, dragy;
2316 int *colour_scratch;
2318 int cx, cy, cur_visible;
2322 #define CORNER_TOLERANCE 0.15F
2323 #define CENTRE_TOLERANCE 0.15F
2326 * Round FP coordinates to the centre of the nearest edge.
2329 static void coord_round_to_edge(float x, float y, int *xr, int *yr)
2331 float xs, ys, xv, yv, dx, dy;
2334 * Find the nearest square-centre.
2336 xs = (float)floor(x) + 0.5F;
2337 ys = (float)floor(y) + 0.5F;
2340 * Find the nearest grid vertex.
2342 xv = (float)floor(x + 0.5F);
2343 yv = (float)floor(y + 0.5F);
2346 * Determine whether the horizontal or vertical edge from that
2347 * vertex alongside that square is closer to us, by comparing
2348 * distances from the square cente.
2350 dx = (float)fabs(x - xs);
2351 dy = (float)fabs(y - ys);
2353 /* Vertical edge: x-coord of corner,
2354 * y-coord of square centre. */
2356 *yr = 1 + 2 * (int)floor(ys);
2358 /* Horizontal edge: x-coord of square centre,
2359 * y-coord of corner. */
2360 *xr = 1 + 2 * (int)floor(xs);
2367 static char *interpret_move(const game_state *state, game_ui *ui,
2368 const game_drawstate *ds,
2369 int x, int y, int button)
2375 px = 2*FROMCOORD((float)x) + 0.5;
2376 py = 2*FROMCOORD((float)y) + 0.5;
2380 if (button == 'C' || button == 'c') return dupstr("C");
2382 if (button == 'S' || button == 's') {
2384 game_state *tmp = dup_game(state);
2385 state->cdiff = solver_state(tmp, DIFF_UNREASONABLE-1);
2386 ret = diff_game(state, tmp, 0);
2391 if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
2392 if (!INUI(state, px, py)) return NULL;
2393 sp = &SPACE(state, px, py);
2394 if (!dot_is_possible(state, sp, 1)) return NULL;
2395 sprintf(buf, "%c%d,%d",
2396 (char)((button == LEFT_BUTTON) ? 'D' : 'd'), px, py);
2403 static char *interpret_move(const game_state *state, game_ui *ui,
2404 const game_drawstate *ds,
2405 int x, int y, int button)
2407 /* UI operations (play mode):
2409 * Toggle edge (set/unset) (left-click on edge)
2410 * Associate space with dot (left-drag from dot)
2411 * Unassociate space (left-drag from space off grid)
2412 * Autofill lines around shape? (right-click?)
2414 * (edit mode; will clear all lines/associations)
2416 * Add or remove dot (left-click)
2419 const char *sep = "";
2425 if (button == 'H' || button == 'h') {
2427 game_state *tmp = dup_game(state);
2428 solver_obvious(tmp);
2429 ret = diff_game(state, tmp, 0);
2434 if (button == LEFT_BUTTON) {
2435 ui->cur_visible = 0;
2436 coord_round_to_edge(FROMCOORD((float)x), FROMCOORD((float)y),
2439 if (!INUI(state, px, py)) return NULL;
2441 sp = &SPACE(state, px, py);
2442 assert(sp->type == s_edge);
2444 sprintf(buf, "E%d,%d", px, py);
2447 } else if (button == RIGHT_BUTTON) {
2450 ui->cur_visible = 0;
2452 px = (int)(2*FROMCOORD((float)x) + 0.5);
2453 py = (int)(2*FROMCOORD((float)y) + 0.5);
2458 * If there's a dot anywhere nearby, we pick up an arrow
2459 * pointing at that dot.
2461 for (py1 = py-1; py1 <= py+1; py1++)
2462 for (px1 = px-1; px1 <= px+1; px1++) {
2463 if (px1 >= 0 && px1 < state->sx &&
2464 py1 >= 0 && py1 < state->sy &&
2465 x >= SCOORD(px1-1) && x < SCOORD(px1+1) &&
2466 y >= SCOORD(py1-1) && y < SCOORD(py1+1) &&
2467 SPACE(state, px1, py1).flags & F_DOT) {
2469 * Found a dot. Begin a drag from it.
2471 dot = &SPACE(state, px1, py1);
2474 goto done; /* multi-level break */
2479 * Otherwise, find the nearest _square_, and pick up the
2480 * same arrow as it's got on it, if any.
2483 px = 2*FROMCOORD(x+TILE_SIZE) - 1;
2484 py = 2*FROMCOORD(y+TILE_SIZE) - 1;
2485 if (px >= 0 && px < state->sx && py >= 0 && py < state->sy) {
2486 sp = &SPACE(state, px, py);
2487 if (sp->flags & F_TILE_ASSOC) {
2488 dot = &SPACE(state, sp->dotx, sp->doty);
2497 * Now, if we've managed to find a dot, begin a drag.
2500 ui->dragging = TRUE;
2507 } else if (button == RIGHT_DRAG && ui->dragging) {
2508 /* just move the drag coords. */
2512 } else if (button == RIGHT_RELEASE && ui->dragging) {
2513 ui->dragging = FALSE;
2516 * Drags are always targeted at a single square.
2518 px = 2*FROMCOORD(x+TILE_SIZE) - 1;
2519 py = 2*FROMCOORD(y+TILE_SIZE) - 1;
2522 * Dragging an arrow on to the same square it started from
2523 * is a null move; just update the ui and finish.
2525 if (px == ui->srcx && py == ui->srcy)
2529 * Otherwise, we remove the arrow from its starting
2530 * square if we didn't start from a dot...
2532 if ((ui->srcx != ui->dotx || ui->srcy != ui->doty) &&
2533 SPACE(state, ui->srcx, ui->srcy).flags & F_TILE_ASSOC) {
2534 sprintf(buf + strlen(buf), "%sU%d,%d", sep, ui->srcx, ui->srcy);
2539 * ... and if the square we're moving it _to_ is valid, we
2540 * add one there instead.
2542 if (INUI(state, px, py)) {
2543 sp = &SPACE(state, px, py);
2545 if (!(sp->flags & F_DOT) && !(sp->flags & F_TILE_ASSOC))
2546 sprintf(buf + strlen(buf), "%sA%d,%d,%d,%d",
2547 sep, px, py, ui->dotx, ui->doty);
2554 } else if (IS_CURSOR_MOVE(button)) {
2555 move_cursor(button, &ui->cur_x, &ui->cur_y, state->sx-1, state->sy-1, 0);
2556 if (ui->cur_x < 1) ui->cur_x = 1;
2557 if (ui->cur_y < 1) ui->cur_y = 1;
2558 ui->cur_visible = 1;
2560 ui->dx = SCOORD(ui->cur_x);
2561 ui->dy = SCOORD(ui->cur_y);
2564 } else if (IS_CURSOR_SELECT(button)) {
2565 if (!ui->cur_visible) {
2566 ui->cur_visible = 1;
2569 sp = &SPACE(state, ui->cur_x, ui->cur_y);
2571 ui->dragging = FALSE;
2573 if ((ui->srcx != ui->dotx || ui->srcy != ui->doty) &&
2574 SPACE(state, ui->srcx, ui->srcy).flags & F_TILE_ASSOC) {
2575 sprintf(buf, "%sU%d,%d", sep, ui->srcx, ui->srcy);
2578 if (sp->type == s_tile && !(sp->flags & F_DOT) && !(sp->flags & F_TILE_ASSOC)) {
2579 sprintf(buf + strlen(buf), "%sA%d,%d,%d,%d",
2580 sep, ui->cur_x, ui->cur_y, ui->dotx, ui->doty);
2583 } else if (sp->flags & F_DOT) {
2584 ui->dragging = TRUE;
2585 ui->dx = SCOORD(ui->cur_x);
2586 ui->dy = SCOORD(ui->cur_y);
2587 ui->dotx = ui->srcx = ui->cur_x;
2588 ui->doty = ui->srcy = ui->cur_y;
2590 } else if (sp->flags & F_TILE_ASSOC) {
2591 assert(sp->type == s_tile);
2592 ui->dragging = TRUE;
2593 ui->dx = SCOORD(ui->cur_x);
2594 ui->dy = SCOORD(ui->cur_y);
2595 ui->dotx = sp->dotx;
2596 ui->doty = sp->doty;
2597 ui->srcx = ui->cur_x;
2598 ui->srcy = ui->cur_y;
2600 } else if (sp->type == s_edge) {
2601 sprintf(buf, "E%d,%d", ui->cur_x, ui->cur_y);
2610 static int check_complete(const game_state *state, int *dsf, int *colours)
2612 int w = state->w, h = state->h;
2617 int minx, miny, maxx, maxy;
2623 dsf = snew_dsf(w*h);
2631 * During actual game play, completion checking is done on the
2632 * basis of the edges rather than the square associations. So
2633 * first we must go through the grid figuring out the connected
2634 * components into which the edges divide it.
2636 for (y = 0; y < h; y++)
2637 for (x = 0; x < w; x++) {
2638 if (y+1 < h && !(SPACE(state, 2*x+1, 2*y+2).flags & F_EDGE_SET))
2639 dsf_merge(dsf, y*w+x, (y+1)*w+x);
2640 if (x+1 < w && !(SPACE(state, 2*x+2, 2*y+1).flags & F_EDGE_SET))
2641 dsf_merge(dsf, y*w+x, y*w+(x+1));
2645 * That gives us our connected components. Now, for each
2646 * component, decide whether it's _valid_. A valid component is
2649 * - is 180-degree rotationally symmetric
2650 * - has a dot at its centre of symmetry
2651 * - has no other dots anywhere within it (including on its
2653 * - contains no internal edges (i.e. edges separating two
2654 * squares which are both part of the component).
2658 * First, go through the grid finding the bounding box of each
2661 sqdata = snewn(w*h, struct sqdata);
2662 for (i = 0; i < w*h; i++) {
2663 sqdata[i].minx = w+1;
2664 sqdata[i].miny = h+1;
2665 sqdata[i].maxx = sqdata[i].maxy = -1;
2666 sqdata[i].valid = FALSE;
2668 for (y = 0; y < h; y++)
2669 for (x = 0; x < w; x++) {
2670 i = dsf_canonify(dsf, y*w+x);
2671 if (sqdata[i].minx > x)
2673 if (sqdata[i].maxx < x)
2675 if (sqdata[i].miny > y)
2677 if (sqdata[i].maxy < y)
2679 sqdata[i].valid = TRUE;
2683 * Now we're in a position to loop over each actual component
2684 * and figure out where its centre of symmetry has to be if
2687 for (i = 0; i < w*h; i++)
2688 if (sqdata[i].valid) {
2690 cx = sqdata[i].cx = sqdata[i].minx + sqdata[i].maxx + 1;
2691 cy = sqdata[i].cy = sqdata[i].miny + sqdata[i].maxy + 1;
2692 if (!(SPACE(state, sqdata[i].cx, sqdata[i].cy).flags & F_DOT))
2693 sqdata[i].valid = FALSE; /* no dot at centre of symmetry */
2694 if (dsf_canonify(dsf, (cy-1)/2*w+(cx-1)/2) != i ||
2695 dsf_canonify(dsf, (cy)/2*w+(cx-1)/2) != i ||
2696 dsf_canonify(dsf, (cy-1)/2*w+(cx)/2) != i ||
2697 dsf_canonify(dsf, (cy)/2*w+(cx)/2) != i)
2698 sqdata[i].valid = FALSE; /* dot at cx,cy isn't ours */
2699 if (SPACE(state, sqdata[i].cx, sqdata[i].cy).flags & F_DOT_BLACK)
2700 sqdata[i].colour = 2;
2702 sqdata[i].colour = 1;
2706 * Now we loop over the whole grid again, this time finding
2707 * extraneous dots (any dot which wholly or partially overlaps
2708 * a square and is not at the centre of symmetry of that
2709 * square's component disqualifies the component from validity)
2710 * and extraneous edges (any edge separating two squares
2711 * belonging to the same component also disqualifies that
2714 for (y = 1; y < state->sy-1; y++)
2715 for (x = 1; x < state->sx-1; x++) {
2716 space *sp = &SPACE(state, x, y);
2718 if (sp->flags & F_DOT) {
2720 * There's a dot here. Use it to disqualify any
2721 * component which deserves it.
2724 for (cy = (y-1) >> 1; cy <= y >> 1; cy++)
2725 for (cx = (x-1) >> 1; cx <= x >> 1; cx++) {
2726 i = dsf_canonify(dsf, cy*w+cx);
2727 if (x != sqdata[i].cx || y != sqdata[i].cy)
2728 sqdata[i].valid = FALSE;
2732 if (sp->flags & F_EDGE_SET) {
2734 * There's an edge here. Use it to disqualify a
2735 * component if necessary.
2737 int cx1 = (x-1) >> 1, cx2 = x >> 1;
2738 int cy1 = (y-1) >> 1, cy2 = y >> 1;
2739 assert((cx1==cx2) ^ (cy1==cy2));
2740 i = dsf_canonify(dsf, cy1*w+cx1);
2741 if (i == dsf_canonify(dsf, cy2*w+cx2))
2742 sqdata[i].valid = FALSE;
2747 * And finally we test rotational symmetry: for each square in
2748 * the grid, find which component it's in, test that that
2749 * component also has a square in the symmetric position, and
2750 * disqualify it if it doesn't.
2752 for (y = 0; y < h; y++)
2753 for (x = 0; x < w; x++) {
2756 i = dsf_canonify(dsf, y*w+x);
2758 x2 = sqdata[i].cx - 1 - x;
2759 y2 = sqdata[i].cy - 1 - y;
2760 if (i != dsf_canonify(dsf, y2*w+x2))
2761 sqdata[i].valid = FALSE;
2765 * That's it. We now have all the connected components marked
2766 * as valid or not valid. So now we return a `colours' array if
2767 * we were asked for one, and also we return an overall
2768 * true/false value depending on whether _every_ square in the
2769 * grid is part of a valid component.
2772 for (i = 0; i < w*h; i++) {
2773 int ci = dsf_canonify(dsf, i);
2774 int thisok = sqdata[ci].valid;
2776 colours[i] = thisok ? sqdata[ci].colour : 0;
2777 ret = ret && thisok;
2787 static game_state *execute_move(const game_state *state, const char *move)
2789 int x, y, ax, ay, n, dx, dy;
2790 game_state *ret = dup_game(state);
2793 debug(("%s\n", move));
2797 if (c == 'E' || c == 'U' || c == 'M'
2799 || c == 'D' || c == 'd'
2803 if (sscanf(move, "%d,%d%n", &x, &y, &n) != 2 ||
2807 sp = &SPACE(ret, x, y);
2809 if (c == 'D' || c == 'd') {
2810 unsigned int currf, newf, maskf;
2812 if (!dot_is_possible(ret, sp, 1)) goto badmove;
2814 newf = F_DOT | (c == 'd' ? F_DOT_BLACK : 0);
2815 currf = GRID(ret, grid, x, y).flags;
2816 maskf = F_DOT | F_DOT_BLACK;
2817 /* if we clicked 'white dot':
2818 * white --> empty, empty --> white, black --> white.
2819 * if we clicked 'black dot':
2820 * black --> empty, empty --> black, white --> black.
2822 if (currf & maskf) {
2823 sp->flags &= ~maskf;
2824 if ((currf & maskf) != newf)
2828 sp->nassoc = 0; /* edit-mode disallows associations. */
2829 game_update_dots(ret);
2833 if (sp->type != s_edge) goto badmove;
2834 sp->flags ^= F_EDGE_SET;
2835 } else if (c == 'U') {
2836 if (sp->type != s_tile || !(sp->flags & F_TILE_ASSOC))
2838 remove_assoc(ret, sp);
2839 } else if (c == 'M') {
2840 if (!(sp->flags & F_DOT)) goto badmove;
2841 sp->flags ^= F_DOT_HOLD;
2844 } else if (c == 'A' || c == 'a') {
2846 if (sscanf(move, "%d,%d,%d,%d%n", &x, &y, &ax, &ay, &n) != 4 ||
2847 x < 1 || y < 1 || x >= (ret->sx-1) || y >= (ret->sy-1) ||
2848 ax < 1 || ay < 1 || ax >= (ret->sx-1) || ay >= (ret->sy-1))
2851 dot = &GRID(ret, grid, ax, ay);
2852 if (!(dot->flags & F_DOT))goto badmove;
2853 if (dot->flags & F_DOT_HOLD) goto badmove;
2855 for (dx = -1; dx <= 1; dx++) {
2856 for (dy = -1; dy <= 1; dy++) {
2857 sp = &GRID(ret, grid, x+dx, y+dy);
2858 if (sp->type != s_tile) continue;
2859 if (sp->flags & F_TILE_ASSOC) {
2860 space *dot = &SPACE(ret, sp->dotx, sp->doty);
2861 if (dot->flags & F_DOT_HOLD) continue;
2863 add_assoc(ret, sp, dot);
2868 } else if (c == 'C') {
2872 } else if (c == 'S') {
2874 ret->used_solve = 1;
2883 if (check_complete(ret, NULL, NULL))
2892 /* ----------------------------------------------------------------------
2896 /* Lines will be much smaller size than squares; say, 1/8 the size?
2898 * Need a 'top-left corner of location XxY' to take this into account;
2899 * alternaticaly, that could give the middle of that location, and the
2900 * drawing code would just know the expected dimensions.
2902 * We also need something to take a click and work out what it was
2903 * we were interested in. Clicking on vertices is required because
2904 * we may want to drag from them, for example.
2907 static void game_compute_size(const game_params *params, int sz,
2910 struct { int tilesize, w, h; } ads, *ds = &ads;
2920 static void game_set_size(drawing *dr, game_drawstate *ds,
2921 const game_params *params, int sz)
2925 assert(TILE_SIZE > 0);
2928 ds->bl = blitter_new(dr, TILE_SIZE, TILE_SIZE);
2930 assert(!ds->cur_bl);
2931 ds->cur_bl = blitter_new(dr, TILE_SIZE, TILE_SIZE);
2934 static float *game_colours(frontend *fe, int *ncolours)
2936 float *ret = snewn(3 * NCOLOURS, float);
2940 * We call game_mkhighlight to ensure the background colour
2941 * isn't completely white. We don't actually use the high- and
2942 * lowlight colours it generates.
2944 game_mkhighlight(fe, ret, COL_BACKGROUND, COL_WHITEBG, COL_BLACKBG);
2946 for (i = 0; i < 3; i++) {
2948 * Currently, white dots and white-background squares are
2951 ret[COL_WHITEDOT * 3 + i] = 1.0F;
2952 ret[COL_WHITEBG * 3 + i] = 1.0F;
2955 * But black-background squares are a dark grey, whereas
2956 * black dots are really black.
2958 ret[COL_BLACKDOT * 3 + i] = 0.0F;
2959 ret[COL_BLACKBG * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.3F;
2962 * In unfilled squares, we draw a faint gridwork.
2964 ret[COL_GRID * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.8F;
2967 * Edges and arrows are filled in in pure black.
2969 ret[COL_EDGE * 3 + i] = 0.0F;
2970 ret[COL_ARROW * 3 + i] = 0.0F;
2974 /* tinge the edit background to bluey */
2975 ret[COL_BACKGROUND * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2976 ret[COL_BACKGROUND * 3 + 1] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2977 ret[COL_BACKGROUND * 3 + 2] = min(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
2980 ret[COL_CURSOR * 3 + 0] = min(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
2981 ret[COL_CURSOR * 3 + 1] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2982 ret[COL_CURSOR * 3 + 2] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2984 *ncolours = NCOLOURS;
2988 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
2990 struct game_drawstate *ds = snew(struct game_drawstate);
2997 ds->grid = snewn(ds->w*ds->h, unsigned long);
2998 for (i = 0; i < ds->w*ds->h; i++)
2999 ds->grid[i] = 0xFFFFFFFFUL;
3000 ds->dx = snewn(ds->w*ds->h, int);
3001 ds->dy = snewn(ds->w*ds->h, int);
3004 ds->dragging = FALSE;
3005 ds->dragx = ds->dragy = 0;
3007 ds->colour_scratch = snewn(ds->w * ds->h, int);
3010 ds->cx = ds->cy = 0;
3011 ds->cur_visible = 0;
3016 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
3018 if (ds->cur_bl) blitter_free(dr, ds->cur_bl);
3019 sfree(ds->colour_scratch);
3020 if (ds->bl) blitter_free(dr, ds->bl);
3027 #define DRAW_EDGE_L 0x0001
3028 #define DRAW_EDGE_R 0x0002
3029 #define DRAW_EDGE_U 0x0004
3030 #define DRAW_EDGE_D 0x0008
3031 #define DRAW_CORNER_UL 0x0010
3032 #define DRAW_CORNER_UR 0x0020
3033 #define DRAW_CORNER_DL 0x0040
3034 #define DRAW_CORNER_DR 0x0080
3035 #define DRAW_WHITE 0x0100
3036 #define DRAW_BLACK 0x0200
3037 #define DRAW_ARROW 0x0400
3038 #define DRAW_CURSOR 0x0800
3039 #define DOT_SHIFT_C 12
3040 #define DOT_SHIFT_M 2
3041 #define DOT_WHITE 1UL
3042 #define DOT_BLACK 2UL
3045 * Draw an arrow centred on (cx,cy), pointing in the direction
3046 * (ddx,ddy). (I.e. pointing at the point (cx+ddx, cy+ddy).
3048 static void draw_arrow(drawing *dr, game_drawstate *ds,
3049 int cx, int cy, int ddx, int ddy, int col)
3051 float vlen = (float)sqrt(ddx*ddx+ddy*ddy);
3052 float xdx = ddx/vlen, xdy = ddy/vlen;
3053 float ydx = -xdy, ydy = xdx;
3054 int e1x = cx + (int)(xdx*TILE_SIZE/3), e1y = cy + (int)(xdy*TILE_SIZE/3);
3055 int e2x = cx - (int)(xdx*TILE_SIZE/3), e2y = cy - (int)(xdy*TILE_SIZE/3);
3056 int adx = (int)((ydx-xdx)*TILE_SIZE/8), ady = (int)((ydy-xdy)*TILE_SIZE/8);
3057 int adx2 = (int)((-ydx-xdx)*TILE_SIZE/8), ady2 = (int)((-ydy-xdy)*TILE_SIZE/8);
3059 draw_line(dr, e1x, e1y, e2x, e2y, col);
3060 draw_line(dr, e1x, e1y, e1x+adx, e1y+ady, col);
3061 draw_line(dr, e1x, e1y, e1x+adx2, e1y+ady2, col);
3064 static void draw_square(drawing *dr, game_drawstate *ds, int x, int y,
3065 unsigned long flags, int ddx, int ddy)
3067 int lx = COORD(x), ly = COORD(y);
3071 clip(dr, lx, ly, TILE_SIZE, TILE_SIZE);
3074 * Draw the tile background.
3076 draw_rect(dr, lx, ly, TILE_SIZE, TILE_SIZE,
3077 (flags & DRAW_WHITE ? COL_WHITEBG :
3078 flags & DRAW_BLACK ? COL_BLACKBG : COL_BACKGROUND));
3083 gridcol = (flags & DRAW_BLACK ? COL_BLACKDOT : COL_GRID);
3084 draw_rect(dr, lx, ly, 1, TILE_SIZE, gridcol);
3085 draw_rect(dr, lx, ly, TILE_SIZE, 1, gridcol);
3088 * Draw the arrow, if present, or the cursor, if here.
3090 if (flags & DRAW_ARROW)
3091 draw_arrow(dr, ds, lx + TILE_SIZE/2, ly + TILE_SIZE/2, ddx, ddy,
3092 (flags & DRAW_CURSOR) ? COL_CURSOR : COL_ARROW);
3093 else if (flags & DRAW_CURSOR)
3094 draw_rect_outline(dr,
3095 lx + TILE_SIZE/2 - CURSOR_SIZE,
3096 ly + TILE_SIZE/2 - CURSOR_SIZE,
3097 2*CURSOR_SIZE+1, 2*CURSOR_SIZE+1,
3103 if (flags & DRAW_EDGE_L)
3104 draw_rect(dr, lx, ly, EDGE_THICKNESS, TILE_SIZE, COL_EDGE);
3105 if (flags & DRAW_EDGE_R)
3106 draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1, ly,
3107 EDGE_THICKNESS - 1, TILE_SIZE, COL_EDGE);
3108 if (flags & DRAW_EDGE_U)
3109 draw_rect(dr, lx, ly, TILE_SIZE, EDGE_THICKNESS, COL_EDGE);
3110 if (flags & DRAW_EDGE_D)
3111 draw_rect(dr, lx, ly + TILE_SIZE - EDGE_THICKNESS + 1,
3112 TILE_SIZE, EDGE_THICKNESS - 1, COL_EDGE);
3113 if (flags & DRAW_CORNER_UL)
3114 draw_rect(dr, lx, ly, EDGE_THICKNESS, EDGE_THICKNESS, COL_EDGE);
3115 if (flags & DRAW_CORNER_UR)
3116 draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1, ly,
3117 EDGE_THICKNESS - 1, EDGE_THICKNESS, COL_EDGE);
3118 if (flags & DRAW_CORNER_DL)
3119 draw_rect(dr, lx, ly + TILE_SIZE - EDGE_THICKNESS + 1,
3120 EDGE_THICKNESS, EDGE_THICKNESS - 1, COL_EDGE);
3121 if (flags & DRAW_CORNER_DR)
3122 draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1,
3123 ly + TILE_SIZE - EDGE_THICKNESS + 1,
3124 EDGE_THICKNESS - 1, EDGE_THICKNESS - 1, COL_EDGE);
3129 for (dy = 0; dy < 3; dy++)
3130 for (dx = 0; dx < 3; dx++) {
3131 int dotval = (flags >> (DOT_SHIFT_C + DOT_SHIFT_M*(dy*3+dx)));
3132 dotval &= (1 << DOT_SHIFT_M)-1;
3135 draw_circle(dr, lx+dx*TILE_SIZE/2, ly+dy*TILE_SIZE/2,
3137 (dotval == 1 ? COL_WHITEDOT : COL_BLACKDOT),
3142 draw_update(dr, lx, ly, TILE_SIZE, TILE_SIZE);
3145 static void game_redraw(drawing *dr, game_drawstate *ds,
3146 const game_state *oldstate, const game_state *state,
3147 int dir, const game_ui *ui,
3148 float animtime, float flashtime)
3150 int w = ds->w, h = ds->h;
3151 int x, y, flashing = FALSE;
3153 if (flashtime > 0) {
3154 int frame = (int)(flashtime / FLASH_TIME);
3155 flashing = (frame % 2 == 0);
3160 blitter_load(dr, ds->bl, ds->dragx, ds->dragy);
3161 draw_update(dr, ds->dragx, ds->dragy, TILE_SIZE, TILE_SIZE);
3162 ds->dragging = FALSE;
3164 if (ds->cur_visible) {
3166 blitter_load(dr, ds->cur_bl, ds->cx, ds->cy);
3167 draw_update(dr, ds->cx, ds->cy, CURSOR_SIZE*2+1, CURSOR_SIZE*2+1);
3168 ds->cur_visible = FALSE;
3172 draw_rect(dr, 0, 0, DRAW_WIDTH, DRAW_HEIGHT, COL_BACKGROUND);
3173 draw_rect(dr, BORDER - EDGE_THICKNESS + 1, BORDER - EDGE_THICKNESS + 1,
3174 w*TILE_SIZE + EDGE_THICKNESS*2 - 1,
3175 h*TILE_SIZE + EDGE_THICKNESS*2 - 1, COL_EDGE);
3176 draw_update(dr, 0, 0, DRAW_WIDTH, DRAW_HEIGHT);
3180 check_complete(state, NULL, ds->colour_scratch);
3182 for (y = 0; y < h; y++)
3183 for (x = 0; x < w; x++) {
3184 unsigned long flags = 0;
3185 int ddx = 0, ddy = 0;
3190 * Set up the flags for this square. Firstly, see if we
3193 if (SPACE(state, x*2, y*2+1).flags & F_EDGE_SET)
3194 flags |= DRAW_EDGE_L;
3195 if (SPACE(state, x*2+2, y*2+1).flags & F_EDGE_SET)
3196 flags |= DRAW_EDGE_R;
3197 if (SPACE(state, x*2+1, y*2).flags & F_EDGE_SET)
3198 flags |= DRAW_EDGE_U;
3199 if (SPACE(state, x*2+1, y*2+2).flags & F_EDGE_SET)
3200 flags |= DRAW_EDGE_D;
3203 * Also, mark corners of neighbouring edges.
3205 if ((x > 0 && SPACE(state, x*2-1, y*2).flags & F_EDGE_SET) ||
3206 (y > 0 && SPACE(state, x*2, y*2-1).flags & F_EDGE_SET))
3207 flags |= DRAW_CORNER_UL;
3208 if ((x+1 < w && SPACE(state, x*2+3, y*2).flags & F_EDGE_SET) ||
3209 (y > 0 && SPACE(state, x*2+2, y*2-1).flags & F_EDGE_SET))
3210 flags |= DRAW_CORNER_UR;
3211 if ((x > 0 && SPACE(state, x*2-1, y*2+2).flags & F_EDGE_SET) ||
3212 (y+1 < h && SPACE(state, x*2, y*2+3).flags & F_EDGE_SET))
3213 flags |= DRAW_CORNER_DL;
3214 if ((x+1 < w && SPACE(state, x*2+3, y*2+2).flags & F_EDGE_SET) ||
3215 (y+1 < h && SPACE(state, x*2+2, y*2+3).flags & F_EDGE_SET))
3216 flags |= DRAW_CORNER_DR;
3219 * If this square is part of a valid region, paint it
3220 * that region's colour. Exception: if we're flashing,
3221 * everything goes briefly back to background colour.
3223 sp = &SPACE(state, x*2+1, y*2+1);
3224 if (ds->colour_scratch[y*w+x] && !flashing) {
3225 flags |= (ds->colour_scratch[y*w+x] == 2 ?
3226 DRAW_BLACK : DRAW_WHITE);
3230 * If this square is associated with a dot but it isn't
3231 * part of a valid region, draw an arrow in it pointing
3232 * in the direction of that dot.
3234 * Exception: if this is the source point of an active
3235 * drag, we don't draw the arrow.
3237 if ((sp->flags & F_TILE_ASSOC) && !ds->colour_scratch[y*w+x]) {
3238 if (ui->dragging && ui->srcx == x*2+1 && ui->srcy == y*2+1) {
3240 } else if (sp->doty != y*2+1 || sp->dotx != x*2+1) {
3241 flags |= DRAW_ARROW;
3242 ddy = sp->doty - (y*2+1);
3243 ddx = sp->dotx - (x*2+1);
3248 * Now go through the nine possible places we could
3251 for (dy = 0; dy < 3; dy++)
3252 for (dx = 0; dx < 3; dx++) {
3253 sp = &SPACE(state, x*2+dx, y*2+dy);
3254 if (sp->flags & F_DOT) {
3255 unsigned long dotval = (sp->flags & F_DOT_BLACK ?
3256 DOT_BLACK : DOT_WHITE);
3257 flags |= dotval << (DOT_SHIFT_C +
3258 DOT_SHIFT_M*(dy*3+dx));
3263 * Now work out if we have to draw a cursor for this square;
3264 * cursors-on-lines are taken care of below.
3266 if (ui->cur_visible &&
3267 ui->cur_x == x*2+1 && ui->cur_y == y*2+1 &&
3268 !(SPACE(state, x*2+1, y*2+1).flags & F_DOT))
3269 flags |= DRAW_CURSOR;
3272 * Now we have everything we're going to need. Draw the
3275 if (ds->grid[y*w+x] != flags ||
3276 ds->dx[y*w+x] != ddx ||
3277 ds->dy[y*w+x] != ddy) {
3278 draw_square(dr, ds, x, y, flags, ddx, ddy);
3279 ds->grid[y*w+x] = flags;
3280 ds->dx[y*w+x] = ddx;
3281 ds->dy[y*w+x] = ddy;
3286 * Draw a cursor. This secondary blitter is much less invasive than trying
3287 * to fix up all of the rest of the code with sufficient flags to be able to
3288 * display this sensibly.
3290 if (ui->cur_visible) {
3291 space *sp = &SPACE(state, ui->cur_x, ui->cur_y);
3292 ds->cur_visible = TRUE;
3293 ds->cx = SCOORD(ui->cur_x) - CURSOR_SIZE;
3294 ds->cy = SCOORD(ui->cur_y) - CURSOR_SIZE;
3295 blitter_save(dr, ds->cur_bl, ds->cx, ds->cy);
3296 if (sp->flags & F_DOT) {
3297 /* draw a red dot (over the top of whatever would be there already) */
3298 draw_circle(dr, SCOORD(ui->cur_x), SCOORD(ui->cur_y), DOT_SIZE,
3299 COL_CURSOR, COL_BLACKDOT);
3300 } else if (sp->type != s_tile) {
3301 /* draw an edge/vertex square; tile cursors are dealt with above. */
3302 int dx = (ui->cur_x % 2) ? CURSOR_SIZE : CURSOR_SIZE/3;
3303 int dy = (ui->cur_y % 2) ? CURSOR_SIZE : CURSOR_SIZE/3;
3304 int x1 = SCOORD(ui->cur_x)-dx, y1 = SCOORD(ui->cur_y)-dy;
3305 int xs = dx*2+1, ys = dy*2+1;
3307 draw_rect(dr, x1, y1, xs, ys, COL_CURSOR);
3309 draw_update(dr, ds->cx, ds->cy, CURSOR_SIZE*2+1, CURSOR_SIZE*2+1);
3313 ds->dragging = TRUE;
3314 ds->dragx = ui->dx - TILE_SIZE/2;
3315 ds->dragy = ui->dy - TILE_SIZE/2;
3316 blitter_save(dr, ds->bl, ds->dragx, ds->dragy);
3317 draw_arrow(dr, ds, ui->dx, ui->dy,
3318 SCOORD(ui->dotx) - ui->dx,
3319 SCOORD(ui->doty) - ui->dy, COL_ARROW);
3324 if (state->cdiff != -1)
3325 sprintf(buf, "Puzzle is %s.", galaxies_diffnames[state->cdiff]);
3328 status_bar(dr, buf);
3333 static float game_anim_length(const game_state *oldstate,
3334 const game_state *newstate, int dir, game_ui *ui)
3339 static float game_flash_length(const game_state *oldstate,
3340 const game_state *newstate, int dir, game_ui *ui)
3342 if ((!oldstate->completed && newstate->completed) &&
3343 !(newstate->used_solve))
3344 return 3 * FLASH_TIME;
3349 static int game_status(const game_state *state)
3351 return state->completed ? +1 : 0;
3354 static int game_timing_state(const game_state *state, game_ui *ui)
3360 static void game_print_size(const game_params *params, float *x, float *y)
3365 * 8mm squares by default. (There isn't all that much detail
3366 * that needs to go in each square.)
3368 game_compute_size(params, 800, &pw, &ph);
3373 static void game_print(drawing *dr, const game_state *state, int sz)
3375 int w = state->w, h = state->h;
3376 int white, black, blackish;
3380 int ncoords = 0, coordsize = 0;
3382 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3383 game_drawstate ads, *ds = &ads;
3386 white = print_mono_colour(dr, 1);
3387 black = print_mono_colour(dr, 0);
3388 blackish = print_hatched_colour(dr, HATCH_X);
3391 * Get the completion information.
3393 dsf = snewn(w * h, int);
3394 colours = snewn(w * h, int);
3395 check_complete(state, dsf, colours);
3400 print_line_width(dr, TILE_SIZE / 64);
3401 for (x = 1; x < w; x++)
3402 draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h), black);
3403 for (y = 1; y < h; y++)
3404 draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y), black);
3407 * Shade the completed regions. Just in case any particular
3408 * printing platform deals badly with adjacent
3409 * similarly-hatched regions, we'll fill each one as a single
3412 for (i = 0; i < w*h; i++) {
3413 j = dsf_canonify(dsf, i);
3414 if (colours[j] != 0) {
3418 * This is the first square we've run into belonging to
3419 * this polyomino, which means an edge of the polyomino
3420 * is certain to be to our left. (After we finish
3421 * tracing round it, we'll set the colours[] entry to
3422 * zero to prevent accidentally doing it again.)
3432 * We are currently sitting on square (x,y), which
3433 * we know to be in our polyomino, and we also know
3434 * that (x+dx,y+dy) is not. The way I visualise
3435 * this is that we're standing to the right of a
3436 * boundary line, stretching our left arm out to
3437 * point to the exterior square on the far side.
3441 * First, check if we've gone round the entire
3445 (x == i%w && y == i/w && dx == -1 && dy == 0))
3449 * Add to our coordinate list the coordinate
3450 * backwards and to the left of where we are.
3452 if (ncoords + 2 > coordsize) {
3453 coordsize = (ncoords * 3 / 2) + 64;
3454 coords = sresize(coords, coordsize, int);
3456 coords[ncoords++] = COORD((2*x+1 + dx + dy) / 2);
3457 coords[ncoords++] = COORD((2*y+1 + dy - dx) / 2);
3460 * Follow the edge round. If the square directly in
3461 * front of us is not part of the polyomino, we
3462 * turn right; if it is and so is the square in
3463 * front of (x+dx,y+dy), we turn left; otherwise we
3466 if (x-dy < 0 || x-dy >= w || y+dx < 0 || y+dx >= h ||
3467 dsf_canonify(dsf, (y+dx)*w+(x-dy)) != j) {
3472 } else if (x+dx-dy >= 0 && x+dx-dy < w &&
3473 y+dy+dx >= 0 && y+dy+dx < h &&
3474 dsf_canonify(dsf, (y+dy+dx)*w+(x+dx-dy)) == j) {
3491 * Now we have our polygon complete, so fill it.
3493 draw_polygon(dr, coords, ncoords/2,
3494 colours[j] == 2 ? blackish : -1, black);
3497 * And mark this polyomino as done.
3506 for (y = 0; y <= h; y++)
3507 for (x = 0; x <= w; x++) {
3508 if (x < w && SPACE(state, x*2+1, y*2).flags & F_EDGE_SET)
3509 draw_rect(dr, COORD(x)-EDGE_THICKNESS, COORD(y)-EDGE_THICKNESS,
3510 EDGE_THICKNESS * 2 + TILE_SIZE, EDGE_THICKNESS * 2,
3512 if (y < h && SPACE(state, x*2, y*2+1).flags & F_EDGE_SET)
3513 draw_rect(dr, COORD(x)-EDGE_THICKNESS, COORD(y)-EDGE_THICKNESS,
3514 EDGE_THICKNESS * 2, EDGE_THICKNESS * 2 + TILE_SIZE,
3521 for (y = 0; y <= 2*h; y++)
3522 for (x = 0; x <= 2*w; x++)
3523 if (SPACE(state, x, y).flags & F_DOT) {
3524 draw_circle(dr, (int)COORD(x/2.0), (int)COORD(y/2.0), DOT_SIZE,
3525 (SPACE(state, x, y).flags & F_DOT_BLACK ?
3526 black : white), black);
3536 #define thegame galaxies
3539 const struct game thegame = {
3540 "Galaxies", "games.galaxies", "galaxies",
3547 TRUE, game_configure, custom_params,
3559 TRUE, game_can_format_as_text_now, game_text_format,
3567 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3570 game_free_drawstate,
3576 FALSE, FALSE, NULL, NULL,
3577 TRUE, /* wants_statusbar */
3579 TRUE, FALSE, game_print_size, game_print,
3580 FALSE, /* wants_statusbar */
3582 FALSE, game_timing_state,
3583 REQUIRE_RBUTTON, /* flags */
3586 #ifdef STANDALONE_SOLVER
3592 static void usage_exit(const char *msg)
3595 fprintf(stderr, "%s: %s\n", quis, msg);
3596 fprintf(stderr, "Usage: %s [--seed SEED] --soak <params> | [game_id [game_id ...]]\n", quis);
3600 static void dump_state(game_state *state)
3602 char *temp = game_text_format(state);
3603 printf("%s\n", temp);
3607 static int gen(game_params *p, random_state *rs, int debug)
3614 solver_show_working = debug;
3616 printf("Generating a %dx%d %s puzzle.\n",
3617 p->w, p->h, galaxies_diffnames[p->diff]);
3619 desc = new_game_desc(p, rs, NULL, 0);
3620 state = new_game(NULL, p, desc);
3623 diff = solver_state(state, DIFF_UNREASONABLE);
3624 printf("Generated %s game %dx%d:%s\n",
3625 galaxies_diffnames[diff], p->w, p->h, desc);
3634 static void soak(game_params *p, random_state *rs)
3636 time_t tt_start, tt_now, tt_last;
3639 int diff, n = 0, i, diffs[DIFF_MAX], ndots = 0, nspaces = 0;
3642 solver_show_working = 0;
3644 tt_start = tt_now = time(NULL);
3645 for (i = 0; i < DIFF_MAX; i++) diffs[i] = 0;
3648 printf("Soak-generating a %dx%d grid, max. diff %s.\n",
3649 p->w, p->h, galaxies_diffnames[p->diff]);
3651 for (i = 0; i < DIFF_MAX; i++)
3652 printf("%s%s", (i == 0) ? "" : ", ", galaxies_diffnames[i]);
3656 desc = new_game_desc(p, rs, NULL, 0);
3657 st = new_game(NULL, p, desc);
3658 diff = solver_state(st, p->diff);
3659 nspaces += st->w*st->h;
3660 for (i = 0; i < st->sx*st->sy; i++)
3661 if (st->grid[i].flags & F_DOT) ndots++;
3667 tt_last = time(NULL);
3668 if (tt_last > tt_now) {
3670 printf("%d total, %3.1f/s, [",
3671 n, (double)n / ((double)tt_now - tt_start));
3672 for (i = 0; i < DIFF_MAX; i++)
3673 printf("%s%.1f%%", (i == 0) ? "" : ", ",
3674 100.0 * ((double)diffs[i] / (double)n));
3675 printf("], %.1f%% dots\n",
3676 100.0 * ((double)ndots / (double)nspaces));
3681 int main(int argc, char **argv)
3684 char *id = NULL, *desc, *err;
3686 int diff, do_soak = 0, verbose = 0;
3688 time_t seed = time(NULL);
3691 while (--argc > 0) {
3693 if (!strcmp(p, "-v")) {
3695 } else if (!strcmp(p, "--seed")) {
3696 if (argc == 0) usage_exit("--seed needs an argument");
3697 seed = (time_t)atoi(*++argv);
3699 } else if (!strcmp(p, "--soak")) {
3701 } else if (*p == '-') {
3702 usage_exit("unrecognised option");
3710 p = default_params();
3711 rs = random_new((void*)&seed, sizeof(time_t));
3714 if (!id) usage_exit("need one argument for --soak");
3715 decode_params(p, *argv);
3722 p->w = random_upto(rs, 15) + 3;
3723 p->h = random_upto(rs, 15) + 3;
3724 p->diff = random_upto(rs, DIFF_UNREASONABLE);
3725 diff = gen(p, rs, 0);
3730 desc = strchr(id, ':');
3732 decode_params(p, id);
3733 gen(p, rs, verbose);
3736 solver_show_working = 1;
3739 decode_params(p, id);
3740 err = validate_desc(p, desc);
3742 fprintf(stderr, "%s: %s\n", argv[0], err);
3745 s = new_game(NULL, p, desc);
3746 diff = solver_state(s, DIFF_UNREASONABLE);
3748 printf("Puzzle is %s.\n", galaxies_diffnames[diff]);
3759 #ifdef STANDALONE_PICTURE_GENERATOR
3762 * Main program for the standalone picture generator. To use it,
3763 * simply provide it with an XBM-format bitmap file (note XBM, not
3764 * XPM) on standard input, and it will output a game ID in return.
3767 * $ ./galaxiespicture < badly-drawn-cat.xbm
3768 * 11x11:eloMBLzFeEzLNMWifhaWYdDbixCymBbBMLoDdewGg
3770 * If you want a puzzle with a non-standard difficulty level, pass
3771 * a partial parameters string as a command-line argument (e.g.
3772 * `./galaxiespicture du < foo.xbm', where `du' is the same suffix
3773 * which if it appeared in a random-seed game ID would set the
3774 * difficulty level to Unreasonable). However, be aware that if the
3775 * generator fails to produce an adequately difficult puzzle too
3776 * many times then it will give up and return an easier one (just
3777 * as it does during normal GUI play). To be sure you really have
3778 * the difficulty you asked for, use galaxiessolver to
3781 * (Perhaps I ought to include an option to make this standalone
3782 * generator carry on looping until it really does get the right
3783 * difficulty. Hmmm.)
3788 int main(int argc, char **argv)
3791 char *params, *desc;
3793 time_t seed = time(NULL);
3798 par = default_params();
3800 decode_params(par, argv[1]); /* get difficulty */
3801 par->w = par->h = -1;
3804 * Now read an XBM file from standard input. This is simple and
3805 * hacky and will do very little error detection, so don't feed
3810 while (fgets(buf, sizeof(buf), stdin)) {
3811 buf[strcspn(buf, "\r\n")] = '\0';
3812 if (!strncmp(buf, "#define", 7)) {
3814 * Lines starting `#define' give the width and height.
3816 char *num = buf + strlen(buf);
3819 while (num > buf && isdigit((unsigned char)num[-1]))
3822 while (symend > buf && isspace((unsigned char)symend[-1]))
3825 if (symend-5 >= buf && !strncmp(symend-5, "width", 5))
3827 else if (symend-6 >= buf && !strncmp(symend-6, "height", 6))
3831 * Otherwise, break the string up into words and take
3832 * any word of the form `0x' plus hex digits to be a
3835 char *p, *wordstart;
3838 if (par->w < 0 || par->h < 0) {
3839 printf("failed to read width and height\n");
3842 picture = snewn(par->w * par->h, int);
3843 for (i = 0; i < par->w * par->h; i++)
3849 while (*p && (*p == ',' || isspace((unsigned char)*p)))
3852 while (*p && !(*p == ',' || *p == '}' ||
3853 isspace((unsigned char)*p)))
3858 if (wordstart[0] == '0' &&
3859 (wordstart[1] == 'x' || wordstart[1] == 'X') &&
3860 !wordstart[2 + strspn(wordstart+2,
3861 "0123456789abcdefABCDEF")]) {
3862 unsigned long byte = strtoul(wordstart+2, NULL, 16);
3863 for (i = 0; i < 8; i++) {
3864 int bit = (byte >> i) & 1;
3865 if (y < par->h && x < par->w)
3866 picture[y * par->w + x] = bit;
3879 for (i = 0; i < par->w * par->h; i++)
3880 if (picture[i] < 0) {
3881 fprintf(stderr, "failed to read enough bitmap data\n");
3885 rs = random_new((void*)&seed, sizeof(time_t));
3887 desc = new_game_desc(par, rs, NULL, FALSE);
3888 params = encode_params(par, FALSE);
3889 printf("%s:%s\n", params, desc);
3901 /* vim: set shiftwidth=4 tabstop=8: */