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);
155 static space *space_opposite_dot(const game_state *state, const space *sp,
157 static space *tile_opposite(const game_state *state, const space *sp);
159 /* ----------------------------------------------------------
160 * Game parameters and presets
163 /* make up some sensible default sizes */
165 #define DEFAULT_PRESET 0
167 static const game_params galaxies_presets[] = {
168 { 7, 7, DIFF_NORMAL },
169 { 7, 7, DIFF_UNREASONABLE },
170 { 10, 10, DIFF_NORMAL },
171 { 15, 15, DIFF_NORMAL },
174 static int game_fetch_preset(int i, char **name, game_params **params)
179 if (i < 0 || i >= lenof(galaxies_presets))
182 ret = snew(game_params);
183 *ret = galaxies_presets[i]; /* structure copy */
185 sprintf(buf, "%dx%d %s", ret->w, ret->h,
186 galaxies_diffnames[ret->diff]);
188 if (name) *name = dupstr(buf);
193 static game_params *default_params(void)
196 game_fetch_preset(DEFAULT_PRESET, NULL, &ret);
200 static void free_params(game_params *params)
205 static game_params *dup_params(const game_params *params)
207 game_params *ret = snew(game_params);
208 *ret = *params; /* structure copy */
212 static void decode_params(game_params *params, char const *string)
214 params->h = params->w = atoi(string);
215 params->diff = DIFF_NORMAL;
216 while (*string && isdigit((unsigned char)*string)) string++;
217 if (*string == 'x') {
219 params->h = atoi(string);
220 while (*string && isdigit((unsigned char)*string)) string++;
222 if (*string == 'd') {
225 for (i = 0; i <= DIFF_UNREASONABLE; i++)
226 if (*string == galaxies_diffchars[i])
228 if (*string) string++;
232 static char *encode_params(const game_params *params, int full)
235 sprintf(str, "%dx%d", params->w, params->h);
237 sprintf(str + strlen(str), "d%c", galaxies_diffchars[params->diff]);
241 static config_item *game_configure(const game_params *params)
246 ret = snewn(4, config_item);
248 ret[0].name = "Width";
249 ret[0].type = C_STRING;
250 sprintf(buf, "%d", params->w);
251 ret[0].sval = dupstr(buf);
254 ret[1].name = "Height";
255 ret[1].type = C_STRING;
256 sprintf(buf, "%d", params->h);
257 ret[1].sval = dupstr(buf);
260 ret[2].name = "Difficulty";
261 ret[2].type = C_CHOICES;
262 ret[2].sval = DIFFCONFIG;
263 ret[2].ival = params->diff;
273 static game_params *custom_params(const config_item *cfg)
275 game_params *ret = snew(game_params);
277 ret->w = atoi(cfg[0].sval);
278 ret->h = atoi(cfg[1].sval);
279 ret->diff = cfg[2].ival;
284 static char *validate_params(const game_params *params, int full)
286 if (params->w < 3 || params->h < 3)
287 return "Width and height must both be at least 3";
289 * This shouldn't be able to happen at all, since decode_params
290 * and custom_params will never generate anything that isn't
293 assert(params->diff <= DIFF_UNREASONABLE);
298 /* ----------------------------------------------------------
299 * Game utility functions.
302 static void add_dot(space *space) {
303 assert(!(space->flags & F_DOT));
304 space->flags |= F_DOT;
308 static void remove_dot(space *space) {
309 assert(space->flags & F_DOT);
310 space->flags &= ~F_DOT;
313 static void remove_assoc(const game_state *state, space *tile) {
314 if (tile->flags & F_TILE_ASSOC) {
315 SPACE(state, tile->dotx, tile->doty).nassoc--;
316 tile->flags &= ~F_TILE_ASSOC;
322 static void remove_assoc_with_opposite(game_state *state, space *tile) {
325 if (!(tile->flags & F_TILE_ASSOC)) {
329 opposite = tile_opposite(state, tile);
330 remove_assoc(state, tile);
332 if (opposite != NULL && opposite != tile) {
333 remove_assoc(state, opposite);
337 static void add_assoc(const game_state *state, space *tile, space *dot) {
338 remove_assoc(state, tile);
340 #ifdef STANDALONE_PICTURE_GENERATOR
342 assert(!picture[(tile->y/2) * state->w + (tile->x/2)] ==
343 !(dot->flags & F_DOT_BLACK));
345 tile->flags |= F_TILE_ASSOC;
349 /*debug(("add_assoc sp %d %d --> dot %d,%d, new nassoc %d.\n",
350 tile->x, tile->y, dot->x, dot->y, dot->nassoc));*/
353 static void add_assoc_with_opposite(game_state *state, space *tile, space *dot) {
355 space *opposite = space_opposite_dot(state, tile, dot);
357 if (opposite == NULL) {
360 if (opposite->flags & F_DOT) {
364 colors = snewn(state->w * state->h, int);
365 check_complete(state, NULL, colors);
366 if (colors[(tile->y - 1)/2 * state->w + (tile->x - 1)/2]) {
370 if (colors[(opposite->y - 1)/2 * state->w + (opposite->x - 1)/2]) {
376 add_assoc(state, tile, dot);
377 add_assoc(state, opposite, dot);
380 static space *sp2dot(const game_state *state, int x, int y)
382 space *sp = &SPACE(state, x, y);
383 if (!(sp->flags & F_TILE_ASSOC)) return NULL;
384 return &SPACE(state, sp->dotx, sp->doty);
387 #define IS_VERTICAL_EDGE(x) ((x % 2) == 0)
389 static int game_can_format_as_text_now(const game_params *params)
394 static char *game_text_format(const game_state *state)
396 int maxlen = (state->sx+1)*state->sy, x, y;
400 ret = snewn(maxlen+1, char);
403 for (y = 0; y < state->sy; y++) {
404 for (x = 0; x < state->sx; x++) {
405 sp = &SPACE(state, x, y);
406 if (sp->flags & F_DOT)
409 else if (sp->flags & (F_REACHABLE|F_MULTIPLE|F_MARK))
410 *p++ = (sp->flags & F_MULTIPLE) ? 'M' :
411 (sp->flags & F_REACHABLE) ? 'R' : 'X';
416 if (sp->flags & F_TILE_ASSOC) {
417 space *dot = sp2dot(state, sp->x, sp->y);
418 if (dot && dot->flags & F_DOT)
419 *p++ = (dot->flags & F_DOT_BLACK) ? 'B' : 'W';
421 *p++ = '?'; /* association with not-a-dot. */
431 if (sp->flags & F_EDGE_SET)
432 *p++ = (IS_VERTICAL_EDGE(x)) ? '|' : '-';
438 assert(!"shouldn't get here!");
445 assert(p - ret == maxlen);
451 static void dbg_state(const game_state *state)
454 char *temp = game_text_format(state);
455 debug(("%s\n", temp));
460 /* Space-enumeration callbacks should all return 1 for 'progress made',
461 * -1 for 'impossible', and 0 otherwise. */
462 typedef int (*space_cb)(game_state *state, space *sp, void *ctx);
464 #define IMPOSSIBLE_QUITS 1
466 static int foreach_sub(game_state *state, space_cb cb, unsigned int f,
467 void *ctx, int startx, int starty)
469 int x, y, progress = 0, impossible = 0, ret;
472 for (y = starty; y < state->sy; y += 2) {
473 sp = &SPACE(state, startx, y);
474 for (x = startx; x < state->sx; x += 2) {
475 ret = cb(state, sp, ctx);
477 if (f & IMPOSSIBLE_QUITS) return -1;
479 } else if (ret == 1) {
485 return impossible ? -1 : progress;
488 static int foreach_tile(game_state *state, space_cb cb, unsigned int f,
491 return foreach_sub(state, cb, f, ctx, 1, 1);
494 static int foreach_edge(game_state *state, space_cb cb, unsigned int f,
499 ret1 = foreach_sub(state, cb, f, ctx, 0, 1);
500 ret2 = foreach_sub(state, cb, f, ctx, 1, 0);
502 if (ret1 == -1 || ret2 == -1) return -1;
503 return (ret1 || ret2) ? 1 : 0;
507 static int foreach_vertex(game_state *state, space_cb cb, unsigned int f,
510 return foreach_sub(state, cb, f, ctx, 0, 0);
515 static int is_same_assoc(game_state *state,
516 int x1, int y1, int x2, int y2)
520 if (!INGRID(state, x1, y1) || !INGRID(state, x2, y2))
523 s1 = &SPACE(state, x1, y1);
524 s2 = &SPACE(state, x2, y2);
525 assert(s1->type == s_tile && s2->type == s_tile);
526 if ((s1->flags & F_TILE_ASSOC) && (s2->flags & F_TILE_ASSOC) &&
527 s1->dotx == s2->dotx && s1->doty == s2->doty)
529 return 0; /* 0 if not same or not both associated. */
534 static int edges_into_vertex(game_state *state,
537 int dx, dy, nx, ny, count = 0;
539 assert(SPACE(state, x, y).type == s_vertex);
540 for (dx = -1; dx <= 1; dx++) {
541 for (dy = -1; dy <= 1; dy++) {
542 if (dx != 0 && dy != 0) continue;
543 if (dx == 0 && dy == 0) continue;
545 nx = x+dx; ny = y+dy;
546 if (!INGRID(state, nx, ny)) continue;
547 assert(SPACE(state, nx, ny).type == s_edge);
548 if (SPACE(state, nx, ny).flags & F_EDGE_SET)
556 static space *space_opposite_dot(const game_state *state, const space *sp,
566 if (!INGRID(state, tx, ty)) return NULL;
568 sp2 = &SPACE(state, tx, ty);
569 assert(sp2->type == sp->type);
573 static space *tile_opposite(const game_state *state, const space *sp)
577 assert(sp->flags & F_TILE_ASSOC);
578 dot = &SPACE(state, sp->dotx, sp->doty);
579 return space_opposite_dot(state, sp, dot);
582 static int dotfortile(game_state *state, space *tile, space *dot)
584 space *tile_opp = space_opposite_dot(state, tile, dot);
586 if (!tile_opp) return 0; /* opposite would be off grid */
587 if (tile_opp->flags & F_TILE_ASSOC &&
588 (tile_opp->dotx != dot->x || tile_opp->doty != dot->y))
589 return 0; /* opposite already associated with diff. dot */
593 static void adjacencies(game_state *state, space *sp, space **a1s, space **a2s)
595 int dxs[4] = {-1, 1, 0, 0}, dys[4] = {0, 0, -1, 1};
598 /* this function needs optimising. */
600 for (n = 0; n < 4; n++) {
604 if (INGRID(state, x, y)) {
605 a1s[n] = &SPACE(state, x, y);
607 x += dxs[n]; y += dys[n];
609 if (INGRID(state, x, y))
610 a2s[n] = &SPACE(state, x, y);
614 a1s[n] = a2s[n] = NULL;
619 static int outline_tile_fordot(game_state *state, space *tile, int mark)
621 space *tadj[4], *eadj[4];
622 int i, didsth = 0, edge, same;
624 assert(tile->type == s_tile);
625 adjacencies(state, tile, eadj, tadj);
626 for (i = 0; i < 4; i++) {
627 if (!eadj[i]) continue;
629 edge = (eadj[i]->flags & F_EDGE_SET) ? 1 : 0;
631 if (!(tile->flags & F_TILE_ASSOC))
632 same = (tadj[i]->flags & F_TILE_ASSOC) ? 0 : 1;
634 same = ((tadj[i]->flags & F_TILE_ASSOC) &&
635 tile->dotx == tadj[i]->dotx &&
636 tile->doty == tadj[i]->doty) ? 1 : 0;
640 if (!edge && !same) {
641 if (mark) eadj[i]->flags |= F_EDGE_SET;
643 } else if (edge && same) {
644 if (mark) eadj[i]->flags &= ~F_EDGE_SET;
651 static void tiles_from_edge(game_state *state, space *sp, space **ts)
655 if (IS_VERTICAL_EDGE(sp->x)) {
656 xs[0] = sp->x-1; ys[0] = sp->y;
657 xs[1] = sp->x+1; ys[1] = sp->y;
659 xs[0] = sp->x; ys[0] = sp->y-1;
660 xs[1] = sp->x; ys[1] = sp->y+1;
662 ts[0] = INGRID(state, xs[0], ys[0]) ? &SPACE(state, xs[0], ys[0]) : NULL;
663 ts[1] = INGRID(state, xs[1], ys[1]) ? &SPACE(state, xs[1], ys[1]) : NULL;
666 /* Returns a move string for use by 'solve', including the initial
667 * 'S' if issolve is true. */
668 static char *diff_game(const game_state *src, const game_state *dest,
671 int movelen = 0, movesize = 256, x, y, len;
672 char *move = snewn(movesize, char), buf[80], *sep = "";
673 char achar = issolve ? 'a' : 'A';
676 assert(src->sx == dest->sx && src->sy == dest->sy);
679 move[movelen++] = 'S';
682 move[movelen] = '\0';
683 for (x = 0; x < src->sx; x++) {
684 for (y = 0; y < src->sy; y++) {
685 sps = &SPACE(src, x, y);
686 spd = &SPACE(dest, x, y);
688 assert(sps->type == spd->type);
691 if (sps->type == s_tile) {
692 if ((sps->flags & F_TILE_ASSOC) &&
693 (spd->flags & F_TILE_ASSOC)) {
694 if (sps->dotx != spd->dotx ||
695 sps->doty != spd->doty)
696 /* Both associated; change association, if different */
697 len = sprintf(buf, "%s%c%d,%d,%d,%d", sep,
698 (int)achar, x, y, spd->dotx, spd->doty);
699 } else if (sps->flags & F_TILE_ASSOC)
700 /* Only src associated; remove. */
701 len = sprintf(buf, "%sU%d,%d", sep, x, y);
702 else if (spd->flags & F_TILE_ASSOC)
703 /* Only dest associated; add. */
704 len = sprintf(buf, "%s%c%d,%d,%d,%d", sep,
705 (int)achar, x, y, spd->dotx, spd->doty);
706 } else if (sps->type == s_edge) {
707 if ((sps->flags & F_EDGE_SET) != (spd->flags & F_EDGE_SET))
708 /* edge flags are different; flip them. */
709 len = sprintf(buf, "%sE%d,%d", sep, x, y);
712 if (movelen + len >= movesize) {
713 movesize = movelen + len + 256;
714 move = sresize(move, movesize, char);
716 strcpy(move + movelen, buf);
722 debug(("diff_game src then dest:\n"));
725 debug(("diff string %s\n", move));
729 /* Returns 1 if a dot here would not be too close to any other dots
730 * (and would avoid other game furniture). */
731 static int dot_is_possible(game_state *state, space *sp, int allow_assoc)
733 int bx = 0, by = 0, dx, dy;
735 #ifdef STANDALONE_PICTURE_GENERATOR
743 if (IS_VERTICAL_EDGE(sp->x)) {
753 for (dx = -bx; dx <= bx; dx++) {
754 for (dy = -by; dy <= by; dy++) {
755 if (!INGRID(state, sp->x+dx, sp->y+dy)) continue;
757 adj = &SPACE(state, sp->x+dx, sp->y+dy);
759 #ifdef STANDALONE_PICTURE_GENERATOR
761 * Check that all the squares we're looking at have the
765 if (adj->type == s_tile) {
766 int c = picture[(adj->y / 2) * state->w + (adj->x / 2)];
770 return 0; /* colour mismatch */
775 if (!allow_assoc && (adj->flags & F_TILE_ASSOC))
778 if (dx != 0 || dy != 0) {
779 /* Other than our own square, no dots nearby. */
780 if (adj->flags & (F_DOT))
784 /* We don't want edges within our rectangle
785 * (but don't care about edges on the edge) */
786 if (abs(dx) < bx && abs(dy) < by &&
787 adj->flags & F_EDGE_SET)
794 /* ----------------------------------------------------------
795 * Game generation, structure creation, and descriptions.
798 static game_state *blank_game(int w, int h)
800 game_state *state = snew(game_state);
808 state->grid = snewn(state->sx * state->sy, space);
809 state->completed = state->used_solve = 0;
811 for (x = 0; x < state->sx; x++) {
812 for (y = 0; y < state->sy; y++) {
813 space *sp = &SPACE(state, x, y);
814 memset(sp, 0, sizeof(space));
817 if ((x % 2) == 0 && (y % 2) == 0)
819 else if ((x % 2) == 0 || (y % 2) == 0) {
821 if (x == 0 || y == 0 || x == state->sx-1 || y == state->sy-1)
822 sp->flags |= F_EDGE_SET;
831 state->me = NULL; /* filled in by new_game. */
837 static void game_update_dots(game_state *state)
839 int i, n, sz = state->sx * state->sy;
841 if (state->dots) sfree(state->dots);
844 for (i = 0; i < sz; i++) {
845 if (state->grid[i].flags & F_DOT) state->ndots++;
847 state->dots = snewn(state->ndots, space *);
849 for (i = 0; i < sz; i++) {
850 if (state->grid[i].flags & F_DOT)
851 state->dots[n++] = &state->grid[i];
855 static void clear_game(game_state *state, int cleardots)
859 /* don't erase edge flags around outline! */
860 for (x = 1; x < state->sx-1; x++) {
861 for (y = 1; y < state->sy-1; y++) {
863 SPACE(state, x, y).flags = 0;
865 SPACE(state, x, y).flags &= (F_DOT|F_DOT_BLACK);
868 if (cleardots) game_update_dots(state);
871 static game_state *dup_game(const game_state *state)
873 game_state *ret = blank_game(state->w, state->h);
875 ret->completed = state->completed;
876 ret->used_solve = state->used_solve;
878 memcpy(ret->grid, state->grid,
879 ret->sx*ret->sy*sizeof(space));
881 game_update_dots(ret);
884 ret->cdiff = state->cdiff;
889 static void free_game(game_state *state)
891 if (state->dots) sfree(state->dots);
896 /* Game description is a sequence of letters representing the number
897 * of spaces (a = 0, y = 24) before the next dot; a-y for a white dot,
898 * and A-Y for a black dot. 'z' is 25 spaces (and no dot).
900 * I know it's a bitch to generate by hand, so we provide
904 static char *encode_game(game_state *state)
910 area = (state->sx-2) * (state->sy-2);
912 desc = snewn(area, char);
915 for (y = 1; y < state->sy-1; y++) {
916 for (x = 1; x < state->sx-1; x++) {
917 f = SPACE(state, x, y).flags;
919 /* a/A is 0 spaces between, b/B is 1 space, ...
920 * y/Y is 24 spaces, za/zA is 25 spaces, ...
921 * It's easier to count from 0 because we then
922 * don't have to special-case the top left-hand corner
923 * (which could be a dot with 0 spaces before it). */
931 *p++ = ((f & F_DOT_BLACK) ? 'A' : 'a') + run;
936 assert(p - desc < area);
938 desc = sresize(desc, p - desc, char);
945 space *olddot, *newdot;
948 enum { MD_CHECK, MD_MOVE };
950 static int movedot_cb(game_state *state, space *tile, void *vctx)
952 struct movedot *md = (struct movedot *)vctx;
953 space *newopp = NULL;
955 assert(tile->type == s_tile);
956 assert(md->olddot && md->newdot);
958 if (!(tile->flags & F_TILE_ASSOC)) return 0;
959 if (tile->dotx != md->olddot->x || tile->doty != md->olddot->y)
962 newopp = space_opposite_dot(state, tile, md->newdot);
966 /* If the tile is associated with the old dot, check its
967 * opposite wrt the _new_ dot is empty or same assoc. */
968 if (!newopp) return -1; /* no new opposite */
969 if (newopp->flags & F_TILE_ASSOC) {
970 if (newopp->dotx != md->olddot->x ||
971 newopp->doty != md->olddot->y)
972 return -1; /* associated, but wrong dot. */
974 #ifdef STANDALONE_PICTURE_GENERATOR
977 * Reject if either tile and the dot don't match in colour.
979 if (!(picture[(tile->y/2) * state->w + (tile->x/2)]) ^
980 !(md->newdot->flags & F_DOT_BLACK))
982 if (!(picture[(newopp->y/2) * state->w + (newopp->x/2)]) ^
983 !(md->newdot->flags & F_DOT_BLACK))
990 /* Move dot associations: anything that was associated
991 * with the old dot, and its opposite wrt the new dot,
992 * become associated with the new dot. */
994 debug(("Associating %d,%d and %d,%d with new dot %d,%d.\n",
995 tile->x, tile->y, newopp->x, newopp->y,
996 md->newdot->x, md->newdot->y));
997 add_assoc(state, tile, md->newdot);
998 add_assoc(state, newopp, md->newdot);
999 return 1; /* we did something! */
1004 /* For the given dot, first see if we could expand it into all the given
1005 * extra spaces (by checking for empty spaces on the far side), and then
1006 * see if we can move the dot to shift the CoG to include the new spaces.
1008 static int dot_expand_or_move(game_state *state, space *dot,
1009 space **toadd, int nadd)
1012 int i, ret, nnew, cx, cy;
1015 debug(("dot_expand_or_move: %d tiles for dot %d,%d\n",
1016 nadd, dot->x, dot->y));
1017 for (i = 0; i < nadd; i++)
1018 debug(("dot_expand_or_move: dot %d,%d\n",
1019 toadd[i]->x, toadd[i]->y));
1020 assert(dot->flags & F_DOT);
1022 #ifdef STANDALONE_PICTURE_GENERATOR
1025 * Reject the expansion totally if any of the new tiles are
1028 for (i = 0; i < nadd; i++) {
1029 if (!(picture[(toadd[i]->y/2) * state->w + (toadd[i]->x/2)]) ^
1030 !(dot->flags & F_DOT_BLACK))
1036 /* First off, could we just expand the current dot's tile to cover
1037 * the space(s) passed in and their opposites? */
1038 for (i = 0; i < nadd; i++) {
1039 tileopp = space_opposite_dot(state, toadd[i], dot);
1040 if (!tileopp) goto noexpand;
1041 if (tileopp->flags & F_TILE_ASSOC) goto noexpand;
1042 #ifdef STANDALONE_PICTURE_GENERATOR
1045 * The opposite tiles have to be the right colour as well.
1047 if (!(picture[(tileopp->y/2) * state->w + (tileopp->x/2)]) ^
1048 !(dot->flags & F_DOT_BLACK))
1053 /* OK, all spaces have valid empty opposites: associate spaces and
1054 * opposites with our dot. */
1055 for (i = 0; i < nadd; i++) {
1056 tileopp = space_opposite_dot(state, toadd[i], dot);
1057 add_assoc(state, toadd[i], dot);
1058 add_assoc(state, tileopp, dot);
1059 debug(("Added associations %d,%d and %d,%d --> %d,%d\n",
1060 toadd[i]->x, toadd[i]->y,
1061 tileopp->x, tileopp->y,
1068 /* Otherwise, try to move dot so as to encompass given spaces: */
1069 /* first, calculate the 'centre of gravity' of the new dot. */
1070 nnew = dot->nassoc + nadd; /* number of tiles assoc. with new dot. */
1071 cx = dot->x * dot->nassoc;
1072 cy = dot->y * dot->nassoc;
1073 for (i = 0; i < nadd; i++) {
1077 /* If the CoG isn't a whole number, it's not possible. */
1078 if ((cx % nnew) != 0 || (cy % nnew) != 0) {
1079 debug(("Unable to move dot %d,%d, CoG not whole number.\n",
1083 cx /= nnew; cy /= nnew;
1085 /* Check whether all spaces in the old tile would have a good
1086 * opposite wrt the new dot. */
1088 md.newdot = &SPACE(state, cx, cy);
1090 ret = foreach_tile(state, movedot_cb, IMPOSSIBLE_QUITS, &md);
1092 debug(("Unable to move dot %d,%d, new dot not symmetrical.\n",
1096 /* Also check whether all spaces we're adding would have a good
1097 * opposite wrt the new dot. */
1098 for (i = 0; i < nadd; i++) {
1099 tileopp = space_opposite_dot(state, toadd[i], md.newdot);
1100 if (tileopp && (tileopp->flags & F_TILE_ASSOC) &&
1101 (tileopp->dotx != dot->x || tileopp->doty != dot->y)) {
1105 debug(("Unable to move dot %d,%d, new dot not symmetrical.\n",
1109 #ifdef STANDALONE_PICTURE_GENERATOR
1111 if (!(picture[(tileopp->y/2) * state->w + (tileopp->x/2)]) ^
1112 !(dot->flags & F_DOT_BLACK))
1118 /* If we've got here, we're ok. First, associate all of 'toadd'
1119 * with the _old_ dot (so they'll get fixed up, with their opposites,
1120 * in the next step). */
1121 for (i = 0; i < nadd; i++) {
1122 debug(("Associating to-add %d,%d with old dot %d,%d.\n",
1123 toadd[i]->x, toadd[i]->y, dot->x, dot->y));
1124 add_assoc(state, toadd[i], dot);
1127 /* Finally, move the dot and fix up all the old associations. */
1128 debug(("Moving dot at %d,%d to %d,%d\n",
1129 dot->x, dot->y, md.newdot->x, md.newdot->y));
1131 #ifdef STANDALONE_PICTURE_GENERATOR
1132 int f = dot->flags & F_DOT_BLACK;
1136 #ifdef STANDALONE_PICTURE_GENERATOR
1137 md.newdot->flags |= f;
1142 ret = foreach_tile(state, movedot_cb, 0, &md);
1149 /* Hard-code to a max. of 2x2 squares, for speed (less malloc) */
1151 #define MAX_OUTSIDE 8
1153 #define MAX_TILE_PERC 20
1155 static int generate_try_block(game_state *state, random_state *rs,
1156 int x1, int y1, int x2, int y2)
1158 int x, y, nadd = 0, nout = 0, i, maxsz;
1159 space *sp, *toadd[MAX_TOADD], *outside[MAX_OUTSIDE], *dot;
1161 if (!INGRID(state, x1, y1) || !INGRID(state, x2, y2)) return 0;
1163 /* We limit the maximum size of tiles to be ~2*sqrt(area); so,
1164 * a 5x5 grid shouldn't have anything >10 tiles, a 20x20 grid
1165 * nothing >40 tiles. */
1166 maxsz = (int)sqrt((double)(state->w * state->h)) * 2;
1167 debug(("generate_try_block, maxsz %d\n", maxsz));
1169 /* Make a static list of the spaces; if any space is already
1170 * associated then quit immediately. */
1171 for (x = x1; x <= x2; x += 2) {
1172 for (y = y1; y <= y2; y += 2) {
1173 assert(nadd < MAX_TOADD);
1174 sp = &SPACE(state, x, y);
1175 assert(sp->type == s_tile);
1176 if (sp->flags & F_TILE_ASSOC) return 0;
1181 /* Make a list of the spaces outside of our block, and shuffle it. */
1182 #define OUTSIDE(x, y) do { \
1183 if (INGRID(state, (x), (y))) { \
1184 assert(nout < MAX_OUTSIDE); \
1185 outside[nout++] = &SPACE(state, (x), (y)); \
1188 for (x = x1; x <= x2; x += 2) {
1192 for (y = y1; y <= y2; y += 2) {
1196 shuffle(outside, nout, sizeof(space *), rs);
1198 for (i = 0; i < nout; i++) {
1199 if (!(outside[i]->flags & F_TILE_ASSOC)) continue;
1200 dot = &SPACE(state, outside[i]->dotx, outside[i]->doty);
1201 if (dot->nassoc >= maxsz) {
1202 debug(("Not adding to dot %d,%d, large enough (%d) already.\n",
1203 dot->x, dot->y, dot->nassoc));
1206 if (dot_expand_or_move(state, dot, toadd, nadd)) return 1;
1211 #ifdef STANDALONE_SOLVER
1213 #define MAXTRIES maxtries
1220 static void generate_pass(game_state *state, random_state *rs, int *scratch,
1221 int perc, unsigned int flags)
1223 int sz = state->sx*state->sy, nspc, i, ret;
1225 shuffle(scratch, sz, sizeof(int), rs);
1227 /* This bug took me a, er, little while to track down. On PalmOS,
1228 * which has 16-bit signed ints, puzzles over about 9x9 started
1229 * failing to generate because the nspc calculation would start
1230 * to overflow, causing the dots not to be filled in properly. */
1231 nspc = (int)(((long)perc * (long)sz) / 100L);
1232 debug(("generate_pass: %d%% (%d of %dx%d) squares, flags 0x%x\n",
1233 perc, nspc, state->sx, state->sy, flags));
1235 for (i = 0; i < nspc; i++) {
1236 space *sp = &state->grid[scratch[i]];
1237 int x1 = sp->x, y1 = sp->y, x2 = sp->x, y2 = sp->y;
1239 if (sp->type == s_edge) {
1240 if (IS_VERTICAL_EDGE(sp->x)) {
1246 if (sp->type != s_vertex) {
1247 /* heuristic; expanding from vertices tends to generate lots of
1248 * too-big regions of tiles. */
1249 if (generate_try_block(state, rs, x1, y1, x2, y2))
1250 continue; /* we expanded successfully. */
1253 if (!(flags & GP_DOTS)) continue;
1255 if ((sp->type == s_edge) && (i % 2)) {
1256 debug(("Omitting edge %d,%d as half-of.\n", sp->x, sp->y));
1260 /* If we've got here we might want to put a dot down. Check
1261 * if we can, and add one if so. */
1262 if (dot_is_possible(state, sp, 0)) {
1264 #ifdef STANDALONE_PICTURE_GENERATOR
1266 if (picture[(sp->y/2) * state->w + (sp->x/2)])
1267 sp->flags |= F_DOT_BLACK;
1270 ret = solver_obvious_dot(state, sp);
1272 debug(("Added dot (and obvious associations) at %d,%d\n",
1280 static char *new_game_desc(const game_params *params, random_state *rs,
1281 char **aux, int interactive)
1283 game_state *state = blank_game(params->w, params->h), *copy;
1285 int *scratch, sz = state->sx*state->sy, i;
1286 int diff, ntries = 0, cc;
1288 /* Random list of squares to try and process, one-by-one. */
1289 scratch = snewn(sz, int);
1290 for (i = 0; i < sz; i++) scratch[i] = i;
1293 clear_game(state, 1);
1296 /* generate_pass(state, rs, scratch, 10, GP_DOTS); */
1297 /* generate_pass(state, rs, scratch, 100, 0); */
1298 generate_pass(state, rs, scratch, 100, GP_DOTS);
1300 game_update_dots(state);
1304 char *tmp = encode_game(state);
1305 debug(("new_game_desc state %dx%d:%s\n", params->w, params->h, tmp));
1310 for (i = 0; i < state->sx*state->sy; i++)
1311 if (state->grid[i].type == s_tile)
1312 outline_tile_fordot(state, &state->grid[i], TRUE);
1313 cc = check_complete(state, NULL, NULL);
1316 copy = dup_game(state);
1317 clear_game(copy, 0);
1319 diff = solver_state(copy, params->diff);
1322 assert(diff != DIFF_IMPOSSIBLE);
1323 if (diff != params->diff) {
1325 * We'll grudgingly accept a too-easy puzzle, but we must
1326 * _not_ permit a too-hard one (one which the solver
1327 * couldn't handle at all).
1329 if (diff > params->diff ||
1330 ntries < MAXTRIES) goto generate;
1333 #ifdef STANDALONE_PICTURE_GENERATOR
1335 * Postprocessing pass to prevent excessive numbers of adjacent
1336 * singletons. Iterate over all edges in random shuffled order;
1337 * for each edge that separates two regions, investigate
1338 * whether removing that edge and merging the regions would
1339 * still yield a valid and soluble puzzle. (The two regions
1340 * must also be the same colour, of course.) If so, do it.
1342 * This postprocessing pass is slow (due to repeated solver
1343 * invocations), and seems to be unnecessary during normal
1344 * unconstrained game generation. However, when generating a
1345 * game under colour constraints, excessive singletons seem to
1346 * turn up more often, so it's worth doing this.
1353 nposns = params->w * (params->h+1) + params->h * (params->w+1);
1354 posns = snewn(nposns, int);
1355 for (i = j = 0; i < state->sx*state->sy; i++)
1356 if (state->grid[i].type == s_edge)
1358 assert(j == nposns);
1360 shuffle(posns, nposns, sizeof(*posns), rs);
1362 for (i = 0; i < nposns; i++) {
1363 int x, y, x0, y0, x1, y1, cx, cy, cn, cx0, cy0, cx1, cy1, tx, ty;
1364 space *s0, *s1, *ts, *d0, *d1, *dn;
1367 /* Coordinates of edge space */
1368 x = posns[i] % state->sx;
1369 y = posns[i] / state->sx;
1371 /* Coordinates of square spaces on either side of edge */
1372 x0 = ((x+1) & ~1) - 1; /* round down to next odd number */
1373 y0 = ((y+1) & ~1) - 1;
1374 x1 = 2*x-x0; /* and reflect about x to get x1 */
1377 if (!INGRID(state, x0, y0) || !INGRID(state, x1, y1))
1378 continue; /* outermost edge of grid */
1379 s0 = &SPACE(state, x0, y0);
1380 s1 = &SPACE(state, x1, y1);
1381 assert(s0->type == s_tile && s1->type == s_tile);
1383 if (s0->dotx == s1->dotx && s0->doty == s1->doty)
1384 continue; /* tiles _already_ owned by same dot */
1386 d0 = &SPACE(state, s0->dotx, s0->doty);
1387 d1 = &SPACE(state, s1->dotx, s1->doty);
1389 if ((d0->flags ^ d1->flags) & F_DOT_BLACK)
1390 continue; /* different colours: cannot merge */
1393 * Work out where the centre of gravity of the new
1396 cx = d0->nassoc * d0->x + d1->nassoc * d1->x;
1397 cy = d0->nassoc * d0->y + d1->nassoc * d1->y;
1398 cn = d0->nassoc + d1->nassoc;
1399 if (cx % cn || cy % cn)
1400 continue; /* CoG not at integer coordinates */
1403 assert(INUI(state, cx, cy));
1406 * Ensure that the CoG would actually be _in_ the new
1407 * region, by verifying that all its surrounding tiles
1408 * belong to one or other of our two dots.
1410 cx0 = ((cx+1) & ~1) - 1; /* round down to next odd number */
1411 cy0 = ((cy+1) & ~1) - 1;
1412 cx1 = 2*cx-cx0; /* and reflect about cx to get cx1 */
1415 for (ty = cy0; ty <= cy1; ty += 2)
1416 for (tx = cx0; tx <= cx1; tx += 2) {
1417 ts = &SPACE(state, tx, ty);
1418 assert(ts->type == s_tile);
1419 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1420 (ts->dotx != d1->x || ts->doty != d1->y))
1427 * Verify that for every tile in either source region,
1428 * that tile's image in the new CoG is also in one of
1429 * the two source regions.
1431 for (ty = 1; ty < state->sy; ty += 2) {
1432 for (tx = 1; tx < state->sx; tx += 2) {
1435 ts = &SPACE(state, tx, ty);
1436 assert(ts->type == s_tile);
1437 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1438 (ts->dotx != d1->x || ts->doty != d1->y))
1439 continue; /* not part of these tiles anyway */
1442 if (!INGRID(state, tx1, ty1)) {
1446 ts = &SPACE(state, cx+cx-tx, cy+cy-ty);
1447 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1448 (ts->dotx != d1->x || ts->doty != d1->y)) {
1460 * Now we're clear to attempt the merge. We take a copy
1461 * of the game state first, so we can revert it easily
1462 * if the resulting puzzle turns out to have become
1465 copy2 = dup_game(state);
1469 dn = &SPACE(state, cx, cy);
1471 dn->flags |= (d0->flags & F_DOT_BLACK);
1472 for (ty = 1; ty < state->sy; ty += 2) {
1473 for (tx = 1; tx < state->sx; tx += 2) {
1474 ts = &SPACE(state, tx, ty);
1475 assert(ts->type == s_tile);
1476 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1477 (ts->dotx != d1->x || ts->doty != d1->y))
1478 continue; /* not part of these tiles anyway */
1479 add_assoc(state, ts, dn);
1483 copy = dup_game(state);
1484 clear_game(copy, 0);
1486 newdiff = solver_state(copy, params->diff);
1488 if (diff == newdiff) {
1489 /* Still just as soluble. Let the merge stand. */
1492 /* Became insoluble. Revert. */
1501 desc = encode_game(state);
1502 #ifndef STANDALONE_SOLVER
1503 debug(("new_game_desc generated: \n"));
1513 static int dots_too_close(game_state *state)
1515 /* Quick-and-dirty check, using half the solver:
1516 * solver_obvious will only fail if the dots are
1517 * too close together, so dot-proximity associations
1519 game_state *tmp = dup_game(state);
1520 int ret = solver_obvious(tmp);
1522 return (ret == -1) ? 1 : 0;
1525 static game_state *load_game(const game_params *params, const char *desc,
1528 game_state *state = blank_game(params->w, params->h);
1540 if (n >= 'a' && n <= 'y') {
1543 } else if (n >= 'A' && n <= 'Y') {
1547 why = "Invalid characters in game description"; goto fail;
1549 /* if we got here we incremented i and have a dot to add. */
1550 y = (i / (state->sx-2)) + 1;
1551 x = (i % (state->sx-2)) + 1;
1552 if (!INUI(state, x, y)) {
1553 why = "Too much data to fit in grid"; goto fail;
1555 add_dot(&SPACE(state, x, y));
1556 SPACE(state, x, y).flags |= df;
1559 game_update_dots(state);
1561 if (dots_too_close(state)) {
1562 why = "Dots too close together"; goto fail;
1569 if (why_r) *why_r = why;
1573 static char *validate_desc(const game_params *params, const char *desc)
1576 game_state *dummy = load_game(params, desc, &why);
1585 static game_state *new_game(midend *me, const game_params *params,
1588 game_state *state = load_game(params, desc, NULL);
1590 assert("Unable to load ?validated game.");
1599 /* ----------------------------------------------------------
1600 * Solver and all its little wizards.
1603 int solver_recurse_depth;
1605 typedef struct solver_ctx {
1607 int sz; /* state->sx * state->sy */
1608 space **scratch; /* size sz */
1612 static solver_ctx *new_solver(game_state *state)
1614 solver_ctx *sctx = snew(solver_ctx);
1615 sctx->state = state;
1616 sctx->sz = state->sx*state->sy;
1617 sctx->scratch = snewn(sctx->sz, space *);
1621 static void free_solver(solver_ctx *sctx)
1623 sfree(sctx->scratch);
1627 /* Solver ideas so far:
1629 * For any empty space, work out how many dots it could associate
1631 * it needs line-of-sight
1632 * it needs an empty space on the far side
1633 * any adjacent lines need corresponding line possibilities.
1636 /* The solver_ctx should keep a list of dot positions, for quicker looping.
1638 * Solver techniques, in order of difficulty:
1639 * obvious adjacency to dots
1640 * transferring tiles to opposite side
1641 * transferring lines to opposite side
1642 * one possible dot for a given tile based on opposite availability
1643 * tile with 3 definite edges next to an associated tile must associate
1646 * one possible dot for a given tile based on line-of-sight
1649 static int solver_add_assoc(game_state *state, space *tile, int dx, int dy,
1652 space *dot, *tile_opp;
1654 dot = &SPACE(state, dx, dy);
1655 tile_opp = space_opposite_dot(state, tile, dot);
1657 assert(tile->type == s_tile);
1658 if (tile->flags & F_TILE_ASSOC) {
1659 if ((tile->dotx != dx) || (tile->doty != dy)) {
1660 solvep(("%*sSet %d,%d --> %d,%d (%s) impossible; "
1661 "already --> %d,%d.\n",
1662 solver_recurse_depth*4, "",
1663 tile->x, tile->y, dx, dy, why,
1664 tile->dotx, tile->doty));
1667 return 0; /* no-op */
1670 solvep(("%*s%d,%d --> %d,%d impossible, no opposite tile.\n",
1671 solver_recurse_depth*4, "", tile->x, tile->y, dx, dy));
1674 if (tile_opp->flags & F_TILE_ASSOC &&
1675 (tile_opp->dotx != dx || tile_opp->doty != dy)) {
1676 solvep(("%*sSet %d,%d --> %d,%d (%s) impossible; "
1677 "opposite already --> %d,%d.\n",
1678 solver_recurse_depth*4, "",
1679 tile->x, tile->y, dx, dy, why,
1680 tile_opp->dotx, tile_opp->doty));
1684 add_assoc(state, tile, dot);
1685 add_assoc(state, tile_opp, dot);
1686 solvep(("%*sSetting %d,%d --> %d,%d (%s).\n",
1687 solver_recurse_depth*4, "",
1688 tile->x, tile->y,dx, dy, why));
1689 solvep(("%*sSetting %d,%d --> %d,%d (%s, opposite).\n",
1690 solver_recurse_depth*4, "",
1691 tile_opp->x, tile_opp->y, dx, dy, why));
1695 static int solver_obvious_dot(game_state *state, space *dot)
1697 int dx, dy, ret, didsth = 0;
1700 debug(("%*ssolver_obvious_dot for %d,%d.\n",
1701 solver_recurse_depth*4, "", dot->x, dot->y));
1703 assert(dot->flags & F_DOT);
1704 for (dx = -1; dx <= 1; dx++) {
1705 for (dy = -1; dy <= 1; dy++) {
1706 if (!INGRID(state, dot->x+dx, dot->y+dy)) continue;
1708 tile = &SPACE(state, dot->x+dx, dot->y+dy);
1709 if (tile->type == s_tile) {
1710 ret = solver_add_assoc(state, tile, dot->x, dot->y,
1712 if (ret < 0) return -1;
1713 if (ret > 0) didsth = 1;
1720 static int solver_obvious(game_state *state)
1722 int i, didsth = 0, ret;
1724 debug(("%*ssolver_obvious.\n", solver_recurse_depth*4, ""));
1726 for (i = 0; i < state->ndots; i++) {
1727 ret = solver_obvious_dot(state, state->dots[i]);
1728 if (ret < 0) return -1;
1729 if (ret > 0) didsth = 1;
1734 static int solver_lines_opposite_cb(game_state *state, space *edge, void *ctx)
1736 int didsth = 0, n, dx, dy;
1737 space *tiles[2], *tile_opp, *edge_opp;
1739 assert(edge->type == s_edge);
1741 tiles_from_edge(state, edge, tiles);
1743 /* if tiles[0] && tiles[1] && they're both associated
1744 * and they're both associated with different dots,
1745 * ensure the line is set. */
1746 if (!(edge->flags & F_EDGE_SET) &&
1747 tiles[0] && tiles[1] &&
1748 (tiles[0]->flags & F_TILE_ASSOC) &&
1749 (tiles[1]->flags & F_TILE_ASSOC) &&
1750 (tiles[0]->dotx != tiles[1]->dotx ||
1751 tiles[0]->doty != tiles[1]->doty)) {
1752 /* No edge, but the two adjacent tiles are both
1753 * associated with different dots; add the edge. */
1754 solvep(("%*sSetting edge %d,%d - tiles different dots.\n",
1755 solver_recurse_depth*4, "", edge->x, edge->y));
1756 edge->flags |= F_EDGE_SET;
1760 if (!(edge->flags & F_EDGE_SET)) return didsth;
1761 for (n = 0; n < 2; n++) {
1762 if (!tiles[n]) continue;
1763 assert(tiles[n]->type == s_tile);
1764 if (!(tiles[n]->flags & F_TILE_ASSOC)) continue;
1766 tile_opp = tile_opposite(state, tiles[n]);
1768 solvep(("%*simpossible: edge %d,%d has assoc. tile %d,%d"
1769 " with no opposite.\n",
1770 solver_recurse_depth*4, "",
1771 edge->x, edge->y, tiles[n]->x, tiles[n]->y));
1772 /* edge of tile has no opposite edge (off grid?);
1773 * this is impossible. */
1777 dx = tiles[n]->x - edge->x;
1778 dy = tiles[n]->y - edge->y;
1779 assert(INGRID(state, tile_opp->x+dx, tile_opp->y+dy));
1780 edge_opp = &SPACE(state, tile_opp->x+dx, tile_opp->y+dy);
1781 if (!(edge_opp->flags & F_EDGE_SET)) {
1782 solvep(("%*sSetting edge %d,%d as opposite %d,%d\n",
1783 solver_recurse_depth*4, "",
1784 tile_opp->x-dx, tile_opp->y-dy, edge->x, edge->y));
1785 edge_opp->flags |= F_EDGE_SET;
1792 static int solver_spaces_oneposs_cb(game_state *state, space *tile, void *ctx)
1795 space *edgeadj[4], *tileadj[4];
1798 assert(tile->type == s_tile);
1799 if (tile->flags & F_TILE_ASSOC) return 0;
1801 adjacencies(state, tile, edgeadj, tileadj);
1803 /* Empty tile. If each edge is either set, or associated with
1804 * the same dot, we must also associate with dot. */
1805 eset = 0; dotx = -1; doty = -1;
1806 for (n = 0; n < 4; n++) {
1808 assert(edgeadj[n]->type == s_edge);
1809 if (edgeadj[n]->flags & F_EDGE_SET) {
1813 assert(tileadj[n]->type == s_tile);
1815 /* If an adjacent tile is empty we can't make any deductions.*/
1816 if (!(tileadj[n]->flags & F_TILE_ASSOC))
1819 /* If an adjacent tile is assoc. with a different dot
1820 * we can't make any deductions. */
1821 if (dotx != -1 && doty != -1 &&
1822 (tileadj[n]->dotx != dotx ||
1823 tileadj[n]->doty != doty))
1826 dotx = tileadj[n]->dotx;
1827 doty = tileadj[n]->doty;
1831 solvep(("%*simpossible: empty tile %d,%d has 4 edges\n",
1832 solver_recurse_depth*4, "",
1836 assert(dotx != -1 && doty != -1);
1838 ret = solver_add_assoc(state, tile, dotx, doty, "rest are edges");
1839 if (ret == -1) return -1;
1840 assert(ret != 0); /* really should have done something. */
1845 /* Improved algorithm for tracking line-of-sight from dots, and not spaces.
1847 * The solver_ctx already stores a list of dots: the algorithm proceeds by
1848 * expanding outwards from each dot in turn, expanding first to the boundary
1849 * of its currently-connected tile and then to all empty tiles that could see
1850 * it. Empty tiles will be flagged with a 'can see dot <x,y>' sticker.
1852 * Expansion will happen by (symmetrically opposite) pairs of squares; if
1853 * a square hasn't an opposite number there's no point trying to expand through
1854 * it. Empty tiles will therefore also be tagged in pairs.
1856 * If an empty tile already has a 'can see dot <x,y>' tag from a previous dot,
1857 * it (and its partner) gets untagged (or, rather, a 'can see two dots' tag)
1858 * because we're looking for single-dot possibilities.
1860 * Once we've gone through all the dots, any which still have a 'can see dot'
1861 * tag get associated with that dot (because it must have been the only one);
1862 * any without any tag (i.e. that could see _no_ dots) cause an impossibility
1865 * The expansion will happen each time with a stored list of (space *) pairs,
1866 * rather than a mark-and-sweep idea; that's horrifically inefficient.
1868 * expansion algorithm:
1870 * * allocate list of (space *) the size of s->sx*s->sy.
1871 * * allocate second grid for (flags, dotx, doty) size of sx*sy.
1873 * clear second grid (flags = 0, all dotx and doty = 0)
1874 * flags: F_REACHABLE, F_MULTIPLE
1877 * * for each dot, start with one pair of tiles that are associated with it --
1878 * * vertex --> (dx+1, dy+1), (dx-1, dy-1)
1879 * * edge --> (adj1, adj2)
1880 * * tile --> (tile, tile) ???
1881 * * mark that pair of tiles with F_MARK, clear all other F_MARKs.
1882 * * add two tiles to start of list.
1884 * set start = 0, end = next = 2
1886 * from (start to end-1, step 2) {
1887 * * we have two tiles (t1, t2), opposites wrt our dot.
1888 * * for each (at1) sensible adjacent tile to t1 (i.e. not past an edge):
1889 * * work out at2 as the opposite to at1
1890 * * assert at1 and at2 have the same F_MARK values.
1891 * * if at1 & F_MARK ignore it (we've been there on a previous sweep)
1892 * * if either are associated with a different dot
1893 * * mark both with F_MARK (so we ignore them later)
1894 * * otherwise (assoc. with our dot, or empty):
1895 * * mark both with F_MARK
1896 * * add their space * values to the end of the list, set next += 2.
1900 * * we didn't add any new squares; exit the loop.
1902 * * set start = next+1, end = next. go round again
1904 * We've finished expanding from the dot. Now, for each square we have
1905 * in our list (--> each square with F_MARK):
1906 * * if the tile is empty:
1907 * * if F_REACHABLE was already set
1910 * * set F_REACHABLE, set dotx and doty to our dot.
1912 * Then, continue the whole thing for each dot in turn.
1914 * Once we've done for each dot, go through the entire grid looking for
1915 * empty tiles: for each empty tile:
1916 * if F_REACHABLE and not F_MULTIPLE, set that dot (and its double)
1917 * if !F_REACHABLE, return as impossible.
1921 /* Returns 1 if this tile is either already associated with this dot,
1923 static int solver_expand_checkdot(space *tile, space *dot)
1925 if (!(tile->flags & F_TILE_ASSOC)) return 1;
1926 if (tile->dotx == dot->x && tile->doty == dot->y) return 1;
1930 static void solver_expand_fromdot(game_state *state, space *dot, solver_ctx *sctx)
1932 int i, j, x, y, start, end, next;
1935 /* Clear the grid of the (space) flags we'll use. */
1937 /* This is well optimised; analysis showed that:
1938 for (i = 0; i < sctx->sz; i++) state->grid[i].flags &= ~F_MARK;
1939 took up ~85% of the total function time! */
1940 for (y = 1; y < state->sy; y += 2) {
1941 sp = &SPACE(state, 1, y);
1942 for (x = 1; x < state->sx; x += 2, sp += 2)
1943 sp->flags &= ~F_MARK;
1946 /* Seed the list of marked squares with two that must be associated
1947 * with our dot (possibly the same space) */
1948 if (dot->type == s_tile) {
1949 sctx->scratch[0] = sctx->scratch[1] = dot;
1950 } else if (dot->type == s_edge) {
1951 tiles_from_edge(state, dot, sctx->scratch);
1952 } else if (dot->type == s_vertex) {
1953 /* pick two of the opposite ones arbitrarily. */
1954 sctx->scratch[0] = &SPACE(state, dot->x-1, dot->y-1);
1955 sctx->scratch[1] = &SPACE(state, dot->x+1, dot->y+1);
1957 assert(sctx->scratch[0]->flags & F_TILE_ASSOC);
1958 assert(sctx->scratch[1]->flags & F_TILE_ASSOC);
1960 sctx->scratch[0]->flags |= F_MARK;
1961 sctx->scratch[1]->flags |= F_MARK;
1963 debug(("%*sexpand from dot %d,%d seeded with %d,%d and %d,%d.\n",
1964 solver_recurse_depth*4, "", dot->x, dot->y,
1965 sctx->scratch[0]->x, sctx->scratch[0]->y,
1966 sctx->scratch[1]->x, sctx->scratch[1]->y));
1968 start = 0; end = 2; next = 2;
1971 debug(("%*sexpand: start %d, end %d, next %d\n",
1972 solver_recurse_depth*4, "", start, end, next));
1973 for (i = start; i < end; i += 2) {
1974 space *t1 = sctx->scratch[i]/*, *t2 = sctx->scratch[i+1]*/;
1975 space *edges[4], *tileadj[4], *tileadj2;
1977 adjacencies(state, t1, edges, tileadj);
1979 for (j = 0; j < 4; j++) {
1981 if (edges[j]->flags & F_EDGE_SET) continue;
1984 if (tileadj[j]->flags & F_MARK) continue; /* seen before. */
1986 /* We have a tile adjacent to t1; find its opposite. */
1987 tileadj2 = space_opposite_dot(state, tileadj[j], dot);
1989 debug(("%*sMarking %d,%d, no opposite.\n",
1990 solver_recurse_depth*4, "",
1991 tileadj[j]->x, tileadj[j]->y));
1992 tileadj[j]->flags |= F_MARK;
1993 continue; /* no opposite, so mark for next time. */
1995 /* If the tile had an opposite we should have either seen both of
1996 * these, or neither of these, before. */
1997 assert(!(tileadj2->flags & F_MARK));
1999 if (solver_expand_checkdot(tileadj[j], dot) &&
2000 solver_expand_checkdot(tileadj2, dot)) {
2001 /* Both tiles could associate with this dot; add them to
2003 debug(("%*sAdding %d,%d and %d,%d to possibles list.\n",
2004 solver_recurse_depth*4, "",
2005 tileadj[j]->x, tileadj[j]->y, tileadj2->x, tileadj2->y));
2006 sctx->scratch[next++] = tileadj[j];
2007 sctx->scratch[next++] = tileadj2;
2009 /* Either way, we've seen these tiles already so mark them. */
2010 debug(("%*sMarking %d,%d and %d,%d.\n",
2011 solver_recurse_depth*4, "",
2012 tileadj[j]->x, tileadj[j]->y, tileadj2->x, tileadj2->y));
2013 tileadj[j]->flags |= F_MARK;
2014 tileadj2->flags |= F_MARK;
2018 /* We added more squares; go back and try again. */
2019 start = end; end = next; goto expand;
2022 /* We've expanded as far as we can go. Now we update the main flags
2023 * on all tiles we've expanded into -- if they were empty, we have
2024 * found possible associations for this dot. */
2025 for (i = 0; i < end; i++) {
2026 if (sctx->scratch[i]->flags & F_TILE_ASSOC) continue;
2027 if (sctx->scratch[i]->flags & F_REACHABLE) {
2028 /* This is (at least) the second dot this tile could
2029 * associate with. */
2030 debug(("%*sempty tile %d,%d could assoc. other dot %d,%d\n",
2031 solver_recurse_depth*4, "",
2032 sctx->scratch[i]->x, sctx->scratch[i]->y, dot->x, dot->y));
2033 sctx->scratch[i]->flags |= F_MULTIPLE;
2035 /* This is the first (possibly only) dot. */
2036 debug(("%*sempty tile %d,%d could assoc. 1st dot %d,%d\n",
2037 solver_recurse_depth*4, "",
2038 sctx->scratch[i]->x, sctx->scratch[i]->y, dot->x, dot->y));
2039 sctx->scratch[i]->flags |= F_REACHABLE;
2040 sctx->scratch[i]->dotx = dot->x;
2041 sctx->scratch[i]->doty = dot->y;
2047 static int solver_expand_postcb(game_state *state, space *tile, void *ctx)
2049 assert(tile->type == s_tile);
2051 if (tile->flags & F_TILE_ASSOC) return 0;
2053 if (!(tile->flags & F_REACHABLE)) {
2054 solvep(("%*simpossible: space (%d,%d) can reach no dots.\n",
2055 solver_recurse_depth*4, "", tile->x, tile->y));
2058 if (tile->flags & F_MULTIPLE) return 0;
2060 return solver_add_assoc(state, tile, tile->dotx, tile->doty,
2061 "single possible dot after expansion");
2064 static int solver_expand_dots(game_state *state, solver_ctx *sctx)
2068 for (i = 0; i < sctx->sz; i++)
2069 state->grid[i].flags &= ~(F_REACHABLE|F_MULTIPLE);
2071 for (i = 0; i < state->ndots; i++)
2072 solver_expand_fromdot(state, state->dots[i], sctx);
2074 return foreach_tile(state, solver_expand_postcb, IMPOSSIBLE_QUITS, sctx);
2077 struct recurse_ctx {
2082 static int solver_recurse_cb(game_state *state, space *tile, void *ctx)
2084 struct recurse_ctx *rctx = (struct recurse_ctx *)ctx;
2087 assert(tile->type == s_tile);
2088 if (tile->flags & F_TILE_ASSOC) return 0;
2090 /* We're unassociated: count up all the dots we could associate with. */
2091 for (i = 0; i < state->ndots; i++) {
2092 if (dotfortile(state, tile, state->dots[i]))
2095 if (n > rctx->bestn) {
2102 #define MAXRECURSE 5
2104 static int solver_recurse(game_state *state, int maxdiff)
2106 int diff = DIFF_IMPOSSIBLE, ret, n, gsz = state->sx * state->sy;
2107 space *ingrid, *outgrid = NULL, *bestopp;
2108 struct recurse_ctx rctx;
2110 if (solver_recurse_depth >= MAXRECURSE) {
2111 solvep(("Limiting recursion to %d, returning.", MAXRECURSE));
2112 return DIFF_UNFINISHED;
2115 /* Work out the cell to recurse on; go through all unassociated tiles
2116 * and find which one has the most possible dots it could associate
2121 foreach_tile(state, solver_recurse_cb, 0, &rctx);
2122 if (rctx.bestn == 0) return DIFF_IMPOSSIBLE; /* or assert? */
2125 solvep(("%*sRecursing around %d,%d, with %d possible dots.\n",
2126 solver_recurse_depth*4, "",
2127 rctx.best->x, rctx.best->y, rctx.bestn));
2129 #ifdef STANDALONE_SOLVER
2130 solver_recurse_depth++;
2133 ingrid = snewn(gsz, space);
2134 memcpy(ingrid, state->grid, gsz * sizeof(space));
2136 for (n = 0; n < state->ndots; n++) {
2137 memcpy(state->grid, ingrid, gsz * sizeof(space));
2139 if (!dotfortile(state, rctx.best, state->dots[n])) continue;
2141 /* set cell (temporarily) pointing to that dot. */
2142 solver_add_assoc(state, rctx.best,
2143 state->dots[n]->x, state->dots[n]->y,
2144 "Attempting for recursion");
2146 ret = solver_state(state, maxdiff);
2148 if (diff == DIFF_IMPOSSIBLE && ret != DIFF_IMPOSSIBLE) {
2149 /* we found our first solved grid; copy it away. */
2151 outgrid = snewn(gsz, space);
2152 memcpy(outgrid, state->grid, gsz * sizeof(space));
2154 /* reset cell back to unassociated. */
2155 bestopp = tile_opposite(state, rctx.best);
2156 assert(bestopp && bestopp->flags & F_TILE_ASSOC);
2158 remove_assoc(state, rctx.best);
2159 remove_assoc(state, bestopp);
2161 if (ret == DIFF_AMBIGUOUS || ret == DIFF_UNFINISHED)
2163 else if (ret == DIFF_IMPOSSIBLE)
2166 /* precisely one solution */
2167 if (diff == DIFF_IMPOSSIBLE)
2168 diff = DIFF_UNREASONABLE;
2170 diff = DIFF_AMBIGUOUS;
2172 /* if we've found >1 solution, or ran out of recursion,
2173 * give up immediately. */
2174 if (diff == DIFF_AMBIGUOUS || diff == DIFF_UNFINISHED)
2178 #ifdef STANDALONE_SOLVER
2179 solver_recurse_depth--;
2183 /* we found (at least one) soln; copy it back to state */
2184 memcpy(state->grid, outgrid, gsz * sizeof(space));
2191 static int solver_state(game_state *state, int maxdiff)
2193 solver_ctx *sctx = new_solver(state);
2194 int ret, diff = DIFF_NORMAL;
2196 #ifdef STANDALONE_PICTURE_GENERATOR
2197 /* hack, hack: set picture to NULL during solving so that add_assoc
2198 * won't complain when we attempt recursive guessing and guess wrong */
2199 int *savepic = picture;
2203 ret = solver_obvious(state);
2205 diff = DIFF_IMPOSSIBLE;
2209 #define CHECKRET(d) do { \
2210 if (ret < 0) { diff = DIFF_IMPOSSIBLE; goto got_result; } \
2211 if (ret > 0) { diff = max(diff, (d)); goto cont; } \
2216 ret = foreach_edge(state, solver_lines_opposite_cb,
2217 IMPOSSIBLE_QUITS, sctx);
2218 CHECKRET(DIFF_NORMAL);
2220 ret = foreach_tile(state, solver_spaces_oneposs_cb,
2221 IMPOSSIBLE_QUITS, sctx);
2222 CHECKRET(DIFF_NORMAL);
2224 ret = solver_expand_dots(state, sctx);
2225 CHECKRET(DIFF_NORMAL);
2227 if (maxdiff <= DIFF_NORMAL)
2232 /* if we reach here, we've made no deductions, so we terminate. */
2236 if (check_complete(state, NULL, NULL)) goto got_result;
2238 diff = (maxdiff >= DIFF_UNREASONABLE) ?
2239 solver_recurse(state, maxdiff) : DIFF_UNFINISHED;
2243 #ifndef STANDALONE_SOLVER
2244 debug(("solver_state ends, diff %s:\n", galaxies_diffnames[diff]));
2248 #ifdef STANDALONE_PICTURE_GENERATOR
2256 static char *solve_game(const game_state *state, const game_state *currstate,
2257 const char *aux, char **error)
2259 game_state *tosolve;
2264 tosolve = dup_game(currstate);
2265 diff = solver_state(tosolve, DIFF_UNREASONABLE);
2266 if (diff != DIFF_UNFINISHED && diff != DIFF_IMPOSSIBLE) {
2267 debug(("solve_game solved with current state.\n"));
2272 tosolve = dup_game(state);
2273 diff = solver_state(tosolve, DIFF_UNREASONABLE);
2274 if (diff != DIFF_UNFINISHED && diff != DIFF_IMPOSSIBLE) {
2275 debug(("solve_game solved with original state.\n"));
2284 * Clear tile associations: the solution will only include the
2287 for (i = 0; i < tosolve->sx*tosolve->sy; i++)
2288 tosolve->grid[i].flags &= ~F_TILE_ASSOC;
2289 ret = diff_game(currstate, tosolve, 1);
2295 /* ----------------------------------------------------------
2301 int dx, dy; /* pixel coords of drag pos. */
2302 int dotx, doty; /* grid coords of dot we're dragging from. */
2303 int srcx, srcy; /* grid coords of drag start */
2304 int cur_x, cur_y, cur_visible;
2307 static game_ui *new_ui(const game_state *state)
2309 game_ui *ui = snew(game_ui);
2310 ui->dragging = FALSE;
2311 ui->cur_x = ui->cur_y = 1;
2312 ui->cur_visible = 0;
2316 static void free_ui(game_ui *ui)
2321 static char *encode_ui(const game_ui *ui)
2326 static void decode_ui(game_ui *ui, const char *encoding)
2330 static void game_changed_state(game_ui *ui, const game_state *oldstate,
2331 const game_state *newstate)
2335 #define FLASH_TIME 0.15F
2337 #define PREFERRED_TILE_SIZE 32
2338 #define TILE_SIZE (ds->tilesize)
2339 #define DOT_SIZE (TILE_SIZE / 4)
2340 #define EDGE_THICKNESS (max(TILE_SIZE / 16, 2))
2341 #define BORDER TILE_SIZE
2343 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
2344 #define SCOORD(x) ( ((x) * TILE_SIZE)/2 + BORDER )
2345 #define FROMCOORD(x) ( ((x) - BORDER) / TILE_SIZE )
2347 #define DRAW_WIDTH (BORDER * 2 + ds->w * TILE_SIZE)
2348 #define DRAW_HEIGHT (BORDER * 2 + ds->h * TILE_SIZE)
2350 #define CURSOR_SIZE DOT_SIZE
2352 struct game_drawstate {
2356 unsigned long *grid;
2361 int dragging, dragx, dragy;
2363 int *colour_scratch;
2365 int cx, cy, cur_visible;
2369 #define CORNER_TOLERANCE 0.15F
2370 #define CENTRE_TOLERANCE 0.15F
2373 * Round FP coordinates to the centre of the nearest edge.
2376 static void coord_round_to_edge(float x, float y, int *xr, int *yr)
2378 float xs, ys, xv, yv, dx, dy;
2381 * Find the nearest square-centre.
2383 xs = (float)floor(x) + 0.5F;
2384 ys = (float)floor(y) + 0.5F;
2387 * Find the nearest grid vertex.
2389 xv = (float)floor(x + 0.5F);
2390 yv = (float)floor(y + 0.5F);
2393 * Determine whether the horizontal or vertical edge from that
2394 * vertex alongside that square is closer to us, by comparing
2395 * distances from the square cente.
2397 dx = (float)fabs(x - xs);
2398 dy = (float)fabs(y - ys);
2400 /* Vertical edge: x-coord of corner,
2401 * y-coord of square centre. */
2403 *yr = 1 + 2 * (int)floor(ys);
2405 /* Horizontal edge: x-coord of square centre,
2406 * y-coord of corner. */
2407 *xr = 1 + 2 * (int)floor(xs);
2414 static char *interpret_move(const game_state *state, game_ui *ui,
2415 const game_drawstate *ds,
2416 int x, int y, int button)
2422 px = 2*FROMCOORD((float)x) + 0.5;
2423 py = 2*FROMCOORD((float)y) + 0.5;
2427 if (button == 'C' || button == 'c') return dupstr("C");
2429 if (button == 'S' || button == 's') {
2431 game_state *tmp = dup_game(state);
2432 state->cdiff = solver_state(tmp, DIFF_UNREASONABLE-1);
2433 ret = diff_game(state, tmp, 0);
2438 if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
2439 if (!INUI(state, px, py)) return NULL;
2440 sp = &SPACE(state, px, py);
2441 if (!dot_is_possible(state, sp, 1)) return NULL;
2442 sprintf(buf, "%c%d,%d",
2443 (char)((button == LEFT_BUTTON) ? 'D' : 'd'), px, py);
2450 static char *interpret_move(const game_state *state, game_ui *ui,
2451 const game_drawstate *ds,
2452 int x, int y, int button)
2454 /* UI operations (play mode):
2456 * Toggle edge (set/unset) (left-click on edge)
2457 * Associate space with dot (left-drag from dot)
2458 * Unassociate space (left-drag from space off grid)
2459 * Autofill lines around shape? (right-click?)
2461 * (edit mode; will clear all lines/associations)
2463 * Add or remove dot (left-click)
2466 const char *sep = "";
2472 if (button == 'H' || button == 'h') {
2474 game_state *tmp = dup_game(state);
2475 solver_obvious(tmp);
2476 ret = diff_game(state, tmp, 0);
2481 if (button == LEFT_BUTTON) {
2482 ui->cur_visible = 0;
2483 coord_round_to_edge(FROMCOORD((float)x), FROMCOORD((float)y),
2486 if (!INUI(state, px, py)) return NULL;
2488 sp = &SPACE(state, px, py);
2489 assert(sp->type == s_edge);
2491 sprintf(buf, "E%d,%d", px, py);
2494 } else if (button == RIGHT_BUTTON) {
2497 ui->cur_visible = 0;
2499 px = (int)(2*FROMCOORD((float)x) + 0.5);
2500 py = (int)(2*FROMCOORD((float)y) + 0.5);
2505 * If there's a dot anywhere nearby, we pick up an arrow
2506 * pointing at that dot.
2508 for (py1 = py-1; py1 <= py+1; py1++)
2509 for (px1 = px-1; px1 <= px+1; px1++) {
2510 if (px1 >= 0 && px1 < state->sx &&
2511 py1 >= 0 && py1 < state->sy &&
2512 x >= SCOORD(px1-1) && x < SCOORD(px1+1) &&
2513 y >= SCOORD(py1-1) && y < SCOORD(py1+1) &&
2514 SPACE(state, px1, py1).flags & F_DOT) {
2516 * Found a dot. Begin a drag from it.
2518 dot = &SPACE(state, px1, py1);
2521 goto done; /* multi-level break */
2526 * Otherwise, find the nearest _square_, and pick up the
2527 * same arrow as it's got on it, if any.
2530 px = 2*FROMCOORD(x+TILE_SIZE) - 1;
2531 py = 2*FROMCOORD(y+TILE_SIZE) - 1;
2532 if (px >= 0 && px < state->sx && py >= 0 && py < state->sy) {
2533 sp = &SPACE(state, px, py);
2534 if (sp->flags & F_TILE_ASSOC) {
2535 dot = &SPACE(state, sp->dotx, sp->doty);
2544 * Now, if we've managed to find a dot, begin a drag.
2547 ui->dragging = TRUE;
2554 } else if (button == RIGHT_DRAG && ui->dragging) {
2555 /* just move the drag coords. */
2559 } else if (button == RIGHT_RELEASE && ui->dragging) {
2560 ui->dragging = FALSE;
2563 * Drags are always targeted at a single square.
2565 px = 2*FROMCOORD(x+TILE_SIZE) - 1;
2566 py = 2*FROMCOORD(y+TILE_SIZE) - 1;
2569 * Dragging an arrow on to the same square it started from
2570 * is a null move; just update the ui and finish.
2572 if (px == ui->srcx && py == ui->srcy)
2576 * Otherwise, we remove the arrow from its starting
2577 * square if we didn't start from a dot...
2579 if ((ui->srcx != ui->dotx || ui->srcy != ui->doty) &&
2580 SPACE(state, ui->srcx, ui->srcy).flags & F_TILE_ASSOC) {
2581 sprintf(buf + strlen(buf), "%sU%d,%d", sep, ui->srcx, ui->srcy);
2586 * ... and if the square we're moving it _to_ is valid, we
2587 * add one there instead.
2589 if (INUI(state, px, py)) {
2590 sp = &SPACE(state, px, py);
2592 if (!(sp->flags & F_DOT) && !(sp->flags & F_TILE_ASSOC))
2593 sprintf(buf + strlen(buf), "%sA%d,%d,%d,%d",
2594 sep, px, py, ui->dotx, ui->doty);
2601 } else if (IS_CURSOR_MOVE(button)) {
2602 move_cursor(button, &ui->cur_x, &ui->cur_y, state->sx-1, state->sy-1, 0);
2603 if (ui->cur_x < 1) ui->cur_x = 1;
2604 if (ui->cur_y < 1) ui->cur_y = 1;
2605 ui->cur_visible = 1;
2607 ui->dx = SCOORD(ui->cur_x);
2608 ui->dy = SCOORD(ui->cur_y);
2611 } else if (IS_CURSOR_SELECT(button)) {
2612 if (!ui->cur_visible) {
2613 ui->cur_visible = 1;
2616 sp = &SPACE(state, ui->cur_x, ui->cur_y);
2618 ui->dragging = FALSE;
2620 if ((ui->srcx != ui->dotx || ui->srcy != ui->doty) &&
2621 SPACE(state, ui->srcx, ui->srcy).flags & F_TILE_ASSOC) {
2622 sprintf(buf, "%sU%d,%d", sep, ui->srcx, ui->srcy);
2625 if (sp->type == s_tile && !(sp->flags & F_DOT) && !(sp->flags & F_TILE_ASSOC)) {
2626 sprintf(buf + strlen(buf), "%sA%d,%d,%d,%d",
2627 sep, ui->cur_x, ui->cur_y, ui->dotx, ui->doty);
2630 } else if (sp->flags & F_DOT) {
2631 ui->dragging = TRUE;
2632 ui->dx = SCOORD(ui->cur_x);
2633 ui->dy = SCOORD(ui->cur_y);
2634 ui->dotx = ui->srcx = ui->cur_x;
2635 ui->doty = ui->srcy = ui->cur_y;
2637 } else if (sp->flags & F_TILE_ASSOC) {
2638 assert(sp->type == s_tile);
2639 ui->dragging = TRUE;
2640 ui->dx = SCOORD(ui->cur_x);
2641 ui->dy = SCOORD(ui->cur_y);
2642 ui->dotx = sp->dotx;
2643 ui->doty = sp->doty;
2644 ui->srcx = ui->cur_x;
2645 ui->srcy = ui->cur_y;
2647 } else if (sp->type == s_edge) {
2648 sprintf(buf, "E%d,%d", ui->cur_x, ui->cur_y);
2657 static int check_complete(const game_state *state, int *dsf, int *colours)
2659 int w = state->w, h = state->h;
2664 int minx, miny, maxx, maxy;
2670 dsf = snew_dsf(w*h);
2678 * During actual game play, completion checking is done on the
2679 * basis of the edges rather than the square associations. So
2680 * first we must go through the grid figuring out the connected
2681 * components into which the edges divide it.
2683 for (y = 0; y < h; y++)
2684 for (x = 0; x < w; x++) {
2685 if (y+1 < h && !(SPACE(state, 2*x+1, 2*y+2).flags & F_EDGE_SET))
2686 dsf_merge(dsf, y*w+x, (y+1)*w+x);
2687 if (x+1 < w && !(SPACE(state, 2*x+2, 2*y+1).flags & F_EDGE_SET))
2688 dsf_merge(dsf, y*w+x, y*w+(x+1));
2692 * That gives us our connected components. Now, for each
2693 * component, decide whether it's _valid_. A valid component is
2696 * - is 180-degree rotationally symmetric
2697 * - has a dot at its centre of symmetry
2698 * - has no other dots anywhere within it (including on its
2700 * - contains no internal edges (i.e. edges separating two
2701 * squares which are both part of the component).
2705 * First, go through the grid finding the bounding box of each
2708 sqdata = snewn(w*h, struct sqdata);
2709 for (i = 0; i < w*h; i++) {
2710 sqdata[i].minx = w+1;
2711 sqdata[i].miny = h+1;
2712 sqdata[i].maxx = sqdata[i].maxy = -1;
2713 sqdata[i].valid = FALSE;
2715 for (y = 0; y < h; y++)
2716 for (x = 0; x < w; x++) {
2717 i = dsf_canonify(dsf, y*w+x);
2718 if (sqdata[i].minx > x)
2720 if (sqdata[i].maxx < x)
2722 if (sqdata[i].miny > y)
2724 if (sqdata[i].maxy < y)
2726 sqdata[i].valid = TRUE;
2730 * Now we're in a position to loop over each actual component
2731 * and figure out where its centre of symmetry has to be if
2734 for (i = 0; i < w*h; i++)
2735 if (sqdata[i].valid) {
2737 cx = sqdata[i].cx = sqdata[i].minx + sqdata[i].maxx + 1;
2738 cy = sqdata[i].cy = sqdata[i].miny + sqdata[i].maxy + 1;
2739 if (!(SPACE(state, sqdata[i].cx, sqdata[i].cy).flags & F_DOT))
2740 sqdata[i].valid = FALSE; /* no dot at centre of symmetry */
2741 if (dsf_canonify(dsf, (cy-1)/2*w+(cx-1)/2) != i ||
2742 dsf_canonify(dsf, (cy)/2*w+(cx-1)/2) != i ||
2743 dsf_canonify(dsf, (cy-1)/2*w+(cx)/2) != i ||
2744 dsf_canonify(dsf, (cy)/2*w+(cx)/2) != i)
2745 sqdata[i].valid = FALSE; /* dot at cx,cy isn't ours */
2746 if (SPACE(state, sqdata[i].cx, sqdata[i].cy).flags & F_DOT_BLACK)
2747 sqdata[i].colour = 2;
2749 sqdata[i].colour = 1;
2753 * Now we loop over the whole grid again, this time finding
2754 * extraneous dots (any dot which wholly or partially overlaps
2755 * a square and is not at the centre of symmetry of that
2756 * square's component disqualifies the component from validity)
2757 * and extraneous edges (any edge separating two squares
2758 * belonging to the same component also disqualifies that
2761 for (y = 1; y < state->sy-1; y++)
2762 for (x = 1; x < state->sx-1; x++) {
2763 space *sp = &SPACE(state, x, y);
2765 if (sp->flags & F_DOT) {
2767 * There's a dot here. Use it to disqualify any
2768 * component which deserves it.
2771 for (cy = (y-1) >> 1; cy <= y >> 1; cy++)
2772 for (cx = (x-1) >> 1; cx <= x >> 1; cx++) {
2773 i = dsf_canonify(dsf, cy*w+cx);
2774 if (x != sqdata[i].cx || y != sqdata[i].cy)
2775 sqdata[i].valid = FALSE;
2779 if (sp->flags & F_EDGE_SET) {
2781 * There's an edge here. Use it to disqualify a
2782 * component if necessary.
2784 int cx1 = (x-1) >> 1, cx2 = x >> 1;
2785 int cy1 = (y-1) >> 1, cy2 = y >> 1;
2786 assert((cx1==cx2) ^ (cy1==cy2));
2787 i = dsf_canonify(dsf, cy1*w+cx1);
2788 if (i == dsf_canonify(dsf, cy2*w+cx2))
2789 sqdata[i].valid = FALSE;
2794 * And finally we test rotational symmetry: for each square in
2795 * the grid, find which component it's in, test that that
2796 * component also has a square in the symmetric position, and
2797 * disqualify it if it doesn't.
2799 for (y = 0; y < h; y++)
2800 for (x = 0; x < w; x++) {
2803 i = dsf_canonify(dsf, y*w+x);
2805 x2 = sqdata[i].cx - 1 - x;
2806 y2 = sqdata[i].cy - 1 - y;
2807 if (i != dsf_canonify(dsf, y2*w+x2))
2808 sqdata[i].valid = FALSE;
2812 * That's it. We now have all the connected components marked
2813 * as valid or not valid. So now we return a `colours' array if
2814 * we were asked for one, and also we return an overall
2815 * true/false value depending on whether _every_ square in the
2816 * grid is part of a valid component.
2819 for (i = 0; i < w*h; i++) {
2820 int ci = dsf_canonify(dsf, i);
2821 int thisok = sqdata[ci].valid;
2823 colours[i] = thisok ? sqdata[ci].colour : 0;
2824 ret = ret && thisok;
2834 static game_state *execute_move(const game_state *state, const char *move)
2836 int x, y, ax, ay, n, dx, dy;
2837 game_state *ret = dup_game(state);
2839 int currently_solving = FALSE;
2841 debug(("%s\n", move));
2845 if (c == 'E' || c == 'U' || c == 'M'
2847 || c == 'D' || c == 'd'
2851 if (sscanf(move, "%d,%d%n", &x, &y, &n) != 2 ||
2855 sp = &SPACE(ret, x, y);
2857 if (c == 'D' || c == 'd') {
2858 unsigned int currf, newf, maskf;
2860 if (!dot_is_possible(ret, sp, 1)) goto badmove;
2862 newf = F_DOT | (c == 'd' ? F_DOT_BLACK : 0);
2863 currf = GRID(ret, grid, x, y).flags;
2864 maskf = F_DOT | F_DOT_BLACK;
2865 /* if we clicked 'white dot':
2866 * white --> empty, empty --> white, black --> white.
2867 * if we clicked 'black dot':
2868 * black --> empty, empty --> black, white --> black.
2870 if (currf & maskf) {
2871 sp->flags &= ~maskf;
2872 if ((currf & maskf) != newf)
2876 sp->nassoc = 0; /* edit-mode disallows associations. */
2877 game_update_dots(ret);
2881 if (sp->type != s_edge) goto badmove;
2882 sp->flags ^= F_EDGE_SET;
2883 } else if (c == 'U') {
2884 if (sp->type != s_tile || !(sp->flags & F_TILE_ASSOC))
2886 /* The solver doesn't assume we'll mirror things */
2887 if (currently_solving)
2888 remove_assoc(ret, sp);
2890 remove_assoc_with_opposite(ret, sp);
2891 } else if (c == 'M') {
2892 if (!(sp->flags & F_DOT)) goto badmove;
2893 sp->flags ^= F_DOT_HOLD;
2896 } else if (c == 'A' || c == 'a') {
2898 if (sscanf(move, "%d,%d,%d,%d%n", &x, &y, &ax, &ay, &n) != 4 ||
2899 x < 1 || y < 1 || x >= (ret->sx-1) || y >= (ret->sy-1) ||
2900 ax < 1 || ay < 1 || ax >= (ret->sx-1) || ay >= (ret->sy-1))
2903 dot = &GRID(ret, grid, ax, ay);
2904 if (!(dot->flags & F_DOT))goto badmove;
2905 if (dot->flags & F_DOT_HOLD) goto badmove;
2907 for (dx = -1; dx <= 1; dx++) {
2908 for (dy = -1; dy <= 1; dy++) {
2909 sp = &GRID(ret, grid, x+dx, y+dy);
2910 if (sp->type != s_tile) continue;
2911 if (sp->flags & F_TILE_ASSOC) {
2912 space *dot = &SPACE(ret, sp->dotx, sp->doty);
2913 if (dot->flags & F_DOT_HOLD) continue;
2915 /* The solver doesn't assume we'll mirror things */
2916 if (currently_solving)
2917 add_assoc(ret, sp, dot);
2919 add_assoc_with_opposite(ret, sp, dot);
2924 } else if (c == 'C') {
2928 } else if (c == 'S') {
2930 ret->used_solve = 1;
2931 currently_solving = TRUE;
2940 if (check_complete(ret, NULL, NULL))
2949 /* ----------------------------------------------------------------------
2953 /* Lines will be much smaller size than squares; say, 1/8 the size?
2955 * Need a 'top-left corner of location XxY' to take this into account;
2956 * alternaticaly, that could give the middle of that location, and the
2957 * drawing code would just know the expected dimensions.
2959 * We also need something to take a click and work out what it was
2960 * we were interested in. Clicking on vertices is required because
2961 * we may want to drag from them, for example.
2964 static void game_compute_size(const game_params *params, int sz,
2967 struct { int tilesize, w, h; } ads, *ds = &ads;
2977 static void game_set_size(drawing *dr, game_drawstate *ds,
2978 const game_params *params, int sz)
2982 assert(TILE_SIZE > 0);
2985 ds->bl = blitter_new(dr, TILE_SIZE, TILE_SIZE);
2987 assert(!ds->blmirror);
2988 ds->blmirror = blitter_new(dr, TILE_SIZE, TILE_SIZE);
2990 assert(!ds->cur_bl);
2991 ds->cur_bl = blitter_new(dr, TILE_SIZE, TILE_SIZE);
2994 static float *game_colours(frontend *fe, int *ncolours)
2996 float *ret = snewn(3 * NCOLOURS, float);
3000 * We call game_mkhighlight to ensure the background colour
3001 * isn't completely white. We don't actually use the high- and
3002 * lowlight colours it generates.
3004 game_mkhighlight(fe, ret, COL_BACKGROUND, COL_WHITEBG, COL_BLACKBG);
3006 for (i = 0; i < 3; i++) {
3008 * Currently, white dots and white-background squares are
3011 ret[COL_WHITEDOT * 3 + i] = 1.0F;
3012 ret[COL_WHITEBG * 3 + i] = 1.0F;
3015 * But black-background squares are a dark grey, whereas
3016 * black dots are really black.
3018 ret[COL_BLACKDOT * 3 + i] = 0.0F;
3019 ret[COL_BLACKBG * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.3F;
3022 * In unfilled squares, we draw a faint gridwork.
3024 ret[COL_GRID * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.8F;
3027 * Edges and arrows are filled in in pure black.
3029 ret[COL_EDGE * 3 + i] = 0.0F;
3030 ret[COL_ARROW * 3 + i] = 0.0F;
3034 /* tinge the edit background to bluey */
3035 ret[COL_BACKGROUND * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
3036 ret[COL_BACKGROUND * 3 + 1] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
3037 ret[COL_BACKGROUND * 3 + 2] = min(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
3040 ret[COL_CURSOR * 3 + 0] = min(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
3041 ret[COL_CURSOR * 3 + 1] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
3042 ret[COL_CURSOR * 3 + 2] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
3044 *ncolours = NCOLOURS;
3048 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
3050 struct game_drawstate *ds = snew(struct game_drawstate);
3057 ds->grid = snewn(ds->w*ds->h, unsigned long);
3058 for (i = 0; i < ds->w*ds->h; i++)
3059 ds->grid[i] = 0xFFFFFFFFUL;
3060 ds->dx = snewn(ds->w*ds->h, int);
3061 ds->dy = snewn(ds->w*ds->h, int);
3064 ds->blmirror = NULL;
3065 ds->dragging = FALSE;
3066 ds->dragx = ds->dragy = 0;
3068 ds->colour_scratch = snewn(ds->w * ds->h, int);
3071 ds->cx = ds->cy = 0;
3072 ds->cur_visible = 0;
3077 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
3079 if (ds->cur_bl) blitter_free(dr, ds->cur_bl);
3080 sfree(ds->colour_scratch);
3081 if (ds->blmirror) blitter_free(dr, ds->blmirror);
3082 if (ds->bl) blitter_free(dr, ds->bl);
3089 #define DRAW_EDGE_L 0x0001
3090 #define DRAW_EDGE_R 0x0002
3091 #define DRAW_EDGE_U 0x0004
3092 #define DRAW_EDGE_D 0x0008
3093 #define DRAW_CORNER_UL 0x0010
3094 #define DRAW_CORNER_UR 0x0020
3095 #define DRAW_CORNER_DL 0x0040
3096 #define DRAW_CORNER_DR 0x0080
3097 #define DRAW_WHITE 0x0100
3098 #define DRAW_BLACK 0x0200
3099 #define DRAW_ARROW 0x0400
3100 #define DRAW_CURSOR 0x0800
3101 #define DOT_SHIFT_C 12
3102 #define DOT_SHIFT_M 2
3103 #define DOT_WHITE 1UL
3104 #define DOT_BLACK 2UL
3107 * Draw an arrow centred on (cx,cy), pointing in the direction
3108 * (ddx,ddy). (I.e. pointing at the point (cx+ddx, cy+ddy).
3110 static void draw_arrow(drawing *dr, game_drawstate *ds,
3111 int cx, int cy, int ddx, int ddy, int col)
3113 float vlen = (float)sqrt(ddx*ddx+ddy*ddy);
3114 float xdx = ddx/vlen, xdy = ddy/vlen;
3115 float ydx = -xdy, ydy = xdx;
3116 int e1x = cx + (int)(xdx*TILE_SIZE/3), e1y = cy + (int)(xdy*TILE_SIZE/3);
3117 int e2x = cx - (int)(xdx*TILE_SIZE/3), e2y = cy - (int)(xdy*TILE_SIZE/3);
3118 int adx = (int)((ydx-xdx)*TILE_SIZE/8), ady = (int)((ydy-xdy)*TILE_SIZE/8);
3119 int adx2 = (int)((-ydx-xdx)*TILE_SIZE/8), ady2 = (int)((-ydy-xdy)*TILE_SIZE/8);
3121 draw_line(dr, e1x, e1y, e2x, e2y, col);
3122 draw_line(dr, e1x, e1y, e1x+adx, e1y+ady, col);
3123 draw_line(dr, e1x, e1y, e1x+adx2, e1y+ady2, col);
3126 static void draw_square(drawing *dr, game_drawstate *ds, int x, int y,
3127 unsigned long flags, int ddx, int ddy)
3129 int lx = COORD(x), ly = COORD(y);
3133 clip(dr, lx, ly, TILE_SIZE, TILE_SIZE);
3136 * Draw the tile background.
3138 draw_rect(dr, lx, ly, TILE_SIZE, TILE_SIZE,
3139 (flags & DRAW_WHITE ? COL_WHITEBG :
3140 flags & DRAW_BLACK ? COL_BLACKBG : COL_BACKGROUND));
3145 gridcol = (flags & DRAW_BLACK ? COL_BLACKDOT : COL_GRID);
3146 draw_rect(dr, lx, ly, 1, TILE_SIZE, gridcol);
3147 draw_rect(dr, lx, ly, TILE_SIZE, 1, gridcol);
3150 * Draw the arrow, if present, or the cursor, if here.
3152 if (flags & DRAW_ARROW)
3153 draw_arrow(dr, ds, lx + TILE_SIZE/2, ly + TILE_SIZE/2, ddx, ddy,
3154 (flags & DRAW_CURSOR) ? COL_CURSOR : COL_ARROW);
3155 else if (flags & DRAW_CURSOR)
3156 draw_rect_outline(dr,
3157 lx + TILE_SIZE/2 - CURSOR_SIZE,
3158 ly + TILE_SIZE/2 - CURSOR_SIZE,
3159 2*CURSOR_SIZE+1, 2*CURSOR_SIZE+1,
3165 if (flags & DRAW_EDGE_L)
3166 draw_rect(dr, lx, ly, EDGE_THICKNESS, TILE_SIZE, COL_EDGE);
3167 if (flags & DRAW_EDGE_R)
3168 draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1, ly,
3169 EDGE_THICKNESS - 1, TILE_SIZE, COL_EDGE);
3170 if (flags & DRAW_EDGE_U)
3171 draw_rect(dr, lx, ly, TILE_SIZE, EDGE_THICKNESS, COL_EDGE);
3172 if (flags & DRAW_EDGE_D)
3173 draw_rect(dr, lx, ly + TILE_SIZE - EDGE_THICKNESS + 1,
3174 TILE_SIZE, EDGE_THICKNESS - 1, COL_EDGE);
3175 if (flags & DRAW_CORNER_UL)
3176 draw_rect(dr, lx, ly, EDGE_THICKNESS, EDGE_THICKNESS, COL_EDGE);
3177 if (flags & DRAW_CORNER_UR)
3178 draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1, ly,
3179 EDGE_THICKNESS - 1, EDGE_THICKNESS, COL_EDGE);
3180 if (flags & DRAW_CORNER_DL)
3181 draw_rect(dr, lx, ly + TILE_SIZE - EDGE_THICKNESS + 1,
3182 EDGE_THICKNESS, EDGE_THICKNESS - 1, COL_EDGE);
3183 if (flags & DRAW_CORNER_DR)
3184 draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1,
3185 ly + TILE_SIZE - EDGE_THICKNESS + 1,
3186 EDGE_THICKNESS - 1, EDGE_THICKNESS - 1, COL_EDGE);
3191 for (dy = 0; dy < 3; dy++)
3192 for (dx = 0; dx < 3; dx++) {
3193 int dotval = (flags >> (DOT_SHIFT_C + DOT_SHIFT_M*(dy*3+dx)));
3194 dotval &= (1 << DOT_SHIFT_M)-1;
3197 draw_circle(dr, lx+dx*TILE_SIZE/2, ly+dy*TILE_SIZE/2,
3199 (dotval == 1 ? COL_WHITEDOT : COL_BLACKDOT),
3204 draw_update(dr, lx, ly, TILE_SIZE, TILE_SIZE);
3207 static void calculate_opposite_point(const game_ui *ui,
3208 const game_drawstate *ds, const int x,
3209 const int y, int *oppositex,
3212 /* oppositex - dotx = dotx - x <=> oppositex = 2 * dotx - x */
3213 *oppositex = 2 * SCOORD(ui->dotx) - x;
3214 *oppositey = 2 * SCOORD(ui->doty) - y;
3217 static void game_redraw(drawing *dr, game_drawstate *ds,
3218 const game_state *oldstate, const game_state *state,
3219 int dir, const game_ui *ui,
3220 float animtime, float flashtime)
3222 int w = ds->w, h = ds->h;
3223 int x, y, flashing = FALSE;
3226 if (flashtime > 0) {
3227 int frame = (int)(flashtime / FLASH_TIME);
3228 flashing = (frame % 2 == 0);
3233 assert(ds->blmirror);
3234 calculate_opposite_point(ui, ds, ds->dragx + TILE_SIZE/2,
3235 ds->dragy + TILE_SIZE/2, &oppx, &oppy);
3236 oppx -= TILE_SIZE/2;
3237 oppy -= TILE_SIZE/2;
3238 blitter_load(dr, ds->bl, ds->dragx, ds->dragy);
3239 draw_update(dr, ds->dragx, ds->dragy, TILE_SIZE, TILE_SIZE);
3240 blitter_load(dr, ds->blmirror, oppx, oppy);
3241 draw_update(dr, oppx, oppy, TILE_SIZE, TILE_SIZE);
3242 ds->dragging = FALSE;
3244 if (ds->cur_visible) {
3246 blitter_load(dr, ds->cur_bl, ds->cx, ds->cy);
3247 draw_update(dr, ds->cx, ds->cy, CURSOR_SIZE*2+1, CURSOR_SIZE*2+1);
3248 ds->cur_visible = FALSE;
3252 draw_rect(dr, 0, 0, DRAW_WIDTH, DRAW_HEIGHT, COL_BACKGROUND);
3253 draw_rect(dr, BORDER - EDGE_THICKNESS + 1, BORDER - EDGE_THICKNESS + 1,
3254 w*TILE_SIZE + EDGE_THICKNESS*2 - 1,
3255 h*TILE_SIZE + EDGE_THICKNESS*2 - 1, COL_EDGE);
3256 draw_update(dr, 0, 0, DRAW_WIDTH, DRAW_HEIGHT);
3260 check_complete(state, NULL, ds->colour_scratch);
3262 for (y = 0; y < h; y++)
3263 for (x = 0; x < w; x++) {
3264 unsigned long flags = 0;
3265 int ddx = 0, ddy = 0;
3270 * Set up the flags for this square. Firstly, see if we
3273 if (SPACE(state, x*2, y*2+1).flags & F_EDGE_SET)
3274 flags |= DRAW_EDGE_L;
3275 if (SPACE(state, x*2+2, y*2+1).flags & F_EDGE_SET)
3276 flags |= DRAW_EDGE_R;
3277 if (SPACE(state, x*2+1, y*2).flags & F_EDGE_SET)
3278 flags |= DRAW_EDGE_U;
3279 if (SPACE(state, x*2+1, y*2+2).flags & F_EDGE_SET)
3280 flags |= DRAW_EDGE_D;
3283 * Also, mark corners of neighbouring edges.
3285 if ((x > 0 && SPACE(state, x*2-1, y*2).flags & F_EDGE_SET) ||
3286 (y > 0 && SPACE(state, x*2, y*2-1).flags & F_EDGE_SET))
3287 flags |= DRAW_CORNER_UL;
3288 if ((x+1 < w && SPACE(state, x*2+3, y*2).flags & F_EDGE_SET) ||
3289 (y > 0 && SPACE(state, x*2+2, y*2-1).flags & F_EDGE_SET))
3290 flags |= DRAW_CORNER_UR;
3291 if ((x > 0 && SPACE(state, x*2-1, y*2+2).flags & F_EDGE_SET) ||
3292 (y+1 < h && SPACE(state, x*2, y*2+3).flags & F_EDGE_SET))
3293 flags |= DRAW_CORNER_DL;
3294 if ((x+1 < w && SPACE(state, x*2+3, y*2+2).flags & F_EDGE_SET) ||
3295 (y+1 < h && SPACE(state, x*2+2, y*2+3).flags & F_EDGE_SET))
3296 flags |= DRAW_CORNER_DR;
3299 * If this square is part of a valid region, paint it
3300 * that region's colour. Exception: if we're flashing,
3301 * everything goes briefly back to background colour.
3303 sp = &SPACE(state, x*2+1, y*2+1);
3304 if (ds->colour_scratch[y*w+x] && !flashing) {
3305 flags |= (ds->colour_scratch[y*w+x] == 2 ?
3306 DRAW_BLACK : DRAW_WHITE);
3310 * If this square is associated with a dot but it isn't
3311 * part of a valid region, draw an arrow in it pointing
3312 * in the direction of that dot.
3314 * Exception: if this is the source point of an active
3315 * drag, we don't draw the arrow.
3317 if ((sp->flags & F_TILE_ASSOC) && !ds->colour_scratch[y*w+x]) {
3318 if (ui->dragging && ui->srcx == x*2+1 && ui->srcy == y*2+1) {
3320 } else if (sp->doty != y*2+1 || sp->dotx != x*2+1) {
3321 flags |= DRAW_ARROW;
3322 ddy = sp->doty - (y*2+1);
3323 ddx = sp->dotx - (x*2+1);
3328 * Now go through the nine possible places we could
3331 for (dy = 0; dy < 3; dy++)
3332 for (dx = 0; dx < 3; dx++) {
3333 sp = &SPACE(state, x*2+dx, y*2+dy);
3334 if (sp->flags & F_DOT) {
3335 unsigned long dotval = (sp->flags & F_DOT_BLACK ?
3336 DOT_BLACK : DOT_WHITE);
3337 flags |= dotval << (DOT_SHIFT_C +
3338 DOT_SHIFT_M*(dy*3+dx));
3343 * Now work out if we have to draw a cursor for this square;
3344 * cursors-on-lines are taken care of below.
3346 if (ui->cur_visible &&
3347 ui->cur_x == x*2+1 && ui->cur_y == y*2+1 &&
3348 !(SPACE(state, x*2+1, y*2+1).flags & F_DOT))
3349 flags |= DRAW_CURSOR;
3352 * Now we have everything we're going to need. Draw the
3355 if (ds->grid[y*w+x] != flags ||
3356 ds->dx[y*w+x] != ddx ||
3357 ds->dy[y*w+x] != ddy) {
3358 draw_square(dr, ds, x, y, flags, ddx, ddy);
3359 ds->grid[y*w+x] = flags;
3360 ds->dx[y*w+x] = ddx;
3361 ds->dy[y*w+x] = ddy;
3366 * Draw a cursor. This secondary blitter is much less invasive than trying
3367 * to fix up all of the rest of the code with sufficient flags to be able to
3368 * display this sensibly.
3370 if (ui->cur_visible) {
3371 space *sp = &SPACE(state, ui->cur_x, ui->cur_y);
3372 ds->cur_visible = TRUE;
3373 ds->cx = SCOORD(ui->cur_x) - CURSOR_SIZE;
3374 ds->cy = SCOORD(ui->cur_y) - CURSOR_SIZE;
3375 blitter_save(dr, ds->cur_bl, ds->cx, ds->cy);
3376 if (sp->flags & F_DOT) {
3377 /* draw a red dot (over the top of whatever would be there already) */
3378 draw_circle(dr, SCOORD(ui->cur_x), SCOORD(ui->cur_y), DOT_SIZE,
3379 COL_CURSOR, COL_BLACKDOT);
3380 } else if (sp->type != s_tile) {
3381 /* draw an edge/vertex square; tile cursors are dealt with above. */
3382 int dx = (ui->cur_x % 2) ? CURSOR_SIZE : CURSOR_SIZE/3;
3383 int dy = (ui->cur_y % 2) ? CURSOR_SIZE : CURSOR_SIZE/3;
3384 int x1 = SCOORD(ui->cur_x)-dx, y1 = SCOORD(ui->cur_y)-dy;
3385 int xs = dx*2+1, ys = dy*2+1;
3387 draw_rect(dr, x1, y1, xs, ys, COL_CURSOR);
3389 draw_update(dr, ds->cx, ds->cy, CURSOR_SIZE*2+1, CURSOR_SIZE*2+1);
3393 ds->dragging = TRUE;
3394 ds->dragx = ui->dx - TILE_SIZE/2;
3395 ds->dragy = ui->dy - TILE_SIZE/2;
3396 calculate_opposite_point(ui, ds, ui->dx, ui->dy, &oppx, &oppy);
3397 blitter_save(dr, ds->bl, ds->dragx, ds->dragy);
3398 blitter_save(dr, ds->blmirror, oppx - TILE_SIZE/2, oppy - TILE_SIZE/2);
3399 draw_arrow(dr, ds, ui->dx, ui->dy, SCOORD(ui->dotx) - ui->dx,
3400 SCOORD(ui->doty) - ui->dy, COL_ARROW);
3401 draw_arrow(dr, ds, oppx, oppy, SCOORD(ui->dotx) - oppx,
3402 SCOORD(ui->doty) - oppy, COL_ARROW);
3407 if (state->cdiff != -1)
3408 sprintf(buf, "Puzzle is %s.", galaxies_diffnames[state->cdiff]);
3411 status_bar(dr, buf);
3416 static float game_anim_length(const game_state *oldstate,
3417 const game_state *newstate, int dir, game_ui *ui)
3422 static float game_flash_length(const game_state *oldstate,
3423 const game_state *newstate, int dir, game_ui *ui)
3425 if ((!oldstate->completed && newstate->completed) &&
3426 !(newstate->used_solve))
3427 return 3 * FLASH_TIME;
3432 static int game_status(const game_state *state)
3434 return state->completed ? +1 : 0;
3437 static int game_timing_state(const game_state *state, game_ui *ui)
3443 static void game_print_size(const game_params *params, float *x, float *y)
3448 * 8mm squares by default. (There isn't all that much detail
3449 * that needs to go in each square.)
3451 game_compute_size(params, 800, &pw, &ph);
3456 static void game_print(drawing *dr, const game_state *state, int sz)
3458 int w = state->w, h = state->h;
3459 int white, black, blackish;
3463 int ncoords = 0, coordsize = 0;
3465 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3466 game_drawstate ads, *ds = &ads;
3469 white = print_mono_colour(dr, 1);
3470 black = print_mono_colour(dr, 0);
3471 blackish = print_hatched_colour(dr, HATCH_X);
3474 * Get the completion information.
3476 dsf = snewn(w * h, int);
3477 colours = snewn(w * h, int);
3478 check_complete(state, dsf, colours);
3483 print_line_width(dr, TILE_SIZE / 64);
3484 for (x = 1; x < w; x++)
3485 draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h), black);
3486 for (y = 1; y < h; y++)
3487 draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y), black);
3490 * Shade the completed regions. Just in case any particular
3491 * printing platform deals badly with adjacent
3492 * similarly-hatched regions, we'll fill each one as a single
3495 for (i = 0; i < w*h; i++) {
3496 j = dsf_canonify(dsf, i);
3497 if (colours[j] != 0) {
3501 * This is the first square we've run into belonging to
3502 * this polyomino, which means an edge of the polyomino
3503 * is certain to be to our left. (After we finish
3504 * tracing round it, we'll set the colours[] entry to
3505 * zero to prevent accidentally doing it again.)
3515 * We are currently sitting on square (x,y), which
3516 * we know to be in our polyomino, and we also know
3517 * that (x+dx,y+dy) is not. The way I visualise
3518 * this is that we're standing to the right of a
3519 * boundary line, stretching our left arm out to
3520 * point to the exterior square on the far side.
3524 * First, check if we've gone round the entire
3528 (x == i%w && y == i/w && dx == -1 && dy == 0))
3532 * Add to our coordinate list the coordinate
3533 * backwards and to the left of where we are.
3535 if (ncoords + 2 > coordsize) {
3536 coordsize = (ncoords * 3 / 2) + 64;
3537 coords = sresize(coords, coordsize, int);
3539 coords[ncoords++] = COORD((2*x+1 + dx + dy) / 2);
3540 coords[ncoords++] = COORD((2*y+1 + dy - dx) / 2);
3543 * Follow the edge round. If the square directly in
3544 * front of us is not part of the polyomino, we
3545 * turn right; if it is and so is the square in
3546 * front of (x+dx,y+dy), we turn left; otherwise we
3549 if (x-dy < 0 || x-dy >= w || y+dx < 0 || y+dx >= h ||
3550 dsf_canonify(dsf, (y+dx)*w+(x-dy)) != j) {
3555 } else if (x+dx-dy >= 0 && x+dx-dy < w &&
3556 y+dy+dx >= 0 && y+dy+dx < h &&
3557 dsf_canonify(dsf, (y+dy+dx)*w+(x+dx-dy)) == j) {
3574 * Now we have our polygon complete, so fill it.
3576 draw_polygon(dr, coords, ncoords/2,
3577 colours[j] == 2 ? blackish : -1, black);
3580 * And mark this polyomino as done.
3589 for (y = 0; y <= h; y++)
3590 for (x = 0; x <= w; x++) {
3591 if (x < w && SPACE(state, x*2+1, y*2).flags & F_EDGE_SET)
3592 draw_rect(dr, COORD(x)-EDGE_THICKNESS, COORD(y)-EDGE_THICKNESS,
3593 EDGE_THICKNESS * 2 + TILE_SIZE, EDGE_THICKNESS * 2,
3595 if (y < h && SPACE(state, x*2, y*2+1).flags & F_EDGE_SET)
3596 draw_rect(dr, COORD(x)-EDGE_THICKNESS, COORD(y)-EDGE_THICKNESS,
3597 EDGE_THICKNESS * 2, EDGE_THICKNESS * 2 + TILE_SIZE,
3604 for (y = 0; y <= 2*h; y++)
3605 for (x = 0; x <= 2*w; x++)
3606 if (SPACE(state, x, y).flags & F_DOT) {
3607 draw_circle(dr, (int)COORD(x/2.0), (int)COORD(y/2.0), DOT_SIZE,
3608 (SPACE(state, x, y).flags & F_DOT_BLACK ?
3609 black : white), black);
3619 #define thegame galaxies
3622 const struct game thegame = {
3623 "Galaxies", "games.galaxies", "galaxies",
3630 TRUE, game_configure, custom_params,
3642 TRUE, game_can_format_as_text_now, game_text_format,
3650 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3653 game_free_drawstate,
3659 FALSE, FALSE, NULL, NULL,
3660 TRUE, /* wants_statusbar */
3662 TRUE, FALSE, game_print_size, game_print,
3663 FALSE, /* wants_statusbar */
3665 FALSE, game_timing_state,
3666 REQUIRE_RBUTTON, /* flags */
3669 #ifdef STANDALONE_SOLVER
3675 static void usage_exit(const char *msg)
3678 fprintf(stderr, "%s: %s\n", quis, msg);
3679 fprintf(stderr, "Usage: %s [--seed SEED] --soak <params> | [game_id [game_id ...]]\n", quis);
3683 static void dump_state(game_state *state)
3685 char *temp = game_text_format(state);
3686 printf("%s\n", temp);
3690 static int gen(game_params *p, random_state *rs, int debug)
3697 solver_show_working = debug;
3699 printf("Generating a %dx%d %s puzzle.\n",
3700 p->w, p->h, galaxies_diffnames[p->diff]);
3702 desc = new_game_desc(p, rs, NULL, 0);
3703 state = new_game(NULL, p, desc);
3706 diff = solver_state(state, DIFF_UNREASONABLE);
3707 printf("Generated %s game %dx%d:%s\n",
3708 galaxies_diffnames[diff], p->w, p->h, desc);
3717 static void soak(game_params *p, random_state *rs)
3719 time_t tt_start, tt_now, tt_last;
3722 int diff, n = 0, i, diffs[DIFF_MAX], ndots = 0, nspaces = 0;
3725 solver_show_working = 0;
3727 tt_start = tt_now = time(NULL);
3728 for (i = 0; i < DIFF_MAX; i++) diffs[i] = 0;
3731 printf("Soak-generating a %dx%d grid, max. diff %s.\n",
3732 p->w, p->h, galaxies_diffnames[p->diff]);
3734 for (i = 0; i < DIFF_MAX; i++)
3735 printf("%s%s", (i == 0) ? "" : ", ", galaxies_diffnames[i]);
3739 desc = new_game_desc(p, rs, NULL, 0);
3740 st = new_game(NULL, p, desc);
3741 diff = solver_state(st, p->diff);
3742 nspaces += st->w*st->h;
3743 for (i = 0; i < st->sx*st->sy; i++)
3744 if (st->grid[i].flags & F_DOT) ndots++;
3750 tt_last = time(NULL);
3751 if (tt_last > tt_now) {
3753 printf("%d total, %3.1f/s, [",
3754 n, (double)n / ((double)tt_now - tt_start));
3755 for (i = 0; i < DIFF_MAX; i++)
3756 printf("%s%.1f%%", (i == 0) ? "" : ", ",
3757 100.0 * ((double)diffs[i] / (double)n));
3758 printf("], %.1f%% dots\n",
3759 100.0 * ((double)ndots / (double)nspaces));
3764 int main(int argc, char **argv)
3767 char *id = NULL, *desc, *err;
3769 int diff, do_soak = 0, verbose = 0;
3771 time_t seed = time(NULL);
3774 while (--argc > 0) {
3776 if (!strcmp(p, "-v")) {
3778 } else if (!strcmp(p, "--seed")) {
3779 if (argc == 0) usage_exit("--seed needs an argument");
3780 seed = (time_t)atoi(*++argv);
3782 } else if (!strcmp(p, "--soak")) {
3784 } else if (*p == '-') {
3785 usage_exit("unrecognised option");
3793 p = default_params();
3794 rs = random_new((void*)&seed, sizeof(time_t));
3797 if (!id) usage_exit("need one argument for --soak");
3798 decode_params(p, *argv);
3805 p->w = random_upto(rs, 15) + 3;
3806 p->h = random_upto(rs, 15) + 3;
3807 p->diff = random_upto(rs, DIFF_UNREASONABLE);
3808 diff = gen(p, rs, 0);
3813 desc = strchr(id, ':');
3815 decode_params(p, id);
3816 gen(p, rs, verbose);
3819 solver_show_working = 1;
3822 decode_params(p, id);
3823 err = validate_desc(p, desc);
3825 fprintf(stderr, "%s: %s\n", argv[0], err);
3828 s = new_game(NULL, p, desc);
3829 diff = solver_state(s, DIFF_UNREASONABLE);
3831 printf("Puzzle is %s.\n", galaxies_diffnames[diff]);
3842 #ifdef STANDALONE_PICTURE_GENERATOR
3845 * Main program for the standalone picture generator. To use it,
3846 * simply provide it with an XBM-format bitmap file (note XBM, not
3847 * XPM) on standard input, and it will output a game ID in return.
3850 * $ ./galaxiespicture < badly-drawn-cat.xbm
3851 * 11x11:eloMBLzFeEzLNMWifhaWYdDbixCymBbBMLoDdewGg
3853 * If you want a puzzle with a non-standard difficulty level, pass
3854 * a partial parameters string as a command-line argument (e.g.
3855 * `./galaxiespicture du < foo.xbm', where `du' is the same suffix
3856 * which if it appeared in a random-seed game ID would set the
3857 * difficulty level to Unreasonable). However, be aware that if the
3858 * generator fails to produce an adequately difficult puzzle too
3859 * many times then it will give up and return an easier one (just
3860 * as it does during normal GUI play). To be sure you really have
3861 * the difficulty you asked for, use galaxiessolver to
3864 * (Perhaps I ought to include an option to make this standalone
3865 * generator carry on looping until it really does get the right
3866 * difficulty. Hmmm.)
3871 int main(int argc, char **argv)
3874 char *params, *desc;
3876 time_t seed = time(NULL);
3881 par = default_params();
3883 decode_params(par, argv[1]); /* get difficulty */
3884 par->w = par->h = -1;
3887 * Now read an XBM file from standard input. This is simple and
3888 * hacky and will do very little error detection, so don't feed
3893 while (fgets(buf, sizeof(buf), stdin)) {
3894 buf[strcspn(buf, "\r\n")] = '\0';
3895 if (!strncmp(buf, "#define", 7)) {
3897 * Lines starting `#define' give the width and height.
3899 char *num = buf + strlen(buf);
3902 while (num > buf && isdigit((unsigned char)num[-1]))
3905 while (symend > buf && isspace((unsigned char)symend[-1]))
3908 if (symend-5 >= buf && !strncmp(symend-5, "width", 5))
3910 else if (symend-6 >= buf && !strncmp(symend-6, "height", 6))
3914 * Otherwise, break the string up into words and take
3915 * any word of the form `0x' plus hex digits to be a
3918 char *p, *wordstart;
3921 if (par->w < 0 || par->h < 0) {
3922 printf("failed to read width and height\n");
3925 picture = snewn(par->w * par->h, int);
3926 for (i = 0; i < par->w * par->h; i++)
3932 while (*p && (*p == ',' || isspace((unsigned char)*p)))
3935 while (*p && !(*p == ',' || *p == '}' ||
3936 isspace((unsigned char)*p)))
3941 if (wordstart[0] == '0' &&
3942 (wordstart[1] == 'x' || wordstart[1] == 'X') &&
3943 !wordstart[2 + strspn(wordstart+2,
3944 "0123456789abcdefABCDEF")]) {
3945 unsigned long byte = strtoul(wordstart+2, NULL, 16);
3946 for (i = 0; i < 8; i++) {
3947 int bit = (byte >> i) & 1;
3948 if (y < par->h && x < par->w)
3949 picture[y * par->w + x] = bit;
3962 for (i = 0; i < par->w * par->h; i++)
3963 if (picture[i] < 0) {
3964 fprintf(stderr, "failed to read enough bitmap data\n");
3968 rs = random_new((void*)&seed, sizeof(time_t));
3970 desc = new_game_desc(par, rs, NULL, FALSE);
3971 params = encode_params(par, FALSE);
3972 printf("%s:%s\n", params, desc);
3984 /* vim: set shiftwidth=4 tabstop=8: */