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 /* ----------------------------------------------------------
152 * Game parameters and presets
155 /* make up some sensible default sizes */
157 #define DEFAULT_PRESET 0
159 static const game_params galaxies_presets[] = {
160 { 7, 7, DIFF_NORMAL },
161 { 7, 7, DIFF_UNREASONABLE },
162 { 10, 10, DIFF_NORMAL },
163 { 15, 15, DIFF_NORMAL },
166 static int game_fetch_preset(int i, char **name, game_params **params)
171 if (i < 0 || i >= lenof(galaxies_presets))
174 ret = snew(game_params);
175 *ret = galaxies_presets[i]; /* structure copy */
177 sprintf(buf, "%dx%d %s", ret->w, ret->h,
178 galaxies_diffnames[ret->diff]);
180 if (name) *name = dupstr(buf);
185 static game_params *default_params(void)
188 game_fetch_preset(DEFAULT_PRESET, NULL, &ret);
192 static void free_params(game_params *params)
197 static game_params *dup_params(const game_params *params)
199 game_params *ret = snew(game_params);
200 *ret = *params; /* structure copy */
204 static void decode_params(game_params *params, char const *string)
206 params->h = params->w = atoi(string);
207 params->diff = DIFF_NORMAL;
208 while (*string && isdigit((unsigned char)*string)) string++;
209 if (*string == 'x') {
211 params->h = atoi(string);
212 while (*string && isdigit((unsigned char)*string)) string++;
214 if (*string == 'd') {
217 for (i = 0; i <= DIFF_UNREASONABLE; i++)
218 if (*string == galaxies_diffchars[i])
220 if (*string) string++;
224 static char *encode_params(const game_params *params, int full)
227 sprintf(str, "%dx%d", params->w, params->h);
229 sprintf(str + strlen(str), "d%c", galaxies_diffchars[params->diff]);
233 static config_item *game_configure(const game_params *params)
238 ret = snewn(4, config_item);
240 ret[0].name = "Width";
241 ret[0].type = C_STRING;
242 sprintf(buf, "%d", params->w);
243 ret[0].sval = dupstr(buf);
246 ret[1].name = "Height";
247 ret[1].type = C_STRING;
248 sprintf(buf, "%d", params->h);
249 ret[1].sval = dupstr(buf);
252 ret[2].name = "Difficulty";
253 ret[2].type = C_CHOICES;
254 ret[2].sval = DIFFCONFIG;
255 ret[2].ival = params->diff;
265 static game_params *custom_params(const config_item *cfg)
267 game_params *ret = snew(game_params);
269 ret->w = atoi(cfg[0].sval);
270 ret->h = atoi(cfg[1].sval);
271 ret->diff = cfg[2].ival;
276 static char *validate_params(const game_params *params, int full)
278 if (params->w < 3 || params->h < 3)
279 return "Width and height must both be at least 3";
281 * This shouldn't be able to happen at all, since decode_params
282 * and custom_params will never generate anything that isn't
285 assert(params->diff <= DIFF_UNREASONABLE);
290 /* ----------------------------------------------------------
291 * Game utility functions.
294 static void add_dot(space *space) {
295 assert(!(space->flags & F_DOT));
296 space->flags |= F_DOT;
300 static void remove_dot(space *space) {
301 assert(space->flags & F_DOT);
302 space->flags &= ~F_DOT;
305 static void remove_assoc(const game_state *state, space *tile) {
306 if (tile->flags & F_TILE_ASSOC) {
307 SPACE(state, tile->dotx, tile->doty).nassoc--;
308 tile->flags &= ~F_TILE_ASSOC;
314 static void add_assoc(const game_state *state, space *tile, space *dot) {
315 remove_assoc(state, tile);
317 #ifdef STANDALONE_PICTURE_GENERATOR
319 assert(!picture[(tile->y/2) * state->w + (tile->x/2)] ==
320 !(dot->flags & F_DOT_BLACK));
322 tile->flags |= F_TILE_ASSOC;
326 /*debug(("add_assoc sp %d %d --> dot %d,%d, new nassoc %d.\n",
327 tile->x, tile->y, dot->x, dot->y, dot->nassoc));*/
330 static space *sp2dot(const game_state *state, int x, int y)
332 space *sp = &SPACE(state, x, y);
333 if (!(sp->flags & F_TILE_ASSOC)) return NULL;
334 return &SPACE(state, sp->dotx, sp->doty);
337 #define IS_VERTICAL_EDGE(x) ((x % 2) == 0)
339 static int game_can_format_as_text_now(const game_params *params)
344 static char *game_text_format(const game_state *state)
346 int maxlen = (state->sx+1)*state->sy, x, y;
350 ret = snewn(maxlen+1, char);
353 for (y = 0; y < state->sy; y++) {
354 for (x = 0; x < state->sx; x++) {
355 sp = &SPACE(state, x, y);
356 if (sp->flags & F_DOT)
359 else if (sp->flags & (F_REACHABLE|F_MULTIPLE|F_MARK))
360 *p++ = (sp->flags & F_MULTIPLE) ? 'M' :
361 (sp->flags & F_REACHABLE) ? 'R' : 'X';
366 if (sp->flags & F_TILE_ASSOC) {
367 space *dot = sp2dot(state, sp->x, sp->y);
368 if (dot && dot->flags & F_DOT)
369 *p++ = (dot->flags & F_DOT_BLACK) ? 'B' : 'W';
371 *p++ = '?'; /* association with not-a-dot. */
381 if (sp->flags & F_EDGE_SET)
382 *p++ = (IS_VERTICAL_EDGE(x)) ? '|' : '-';
388 assert(!"shouldn't get here!");
395 assert(p - ret == maxlen);
401 static void dbg_state(const game_state *state)
404 char *temp = game_text_format(state);
405 debug(("%s\n", temp));
410 /* Space-enumeration callbacks should all return 1 for 'progress made',
411 * -1 for 'impossible', and 0 otherwise. */
412 typedef int (*space_cb)(game_state *state, space *sp, void *ctx);
414 #define IMPOSSIBLE_QUITS 1
416 static int foreach_sub(game_state *state, space_cb cb, unsigned int f,
417 void *ctx, int startx, int starty)
419 int x, y, progress = 0, impossible = 0, ret;
422 for (y = starty; y < state->sy; y += 2) {
423 sp = &SPACE(state, startx, y);
424 for (x = startx; x < state->sx; x += 2) {
425 ret = cb(state, sp, ctx);
427 if (f & IMPOSSIBLE_QUITS) return -1;
429 } else if (ret == 1) {
435 return impossible ? -1 : progress;
438 static int foreach_tile(game_state *state, space_cb cb, unsigned int f,
441 return foreach_sub(state, cb, f, ctx, 1, 1);
444 static int foreach_edge(game_state *state, space_cb cb, unsigned int f,
449 ret1 = foreach_sub(state, cb, f, ctx, 0, 1);
450 ret2 = foreach_sub(state, cb, f, ctx, 1, 0);
452 if (ret1 == -1 || ret2 == -1) return -1;
453 return (ret1 || ret2) ? 1 : 0;
457 static int foreach_vertex(game_state *state, space_cb cb, unsigned int f,
460 return foreach_sub(state, cb, f, ctx, 0, 0);
465 static int is_same_assoc(game_state *state,
466 int x1, int y1, int x2, int y2)
470 if (!INGRID(state, x1, y1) || !INGRID(state, x2, y2))
473 s1 = &SPACE(state, x1, y1);
474 s2 = &SPACE(state, x2, y2);
475 assert(s1->type == s_tile && s2->type == s_tile);
476 if ((s1->flags & F_TILE_ASSOC) && (s2->flags & F_TILE_ASSOC) &&
477 s1->dotx == s2->dotx && s1->doty == s2->doty)
479 return 0; /* 0 if not same or not both associated. */
484 static int edges_into_vertex(game_state *state,
487 int dx, dy, nx, ny, count = 0;
489 assert(SPACE(state, x, y).type == s_vertex);
490 for (dx = -1; dx <= 1; dx++) {
491 for (dy = -1; dy <= 1; dy++) {
492 if (dx != 0 && dy != 0) continue;
493 if (dx == 0 && dy == 0) continue;
495 nx = x+dx; ny = y+dy;
496 if (!INGRID(state, nx, ny)) continue;
497 assert(SPACE(state, nx, ny).type == s_edge);
498 if (SPACE(state, nx, ny).flags & F_EDGE_SET)
506 static space *space_opposite_dot(game_state *state, space *sp, space *dot)
515 if (!INGRID(state, tx, ty)) return NULL;
517 sp2 = &SPACE(state, tx, ty);
518 assert(sp2->type == sp->type);
522 static space *tile_opposite(game_state *state, space *sp)
526 assert(sp->flags & F_TILE_ASSOC);
527 dot = &SPACE(state, sp->dotx, sp->doty);
528 return space_opposite_dot(state, sp, dot);
531 static int dotfortile(game_state *state, space *tile, space *dot)
533 space *tile_opp = space_opposite_dot(state, tile, dot);
535 if (!tile_opp) return 0; /* opposite would be off grid */
536 if (tile_opp->flags & F_TILE_ASSOC &&
537 (tile_opp->dotx != dot->x || tile_opp->doty != dot->y))
538 return 0; /* opposite already associated with diff. dot */
542 static void adjacencies(game_state *state, space *sp, space **a1s, space **a2s)
544 int dxs[4] = {-1, 1, 0, 0}, dys[4] = {0, 0, -1, 1};
547 /* this function needs optimising. */
549 for (n = 0; n < 4; n++) {
553 if (INGRID(state, x, y)) {
554 a1s[n] = &SPACE(state, x, y);
556 x += dxs[n]; y += dys[n];
558 if (INGRID(state, x, y))
559 a2s[n] = &SPACE(state, x, y);
563 a1s[n] = a2s[n] = NULL;
568 static int outline_tile_fordot(game_state *state, space *tile, int mark)
570 space *tadj[4], *eadj[4];
571 int i, didsth = 0, edge, same;
573 assert(tile->type == s_tile);
574 adjacencies(state, tile, eadj, tadj);
575 for (i = 0; i < 4; i++) {
576 if (!eadj[i]) continue;
578 edge = (eadj[i]->flags & F_EDGE_SET) ? 1 : 0;
580 if (!(tile->flags & F_TILE_ASSOC))
581 same = (tadj[i]->flags & F_TILE_ASSOC) ? 0 : 1;
583 same = ((tadj[i]->flags & F_TILE_ASSOC) &&
584 tile->dotx == tadj[i]->dotx &&
585 tile->doty == tadj[i]->doty) ? 1 : 0;
589 if (!edge && !same) {
590 if (mark) eadj[i]->flags |= F_EDGE_SET;
592 } else if (edge && same) {
593 if (mark) eadj[i]->flags &= ~F_EDGE_SET;
600 static void tiles_from_edge(game_state *state, space *sp, space **ts)
604 if (IS_VERTICAL_EDGE(sp->x)) {
605 xs[0] = sp->x-1; ys[0] = sp->y;
606 xs[1] = sp->x+1; ys[1] = sp->y;
608 xs[0] = sp->x; ys[0] = sp->y-1;
609 xs[1] = sp->x; ys[1] = sp->y+1;
611 ts[0] = INGRID(state, xs[0], ys[0]) ? &SPACE(state, xs[0], ys[0]) : NULL;
612 ts[1] = INGRID(state, xs[1], ys[1]) ? &SPACE(state, xs[1], ys[1]) : NULL;
615 /* Returns a move string for use by 'solve', including the initial
616 * 'S' if issolve is true. */
617 static char *diff_game(const game_state *src, const game_state *dest,
620 int movelen = 0, movesize = 256, x, y, len;
621 char *move = snewn(movesize, char), buf[80], *sep = "";
622 char achar = issolve ? 'a' : 'A';
625 assert(src->sx == dest->sx && src->sy == dest->sy);
628 move[movelen++] = 'S';
631 move[movelen] = '\0';
632 for (x = 0; x < src->sx; x++) {
633 for (y = 0; y < src->sy; y++) {
634 sps = &SPACE(src, x, y);
635 spd = &SPACE(dest, x, y);
637 assert(sps->type == spd->type);
640 if (sps->type == s_tile) {
641 if ((sps->flags & F_TILE_ASSOC) &&
642 (spd->flags & F_TILE_ASSOC)) {
643 if (sps->dotx != spd->dotx ||
644 sps->doty != spd->doty)
645 /* Both associated; change association, if different */
646 len = sprintf(buf, "%s%c%d,%d,%d,%d", sep,
647 (int)achar, x, y, spd->dotx, spd->doty);
648 } else if (sps->flags & F_TILE_ASSOC)
649 /* Only src associated; remove. */
650 len = sprintf(buf, "%sU%d,%d", sep, x, y);
651 else if (spd->flags & F_TILE_ASSOC)
652 /* Only dest associated; add. */
653 len = sprintf(buf, "%s%c%d,%d,%d,%d", sep,
654 (int)achar, x, y, spd->dotx, spd->doty);
655 } else if (sps->type == s_edge) {
656 if ((sps->flags & F_EDGE_SET) != (spd->flags & F_EDGE_SET))
657 /* edge flags are different; flip them. */
658 len = sprintf(buf, "%sE%d,%d", sep, x, y);
661 if (movelen + len >= movesize) {
662 movesize = movelen + len + 256;
663 move = sresize(move, movesize, char);
665 strcpy(move + movelen, buf);
671 debug(("diff_game src then dest:\n"));
674 debug(("diff string %s\n", move));
678 /* Returns 1 if a dot here would not be too close to any other dots
679 * (and would avoid other game furniture). */
680 static int dot_is_possible(game_state *state, space *sp, int allow_assoc)
682 int bx = 0, by = 0, dx, dy;
684 #ifdef STANDALONE_PICTURE_GENERATOR
692 if (IS_VERTICAL_EDGE(sp->x)) {
702 for (dx = -bx; dx <= bx; dx++) {
703 for (dy = -by; dy <= by; dy++) {
704 if (!INGRID(state, sp->x+dx, sp->y+dy)) continue;
706 adj = &SPACE(state, sp->x+dx, sp->y+dy);
708 #ifdef STANDALONE_PICTURE_GENERATOR
710 * Check that all the squares we're looking at have the
714 if (adj->type == s_tile) {
715 int c = picture[(adj->y / 2) * state->w + (adj->x / 2)];
719 return 0; /* colour mismatch */
724 if (!allow_assoc && (adj->flags & F_TILE_ASSOC))
727 if (dx != 0 || dy != 0) {
728 /* Other than our own square, no dots nearby. */
729 if (adj->flags & (F_DOT))
733 /* We don't want edges within our rectangle
734 * (but don't care about edges on the edge) */
735 if (abs(dx) < bx && abs(dy) < by &&
736 adj->flags & F_EDGE_SET)
743 /* ----------------------------------------------------------
744 * Game generation, structure creation, and descriptions.
747 static game_state *blank_game(int w, int h)
749 game_state *state = snew(game_state);
757 state->grid = snewn(state->sx * state->sy, space);
758 state->completed = state->used_solve = 0;
760 for (x = 0; x < state->sx; x++) {
761 for (y = 0; y < state->sy; y++) {
762 space *sp = &SPACE(state, x, y);
763 memset(sp, 0, sizeof(space));
766 if ((x % 2) == 0 && (y % 2) == 0)
768 else if ((x % 2) == 0 || (y % 2) == 0) {
770 if (x == 0 || y == 0 || x == state->sx-1 || y == state->sy-1)
771 sp->flags |= F_EDGE_SET;
780 state->me = NULL; /* filled in by new_game. */
786 static void game_update_dots(game_state *state)
788 int i, n, sz = state->sx * state->sy;
790 if (state->dots) sfree(state->dots);
793 for (i = 0; i < sz; i++) {
794 if (state->grid[i].flags & F_DOT) state->ndots++;
796 state->dots = snewn(state->ndots, space *);
798 for (i = 0; i < sz; i++) {
799 if (state->grid[i].flags & F_DOT)
800 state->dots[n++] = &state->grid[i];
804 static void clear_game(game_state *state, int cleardots)
808 /* don't erase edge flags around outline! */
809 for (x = 1; x < state->sx-1; x++) {
810 for (y = 1; y < state->sy-1; y++) {
812 SPACE(state, x, y).flags = 0;
814 SPACE(state, x, y).flags &= (F_DOT|F_DOT_BLACK);
817 if (cleardots) game_update_dots(state);
820 static game_state *dup_game(const game_state *state)
822 game_state *ret = blank_game(state->w, state->h);
824 ret->completed = state->completed;
825 ret->used_solve = state->used_solve;
827 memcpy(ret->grid, state->grid,
828 ret->sx*ret->sy*sizeof(space));
830 game_update_dots(ret);
833 ret->cdiff = state->cdiff;
838 static void free_game(game_state *state)
840 if (state->dots) sfree(state->dots);
845 /* Game description is a sequence of letters representing the number
846 * of spaces (a = 0, y = 24) before the next dot; a-y for a white dot,
847 * and A-Y for a black dot. 'z' is 25 spaces (and no dot).
849 * I know it's a bitch to generate by hand, so we provide
853 static char *encode_game(game_state *state)
859 area = (state->sx-2) * (state->sy-2);
861 desc = snewn(area, char);
864 for (y = 1; y < state->sy-1; y++) {
865 for (x = 1; x < state->sx-1; x++) {
866 f = SPACE(state, x, y).flags;
868 /* a/A is 0 spaces between, b/B is 1 space, ...
869 * y/Y is 24 spaces, za/zA is 25 spaces, ...
870 * It's easier to count from 0 because we then
871 * don't have to special-case the top left-hand corner
872 * (which could be a dot with 0 spaces before it). */
880 *p++ = ((f & F_DOT_BLACK) ? 'A' : 'a') + run;
885 assert(p - desc < area);
887 desc = sresize(desc, p - desc, char);
894 space *olddot, *newdot;
897 enum { MD_CHECK, MD_MOVE };
899 static int movedot_cb(game_state *state, space *tile, void *vctx)
901 struct movedot *md = (struct movedot *)vctx;
902 space *newopp = NULL;
904 assert(tile->type == s_tile);
905 assert(md->olddot && md->newdot);
907 if (!(tile->flags & F_TILE_ASSOC)) return 0;
908 if (tile->dotx != md->olddot->x || tile->doty != md->olddot->y)
911 newopp = space_opposite_dot(state, tile, md->newdot);
915 /* If the tile is associated with the old dot, check its
916 * opposite wrt the _new_ dot is empty or same assoc. */
917 if (!newopp) return -1; /* no new opposite */
918 if (newopp->flags & F_TILE_ASSOC) {
919 if (newopp->dotx != md->olddot->x ||
920 newopp->doty != md->olddot->y)
921 return -1; /* associated, but wrong dot. */
923 #ifdef STANDALONE_PICTURE_GENERATOR
926 * Reject if either tile and the dot don't match in colour.
928 if (!(picture[(tile->y/2) * state->w + (tile->x/2)]) ^
929 !(md->newdot->flags & F_DOT_BLACK))
931 if (!(picture[(newopp->y/2) * state->w + (newopp->x/2)]) ^
932 !(md->newdot->flags & F_DOT_BLACK))
939 /* Move dot associations: anything that was associated
940 * with the old dot, and its opposite wrt the new dot,
941 * become associated with the new dot. */
943 debug(("Associating %d,%d and %d,%d with new dot %d,%d.\n",
944 tile->x, tile->y, newopp->x, newopp->y,
945 md->newdot->x, md->newdot->y));
946 add_assoc(state, tile, md->newdot);
947 add_assoc(state, newopp, md->newdot);
948 return 1; /* we did something! */
953 /* For the given dot, first see if we could expand it into all the given
954 * extra spaces (by checking for empty spaces on the far side), and then
955 * see if we can move the dot to shift the CoG to include the new spaces.
957 static int dot_expand_or_move(game_state *state, space *dot,
958 space **toadd, int nadd)
961 int i, ret, nnew, cx, cy;
964 debug(("dot_expand_or_move: %d tiles for dot %d,%d\n",
965 nadd, dot->x, dot->y));
966 for (i = 0; i < nadd; i++)
967 debug(("dot_expand_or_move: dot %d,%d\n",
968 toadd[i]->x, toadd[i]->y));
969 assert(dot->flags & F_DOT);
971 #ifdef STANDALONE_PICTURE_GENERATOR
974 * Reject the expansion totally if any of the new tiles are
977 for (i = 0; i < nadd; i++) {
978 if (!(picture[(toadd[i]->y/2) * state->w + (toadd[i]->x/2)]) ^
979 !(dot->flags & F_DOT_BLACK))
985 /* First off, could we just expand the current dot's tile to cover
986 * the space(s) passed in and their opposites? */
987 for (i = 0; i < nadd; i++) {
988 tileopp = space_opposite_dot(state, toadd[i], dot);
989 if (!tileopp) goto noexpand;
990 if (tileopp->flags & F_TILE_ASSOC) goto noexpand;
991 #ifdef STANDALONE_PICTURE_GENERATOR
994 * The opposite tiles have to be the right colour as well.
996 if (!(picture[(tileopp->y/2) * state->w + (tileopp->x/2)]) ^
997 !(dot->flags & F_DOT_BLACK))
1002 /* OK, all spaces have valid empty opposites: associate spaces and
1003 * opposites with our dot. */
1004 for (i = 0; i < nadd; i++) {
1005 tileopp = space_opposite_dot(state, toadd[i], dot);
1006 add_assoc(state, toadd[i], dot);
1007 add_assoc(state, tileopp, dot);
1008 debug(("Added associations %d,%d and %d,%d --> %d,%d\n",
1009 toadd[i]->x, toadd[i]->y,
1010 tileopp->x, tileopp->y,
1017 /* Otherwise, try to move dot so as to encompass given spaces: */
1018 /* first, calculate the 'centre of gravity' of the new dot. */
1019 nnew = dot->nassoc + nadd; /* number of tiles assoc. with new dot. */
1020 cx = dot->x * dot->nassoc;
1021 cy = dot->y * dot->nassoc;
1022 for (i = 0; i < nadd; i++) {
1026 /* If the CoG isn't a whole number, it's not possible. */
1027 if ((cx % nnew) != 0 || (cy % nnew) != 0) {
1028 debug(("Unable to move dot %d,%d, CoG not whole number.\n",
1032 cx /= nnew; cy /= nnew;
1034 /* Check whether all spaces in the old tile would have a good
1035 * opposite wrt the new dot. */
1037 md.newdot = &SPACE(state, cx, cy);
1039 ret = foreach_tile(state, movedot_cb, IMPOSSIBLE_QUITS, &md);
1041 debug(("Unable to move dot %d,%d, new dot not symmetrical.\n",
1045 /* Also check whether all spaces we're adding would have a good
1046 * opposite wrt the new dot. */
1047 for (i = 0; i < nadd; i++) {
1048 tileopp = space_opposite_dot(state, toadd[i], md.newdot);
1049 if (tileopp && (tileopp->flags & F_TILE_ASSOC) &&
1050 (tileopp->dotx != dot->x || tileopp->doty != dot->y)) {
1054 debug(("Unable to move dot %d,%d, new dot not symmetrical.\n",
1058 #ifdef STANDALONE_PICTURE_GENERATOR
1060 if (!(picture[(tileopp->y/2) * state->w + (tileopp->x/2)]) ^
1061 !(dot->flags & F_DOT_BLACK))
1067 /* If we've got here, we're ok. First, associate all of 'toadd'
1068 * with the _old_ dot (so they'll get fixed up, with their opposites,
1069 * in the next step). */
1070 for (i = 0; i < nadd; i++) {
1071 debug(("Associating to-add %d,%d with old dot %d,%d.\n",
1072 toadd[i]->x, toadd[i]->y, dot->x, dot->y));
1073 add_assoc(state, toadd[i], dot);
1076 /* Finally, move the dot and fix up all the old associations. */
1077 debug(("Moving dot at %d,%d to %d,%d\n",
1078 dot->x, dot->y, md.newdot->x, md.newdot->y));
1080 #ifdef STANDALONE_PICTURE_GENERATOR
1081 int f = dot->flags & F_DOT_BLACK;
1085 #ifdef STANDALONE_PICTURE_GENERATOR
1086 md.newdot->flags |= f;
1091 ret = foreach_tile(state, movedot_cb, 0, &md);
1098 /* Hard-code to a max. of 2x2 squares, for speed (less malloc) */
1100 #define MAX_OUTSIDE 8
1102 #define MAX_TILE_PERC 20
1104 static int generate_try_block(game_state *state, random_state *rs,
1105 int x1, int y1, int x2, int y2)
1107 int x, y, nadd = 0, nout = 0, i, maxsz;
1108 space *sp, *toadd[MAX_TOADD], *outside[MAX_OUTSIDE], *dot;
1110 if (!INGRID(state, x1, y1) || !INGRID(state, x2, y2)) return 0;
1112 /* We limit the maximum size of tiles to be ~2*sqrt(area); so,
1113 * a 5x5 grid shouldn't have anything >10 tiles, a 20x20 grid
1114 * nothing >40 tiles. */
1115 maxsz = (int)sqrt((double)(state->w * state->h)) * 2;
1116 debug(("generate_try_block, maxsz %d\n", maxsz));
1118 /* Make a static list of the spaces; if any space is already
1119 * associated then quit immediately. */
1120 for (x = x1; x <= x2; x += 2) {
1121 for (y = y1; y <= y2; y += 2) {
1122 assert(nadd < MAX_TOADD);
1123 sp = &SPACE(state, x, y);
1124 assert(sp->type == s_tile);
1125 if (sp->flags & F_TILE_ASSOC) return 0;
1130 /* Make a list of the spaces outside of our block, and shuffle it. */
1131 #define OUTSIDE(x, y) do { \
1132 if (INGRID(state, (x), (y))) { \
1133 assert(nout < MAX_OUTSIDE); \
1134 outside[nout++] = &SPACE(state, (x), (y)); \
1137 for (x = x1; x <= x2; x += 2) {
1141 for (y = y1; y <= y2; y += 2) {
1145 shuffle(outside, nout, sizeof(space *), rs);
1147 for (i = 0; i < nout; i++) {
1148 if (!(outside[i]->flags & F_TILE_ASSOC)) continue;
1149 dot = &SPACE(state, outside[i]->dotx, outside[i]->doty);
1150 if (dot->nassoc >= maxsz) {
1151 debug(("Not adding to dot %d,%d, large enough (%d) already.\n",
1152 dot->x, dot->y, dot->nassoc));
1155 if (dot_expand_or_move(state, dot, toadd, nadd)) return 1;
1160 #ifdef STANDALONE_SOLVER
1162 #define MAXTRIES maxtries
1167 static int solver_obvious_dot(game_state *state,space *dot);
1171 static void generate_pass(game_state *state, random_state *rs, int *scratch,
1172 int perc, unsigned int flags)
1174 int sz = state->sx*state->sy, nspc, i, ret;
1176 shuffle(scratch, sz, sizeof(int), rs);
1178 /* This bug took me a, er, little while to track down. On PalmOS,
1179 * which has 16-bit signed ints, puzzles over about 9x9 started
1180 * failing to generate because the nspc calculation would start
1181 * to overflow, causing the dots not to be filled in properly. */
1182 nspc = (int)(((long)perc * (long)sz) / 100L);
1183 debug(("generate_pass: %d%% (%d of %dx%d) squares, flags 0x%x\n",
1184 perc, nspc, state->sx, state->sy, flags));
1186 for (i = 0; i < nspc; i++) {
1187 space *sp = &state->grid[scratch[i]];
1188 int x1 = sp->x, y1 = sp->y, x2 = sp->x, y2 = sp->y;
1190 if (sp->type == s_edge) {
1191 if (IS_VERTICAL_EDGE(sp->x)) {
1197 if (sp->type != s_vertex) {
1198 /* heuristic; expanding from vertices tends to generate lots of
1199 * too-big regions of tiles. */
1200 if (generate_try_block(state, rs, x1, y1, x2, y2))
1201 continue; /* we expanded successfully. */
1204 if (!(flags & GP_DOTS)) continue;
1206 if ((sp->type == s_edge) && (i % 2)) {
1207 debug(("Omitting edge %d,%d as half-of.\n", sp->x, sp->y));
1211 /* If we've got here we might want to put a dot down. Check
1212 * if we can, and add one if so. */
1213 if (dot_is_possible(state, sp, 0)) {
1215 #ifdef STANDALONE_PICTURE_GENERATOR
1217 if (picture[(sp->y/2) * state->w + (sp->x/2)])
1218 sp->flags |= F_DOT_BLACK;
1221 ret = solver_obvious_dot(state, sp);
1223 debug(("Added dot (and obvious associations) at %d,%d\n",
1231 static int check_complete(const game_state *state, int *dsf, int *colours);
1232 static int solver_state(game_state *state, int maxdiff);
1234 static char *new_game_desc(const game_params *params, random_state *rs,
1235 char **aux, int interactive)
1237 game_state *state = blank_game(params->w, params->h), *copy;
1239 int *scratch, sz = state->sx*state->sy, i;
1240 int diff, ntries = 0, cc;
1242 /* Random list of squares to try and process, one-by-one. */
1243 scratch = snewn(sz, int);
1244 for (i = 0; i < sz; i++) scratch[i] = i;
1247 clear_game(state, 1);
1250 /* generate_pass(state, rs, scratch, 10, GP_DOTS); */
1251 /* generate_pass(state, rs, scratch, 100, 0); */
1252 generate_pass(state, rs, scratch, 100, GP_DOTS);
1254 game_update_dots(state);
1258 char *tmp = encode_game(state);
1259 debug(("new_game_desc state %dx%d:%s\n", params->w, params->h, tmp));
1264 for (i = 0; i < state->sx*state->sy; i++)
1265 if (state->grid[i].type == s_tile)
1266 outline_tile_fordot(state, &state->grid[i], TRUE);
1267 cc = check_complete(state, NULL, NULL);
1270 copy = dup_game(state);
1271 clear_game(copy, 0);
1273 diff = solver_state(copy, params->diff);
1276 assert(diff != DIFF_IMPOSSIBLE);
1277 if (diff != params->diff) {
1279 * We'll grudgingly accept a too-easy puzzle, but we must
1280 * _not_ permit a too-hard one (one which the solver
1281 * couldn't handle at all).
1283 if (diff > params->diff ||
1284 ntries < MAXTRIES) goto generate;
1287 #ifdef STANDALONE_PICTURE_GENERATOR
1289 * Postprocessing pass to prevent excessive numbers of adjacent
1290 * singletons. Iterate over all edges in random shuffled order;
1291 * for each edge that separates two regions, investigate
1292 * whether removing that edge and merging the regions would
1293 * still yield a valid and soluble puzzle. (The two regions
1294 * must also be the same colour, of course.) If so, do it.
1296 * This postprocessing pass is slow (due to repeated solver
1297 * invocations), and seems to be unnecessary during normal
1298 * unconstrained game generation. However, when generating a
1299 * game under colour constraints, excessive singletons seem to
1300 * turn up more often, so it's worth doing this.
1307 nposns = params->w * (params->h+1) + params->h * (params->w+1);
1308 posns = snewn(nposns, int);
1309 for (i = j = 0; i < state->sx*state->sy; i++)
1310 if (state->grid[i].type == s_edge)
1312 assert(j == nposns);
1314 shuffle(posns, nposns, sizeof(*posns), rs);
1316 for (i = 0; i < nposns; i++) {
1317 int x, y, x0, y0, x1, y1, cx, cy, cn, cx0, cy0, cx1, cy1, tx, ty;
1318 space *s0, *s1, *ts, *d0, *d1, *dn;
1321 /* Coordinates of edge space */
1322 x = posns[i] % state->sx;
1323 y = posns[i] / state->sx;
1325 /* Coordinates of square spaces on either side of edge */
1326 x0 = ((x+1) & ~1) - 1; /* round down to next odd number */
1327 y0 = ((y+1) & ~1) - 1;
1328 x1 = 2*x-x0; /* and reflect about x to get x1 */
1331 if (!INGRID(state, x0, y0) || !INGRID(state, x1, y1))
1332 continue; /* outermost edge of grid */
1333 s0 = &SPACE(state, x0, y0);
1334 s1 = &SPACE(state, x1, y1);
1335 assert(s0->type == s_tile && s1->type == s_tile);
1337 if (s0->dotx == s1->dotx && s0->doty == s1->doty)
1338 continue; /* tiles _already_ owned by same dot */
1340 d0 = &SPACE(state, s0->dotx, s0->doty);
1341 d1 = &SPACE(state, s1->dotx, s1->doty);
1343 if ((d0->flags ^ d1->flags) & F_DOT_BLACK)
1344 continue; /* different colours: cannot merge */
1347 * Work out where the centre of gravity of the new
1350 cx = d0->nassoc * d0->x + d1->nassoc * d1->x;
1351 cy = d0->nassoc * d0->y + d1->nassoc * d1->y;
1352 cn = d0->nassoc + d1->nassoc;
1353 if (cx % cn || cy % cn)
1354 continue; /* CoG not at integer coordinates */
1357 assert(INUI(state, cx, cy));
1360 * Ensure that the CoG would actually be _in_ the new
1361 * region, by verifying that all its surrounding tiles
1362 * belong to one or other of our two dots.
1364 cx0 = ((cx+1) & ~1) - 1; /* round down to next odd number */
1365 cy0 = ((cy+1) & ~1) - 1;
1366 cx1 = 2*cx-cx0; /* and reflect about cx to get cx1 */
1369 for (ty = cy0; ty <= cy1; ty += 2)
1370 for (tx = cx0; tx <= cx1; tx += 2) {
1371 ts = &SPACE(state, tx, ty);
1372 assert(ts->type == s_tile);
1373 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1374 (ts->dotx != d1->x || ts->doty != d1->y))
1381 * Verify that for every tile in either source region,
1382 * that tile's image in the new CoG is also in one of
1383 * the two source regions.
1385 for (ty = 1; ty < state->sy; ty += 2) {
1386 for (tx = 1; tx < state->sx; tx += 2) {
1389 ts = &SPACE(state, tx, ty);
1390 assert(ts->type == s_tile);
1391 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1392 (ts->dotx != d1->x || ts->doty != d1->y))
1393 continue; /* not part of these tiles anyway */
1396 if (!INGRID(state, tx1, ty1)) {
1400 ts = &SPACE(state, cx+cx-tx, cy+cy-ty);
1401 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1402 (ts->dotx != d1->x || ts->doty != d1->y)) {
1414 * Now we're clear to attempt the merge. We take a copy
1415 * of the game state first, so we can revert it easily
1416 * if the resulting puzzle turns out to have become
1419 copy2 = dup_game(state);
1423 dn = &SPACE(state, cx, cy);
1425 dn->flags |= (d0->flags & F_DOT_BLACK);
1426 for (ty = 1; ty < state->sy; ty += 2) {
1427 for (tx = 1; tx < state->sx; tx += 2) {
1428 ts = &SPACE(state, tx, ty);
1429 assert(ts->type == s_tile);
1430 if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1431 (ts->dotx != d1->x || ts->doty != d1->y))
1432 continue; /* not part of these tiles anyway */
1433 add_assoc(state, ts, dn);
1437 copy = dup_game(state);
1438 clear_game(copy, 0);
1440 newdiff = solver_state(copy, params->diff);
1442 if (diff == newdiff) {
1443 /* Still just as soluble. Let the merge stand. */
1446 /* Became insoluble. Revert. */
1455 desc = encode_game(state);
1456 #ifndef STANDALONE_SOLVER
1457 debug(("new_game_desc generated: \n"));
1467 static int solver_obvious(game_state *state);
1469 static int dots_too_close(game_state *state)
1471 /* Quick-and-dirty check, using half the solver:
1472 * solver_obvious will only fail if the dots are
1473 * too close together, so dot-proximity associations
1475 game_state *tmp = dup_game(state);
1476 int ret = solver_obvious(tmp);
1478 return (ret == -1) ? 1 : 0;
1481 static game_state *load_game(const game_params *params, const char *desc,
1484 game_state *state = blank_game(params->w, params->h);
1496 if (n >= 'a' && n <= 'y') {
1499 } else if (n >= 'A' && n <= 'Y') {
1503 why = "Invalid characters in game description"; goto fail;
1505 /* if we got here we incremented i and have a dot to add. */
1506 y = (i / (state->sx-2)) + 1;
1507 x = (i % (state->sx-2)) + 1;
1508 if (!INUI(state, x, y)) {
1509 why = "Too much data to fit in grid"; goto fail;
1511 add_dot(&SPACE(state, x, y));
1512 SPACE(state, x, y).flags |= df;
1515 game_update_dots(state);
1517 if (dots_too_close(state)) {
1518 why = "Dots too close together"; goto fail;
1525 if (why_r) *why_r = why;
1529 static char *validate_desc(const game_params *params, const char *desc)
1532 game_state *dummy = load_game(params, desc, &why);
1541 static game_state *new_game(midend *me, const game_params *params,
1544 game_state *state = load_game(params, desc, NULL);
1546 assert("Unable to load ?validated game.");
1555 /* ----------------------------------------------------------
1556 * Solver and all its little wizards.
1559 int solver_recurse_depth;
1561 typedef struct solver_ctx {
1563 int sz; /* state->sx * state->sy */
1564 space **scratch; /* size sz */
1568 static solver_ctx *new_solver(game_state *state)
1570 solver_ctx *sctx = snew(solver_ctx);
1571 sctx->state = state;
1572 sctx->sz = state->sx*state->sy;
1573 sctx->scratch = snewn(sctx->sz, space *);
1577 static void free_solver(solver_ctx *sctx)
1579 sfree(sctx->scratch);
1583 /* Solver ideas so far:
1585 * For any empty space, work out how many dots it could associate
1587 * it needs line-of-sight
1588 * it needs an empty space on the far side
1589 * any adjacent lines need corresponding line possibilities.
1592 /* The solver_ctx should keep a list of dot positions, for quicker looping.
1594 * Solver techniques, in order of difficulty:
1595 * obvious adjacency to dots
1596 * transferring tiles to opposite side
1597 * transferring lines to opposite side
1598 * one possible dot for a given tile based on opposite availability
1599 * tile with 3 definite edges next to an associated tile must associate
1602 * one possible dot for a given tile based on line-of-sight
1605 static int solver_add_assoc(game_state *state, space *tile, int dx, int dy,
1608 space *dot, *tile_opp;
1610 dot = &SPACE(state, dx, dy);
1611 tile_opp = space_opposite_dot(state, tile, dot);
1613 assert(tile->type == s_tile);
1614 if (tile->flags & F_TILE_ASSOC) {
1615 if ((tile->dotx != dx) || (tile->doty != dy)) {
1616 solvep(("%*sSet %d,%d --> %d,%d (%s) impossible; "
1617 "already --> %d,%d.\n",
1618 solver_recurse_depth*4, "",
1619 tile->x, tile->y, dx, dy, why,
1620 tile->dotx, tile->doty));
1623 return 0; /* no-op */
1626 solvep(("%*s%d,%d --> %d,%d impossible, no opposite tile.\n",
1627 solver_recurse_depth*4, "", tile->x, tile->y, dx, dy));
1630 if (tile_opp->flags & F_TILE_ASSOC &&
1631 (tile_opp->dotx != dx || tile_opp->doty != dy)) {
1632 solvep(("%*sSet %d,%d --> %d,%d (%s) impossible; "
1633 "opposite already --> %d,%d.\n",
1634 solver_recurse_depth*4, "",
1635 tile->x, tile->y, dx, dy, why,
1636 tile_opp->dotx, tile_opp->doty));
1640 add_assoc(state, tile, dot);
1641 add_assoc(state, tile_opp, dot);
1642 solvep(("%*sSetting %d,%d --> %d,%d (%s).\n",
1643 solver_recurse_depth*4, "",
1644 tile->x, tile->y,dx, dy, why));
1645 solvep(("%*sSetting %d,%d --> %d,%d (%s, opposite).\n",
1646 solver_recurse_depth*4, "",
1647 tile_opp->x, tile_opp->y, dx, dy, why));
1651 static int solver_obvious_dot(game_state *state, space *dot)
1653 int dx, dy, ret, didsth = 0;
1656 debug(("%*ssolver_obvious_dot for %d,%d.\n",
1657 solver_recurse_depth*4, "", dot->x, dot->y));
1659 assert(dot->flags & F_DOT);
1660 for (dx = -1; dx <= 1; dx++) {
1661 for (dy = -1; dy <= 1; dy++) {
1662 if (!INGRID(state, dot->x+dx, dot->y+dy)) continue;
1664 tile = &SPACE(state, dot->x+dx, dot->y+dy);
1665 if (tile->type == s_tile) {
1666 ret = solver_add_assoc(state, tile, dot->x, dot->y,
1668 if (ret < 0) return -1;
1669 if (ret > 0) didsth = 1;
1676 static int solver_obvious(game_state *state)
1678 int i, didsth = 0, ret;
1680 debug(("%*ssolver_obvious.\n", solver_recurse_depth*4, ""));
1682 for (i = 0; i < state->ndots; i++) {
1683 ret = solver_obvious_dot(state, state->dots[i]);
1684 if (ret < 0) return -1;
1685 if (ret > 0) didsth = 1;
1690 static int solver_lines_opposite_cb(game_state *state, space *edge, void *ctx)
1692 int didsth = 0, n, dx, dy;
1693 space *tiles[2], *tile_opp, *edge_opp;
1695 assert(edge->type == s_edge);
1697 tiles_from_edge(state, edge, tiles);
1699 /* if tiles[0] && tiles[1] && they're both associated
1700 * and they're both associated with different dots,
1701 * ensure the line is set. */
1702 if (!(edge->flags & F_EDGE_SET) &&
1703 tiles[0] && tiles[1] &&
1704 (tiles[0]->flags & F_TILE_ASSOC) &&
1705 (tiles[1]->flags & F_TILE_ASSOC) &&
1706 (tiles[0]->dotx != tiles[1]->dotx ||
1707 tiles[0]->doty != tiles[1]->doty)) {
1708 /* No edge, but the two adjacent tiles are both
1709 * associated with different dots; add the edge. */
1710 solvep(("%*sSetting edge %d,%d - tiles different dots.\n",
1711 solver_recurse_depth*4, "", edge->x, edge->y));
1712 edge->flags |= F_EDGE_SET;
1716 if (!(edge->flags & F_EDGE_SET)) return didsth;
1717 for (n = 0; n < 2; n++) {
1718 if (!tiles[n]) continue;
1719 assert(tiles[n]->type == s_tile);
1720 if (!(tiles[n]->flags & F_TILE_ASSOC)) continue;
1722 tile_opp = tile_opposite(state, tiles[n]);
1724 solvep(("%*simpossible: edge %d,%d has assoc. tile %d,%d"
1725 " with no opposite.\n",
1726 solver_recurse_depth*4, "",
1727 edge->x, edge->y, tiles[n]->x, tiles[n]->y));
1728 /* edge of tile has no opposite edge (off grid?);
1729 * this is impossible. */
1733 dx = tiles[n]->x - edge->x;
1734 dy = tiles[n]->y - edge->y;
1735 assert(INGRID(state, tile_opp->x+dx, tile_opp->y+dy));
1736 edge_opp = &SPACE(state, tile_opp->x+dx, tile_opp->y+dy);
1737 if (!(edge_opp->flags & F_EDGE_SET)) {
1738 solvep(("%*sSetting edge %d,%d as opposite %d,%d\n",
1739 solver_recurse_depth*4, "",
1740 tile_opp->x-dx, tile_opp->y-dy, edge->x, edge->y));
1741 edge_opp->flags |= F_EDGE_SET;
1748 static int solver_spaces_oneposs_cb(game_state *state, space *tile, void *ctx)
1751 space *edgeadj[4], *tileadj[4];
1754 assert(tile->type == s_tile);
1755 if (tile->flags & F_TILE_ASSOC) return 0;
1757 adjacencies(state, tile, edgeadj, tileadj);
1759 /* Empty tile. If each edge is either set, or associated with
1760 * the same dot, we must also associate with dot. */
1761 eset = 0; dotx = -1; doty = -1;
1762 for (n = 0; n < 4; n++) {
1764 assert(edgeadj[n]->type == s_edge);
1765 if (edgeadj[n]->flags & F_EDGE_SET) {
1769 assert(tileadj[n]->type == s_tile);
1771 /* If an adjacent tile is empty we can't make any deductions.*/
1772 if (!(tileadj[n]->flags & F_TILE_ASSOC))
1775 /* If an adjacent tile is assoc. with a different dot
1776 * we can't make any deductions. */
1777 if (dotx != -1 && doty != -1 &&
1778 (tileadj[n]->dotx != dotx ||
1779 tileadj[n]->doty != doty))
1782 dotx = tileadj[n]->dotx;
1783 doty = tileadj[n]->doty;
1787 solvep(("%*simpossible: empty tile %d,%d has 4 edges\n",
1788 solver_recurse_depth*4, "",
1792 assert(dotx != -1 && doty != -1);
1794 ret = solver_add_assoc(state, tile, dotx, doty, "rest are edges");
1795 if (ret == -1) return -1;
1796 assert(ret != 0); /* really should have done something. */
1801 /* Improved algorithm for tracking line-of-sight from dots, and not spaces.
1803 * The solver_ctx already stores a list of dots: the algorithm proceeds by
1804 * expanding outwards from each dot in turn, expanding first to the boundary
1805 * of its currently-connected tile and then to all empty tiles that could see
1806 * it. Empty tiles will be flagged with a 'can see dot <x,y>' sticker.
1808 * Expansion will happen by (symmetrically opposite) pairs of squares; if
1809 * a square hasn't an opposite number there's no point trying to expand through
1810 * it. Empty tiles will therefore also be tagged in pairs.
1812 * If an empty tile already has a 'can see dot <x,y>' tag from a previous dot,
1813 * it (and its partner) gets untagged (or, rather, a 'can see two dots' tag)
1814 * because we're looking for single-dot possibilities.
1816 * Once we've gone through all the dots, any which still have a 'can see dot'
1817 * tag get associated with that dot (because it must have been the only one);
1818 * any without any tag (i.e. that could see _no_ dots) cause an impossibility
1821 * The expansion will happen each time with a stored list of (space *) pairs,
1822 * rather than a mark-and-sweep idea; that's horrifically inefficient.
1824 * expansion algorithm:
1826 * * allocate list of (space *) the size of s->sx*s->sy.
1827 * * allocate second grid for (flags, dotx, doty) size of sx*sy.
1829 * clear second grid (flags = 0, all dotx and doty = 0)
1830 * flags: F_REACHABLE, F_MULTIPLE
1833 * * for each dot, start with one pair of tiles that are associated with it --
1834 * * vertex --> (dx+1, dy+1), (dx-1, dy-1)
1835 * * edge --> (adj1, adj2)
1836 * * tile --> (tile, tile) ???
1837 * * mark that pair of tiles with F_MARK, clear all other F_MARKs.
1838 * * add two tiles to start of list.
1840 * set start = 0, end = next = 2
1842 * from (start to end-1, step 2) {
1843 * * we have two tiles (t1, t2), opposites wrt our dot.
1844 * * for each (at1) sensible adjacent tile to t1 (i.e. not past an edge):
1845 * * work out at2 as the opposite to at1
1846 * * assert at1 and at2 have the same F_MARK values.
1847 * * if at1 & F_MARK ignore it (we've been there on a previous sweep)
1848 * * if either are associated with a different dot
1849 * * mark both with F_MARK (so we ignore them later)
1850 * * otherwise (assoc. with our dot, or empty):
1851 * * mark both with F_MARK
1852 * * add their space * values to the end of the list, set next += 2.
1856 * * we didn't add any new squares; exit the loop.
1858 * * set start = next+1, end = next. go round again
1860 * We've finished expanding from the dot. Now, for each square we have
1861 * in our list (--> each square with F_MARK):
1862 * * if the tile is empty:
1863 * * if F_REACHABLE was already set
1866 * * set F_REACHABLE, set dotx and doty to our dot.
1868 * Then, continue the whole thing for each dot in turn.
1870 * Once we've done for each dot, go through the entire grid looking for
1871 * empty tiles: for each empty tile:
1872 * if F_REACHABLE and not F_MULTIPLE, set that dot (and its double)
1873 * if !F_REACHABLE, return as impossible.
1877 /* Returns 1 if this tile is either already associated with this dot,
1879 static int solver_expand_checkdot(space *tile, space *dot)
1881 if (!(tile->flags & F_TILE_ASSOC)) return 1;
1882 if (tile->dotx == dot->x && tile->doty == dot->y) return 1;
1886 static void solver_expand_fromdot(game_state *state, space *dot, solver_ctx *sctx)
1888 int i, j, x, y, start, end, next;
1891 /* Clear the grid of the (space) flags we'll use. */
1893 /* This is well optimised; analysis showed that:
1894 for (i = 0; i < sctx->sz; i++) state->grid[i].flags &= ~F_MARK;
1895 took up ~85% of the total function time! */
1896 for (y = 1; y < state->sy; y += 2) {
1897 sp = &SPACE(state, 1, y);
1898 for (x = 1; x < state->sx; x += 2, sp += 2)
1899 sp->flags &= ~F_MARK;
1902 /* Seed the list of marked squares with two that must be associated
1903 * with our dot (possibly the same space) */
1904 if (dot->type == s_tile) {
1905 sctx->scratch[0] = sctx->scratch[1] = dot;
1906 } else if (dot->type == s_edge) {
1907 tiles_from_edge(state, dot, sctx->scratch);
1908 } else if (dot->type == s_vertex) {
1909 /* pick two of the opposite ones arbitrarily. */
1910 sctx->scratch[0] = &SPACE(state, dot->x-1, dot->y-1);
1911 sctx->scratch[1] = &SPACE(state, dot->x+1, dot->y+1);
1913 assert(sctx->scratch[0]->flags & F_TILE_ASSOC);
1914 assert(sctx->scratch[1]->flags & F_TILE_ASSOC);
1916 sctx->scratch[0]->flags |= F_MARK;
1917 sctx->scratch[1]->flags |= F_MARK;
1919 debug(("%*sexpand from dot %d,%d seeded with %d,%d and %d,%d.\n",
1920 solver_recurse_depth*4, "", dot->x, dot->y,
1921 sctx->scratch[0]->x, sctx->scratch[0]->y,
1922 sctx->scratch[1]->x, sctx->scratch[1]->y));
1924 start = 0; end = 2; next = 2;
1927 debug(("%*sexpand: start %d, end %d, next %d\n",
1928 solver_recurse_depth*4, "", start, end, next));
1929 for (i = start; i < end; i += 2) {
1930 space *t1 = sctx->scratch[i]/*, *t2 = sctx->scratch[i+1]*/;
1931 space *edges[4], *tileadj[4], *tileadj2;
1933 adjacencies(state, t1, edges, tileadj);
1935 for (j = 0; j < 4; j++) {
1937 if (edges[j]->flags & F_EDGE_SET) continue;
1940 if (tileadj[j]->flags & F_MARK) continue; /* seen before. */
1942 /* We have a tile adjacent to t1; find its opposite. */
1943 tileadj2 = space_opposite_dot(state, tileadj[j], dot);
1945 debug(("%*sMarking %d,%d, no opposite.\n",
1946 solver_recurse_depth*4, "",
1947 tileadj[j]->x, tileadj[j]->y));
1948 tileadj[j]->flags |= F_MARK;
1949 continue; /* no opposite, so mark for next time. */
1951 /* If the tile had an opposite we should have either seen both of
1952 * these, or neither of these, before. */
1953 assert(!(tileadj2->flags & F_MARK));
1955 if (solver_expand_checkdot(tileadj[j], dot) &&
1956 solver_expand_checkdot(tileadj2, dot)) {
1957 /* Both tiles could associate with this dot; add them to
1959 debug(("%*sAdding %d,%d and %d,%d to possibles list.\n",
1960 solver_recurse_depth*4, "",
1961 tileadj[j]->x, tileadj[j]->y, tileadj2->x, tileadj2->y));
1962 sctx->scratch[next++] = tileadj[j];
1963 sctx->scratch[next++] = tileadj2;
1965 /* Either way, we've seen these tiles already so mark them. */
1966 debug(("%*sMarking %d,%d and %d,%d.\n",
1967 solver_recurse_depth*4, "",
1968 tileadj[j]->x, tileadj[j]->y, tileadj2->x, tileadj2->y));
1969 tileadj[j]->flags |= F_MARK;
1970 tileadj2->flags |= F_MARK;
1974 /* We added more squares; go back and try again. */
1975 start = end; end = next; goto expand;
1978 /* We've expanded as far as we can go. Now we update the main flags
1979 * on all tiles we've expanded into -- if they were empty, we have
1980 * found possible associations for this dot. */
1981 for (i = 0; i < end; i++) {
1982 if (sctx->scratch[i]->flags & F_TILE_ASSOC) continue;
1983 if (sctx->scratch[i]->flags & F_REACHABLE) {
1984 /* This is (at least) the second dot this tile could
1985 * associate with. */
1986 debug(("%*sempty tile %d,%d could assoc. other dot %d,%d\n",
1987 solver_recurse_depth*4, "",
1988 sctx->scratch[i]->x, sctx->scratch[i]->y, dot->x, dot->y));
1989 sctx->scratch[i]->flags |= F_MULTIPLE;
1991 /* This is the first (possibly only) dot. */
1992 debug(("%*sempty tile %d,%d could assoc. 1st dot %d,%d\n",
1993 solver_recurse_depth*4, "",
1994 sctx->scratch[i]->x, sctx->scratch[i]->y, dot->x, dot->y));
1995 sctx->scratch[i]->flags |= F_REACHABLE;
1996 sctx->scratch[i]->dotx = dot->x;
1997 sctx->scratch[i]->doty = dot->y;
2003 static int solver_expand_postcb(game_state *state, space *tile, void *ctx)
2005 assert(tile->type == s_tile);
2007 if (tile->flags & F_TILE_ASSOC) return 0;
2009 if (!(tile->flags & F_REACHABLE)) {
2010 solvep(("%*simpossible: space (%d,%d) can reach no dots.\n",
2011 solver_recurse_depth*4, "", tile->x, tile->y));
2014 if (tile->flags & F_MULTIPLE) return 0;
2016 return solver_add_assoc(state, tile, tile->dotx, tile->doty,
2017 "single possible dot after expansion");
2020 static int solver_expand_dots(game_state *state, solver_ctx *sctx)
2024 for (i = 0; i < sctx->sz; i++)
2025 state->grid[i].flags &= ~(F_REACHABLE|F_MULTIPLE);
2027 for (i = 0; i < state->ndots; i++)
2028 solver_expand_fromdot(state, state->dots[i], sctx);
2030 return foreach_tile(state, solver_expand_postcb, IMPOSSIBLE_QUITS, sctx);
2033 struct recurse_ctx {
2038 static int solver_recurse_cb(game_state *state, space *tile, void *ctx)
2040 struct recurse_ctx *rctx = (struct recurse_ctx *)ctx;
2043 assert(tile->type == s_tile);
2044 if (tile->flags & F_TILE_ASSOC) return 0;
2046 /* We're unassociated: count up all the dots we could associate with. */
2047 for (i = 0; i < state->ndots; i++) {
2048 if (dotfortile(state, tile, state->dots[i]))
2051 if (n > rctx->bestn) {
2058 static int solver_state(game_state *state, int maxdiff);
2060 #define MAXRECURSE 5
2062 static int solver_recurse(game_state *state, int maxdiff)
2064 int diff = DIFF_IMPOSSIBLE, ret, n, gsz = state->sx * state->sy;
2065 space *ingrid, *outgrid = NULL, *bestopp;
2066 struct recurse_ctx rctx;
2068 if (solver_recurse_depth >= MAXRECURSE) {
2069 solvep(("Limiting recursion to %d, returning.", MAXRECURSE));
2070 return DIFF_UNFINISHED;
2073 /* Work out the cell to recurse on; go through all unassociated tiles
2074 * and find which one has the most possible dots it could associate
2079 foreach_tile(state, solver_recurse_cb, 0, &rctx);
2080 if (rctx.bestn == 0) return DIFF_IMPOSSIBLE; /* or assert? */
2083 solvep(("%*sRecursing around %d,%d, with %d possible dots.\n",
2084 solver_recurse_depth*4, "",
2085 rctx.best->x, rctx.best->y, rctx.bestn));
2087 #ifdef STANDALONE_SOLVER
2088 solver_recurse_depth++;
2091 ingrid = snewn(gsz, space);
2092 memcpy(ingrid, state->grid, gsz * sizeof(space));
2094 for (n = 0; n < state->ndots; n++) {
2095 memcpy(state->grid, ingrid, gsz * sizeof(space));
2097 if (!dotfortile(state, rctx.best, state->dots[n])) continue;
2099 /* set cell (temporarily) pointing to that dot. */
2100 solver_add_assoc(state, rctx.best,
2101 state->dots[n]->x, state->dots[n]->y,
2102 "Attempting for recursion");
2104 ret = solver_state(state, maxdiff);
2106 if (diff == DIFF_IMPOSSIBLE && ret != DIFF_IMPOSSIBLE) {
2107 /* we found our first solved grid; copy it away. */
2109 outgrid = snewn(gsz, space);
2110 memcpy(outgrid, state->grid, gsz * sizeof(space));
2112 /* reset cell back to unassociated. */
2113 bestopp = tile_opposite(state, rctx.best);
2114 assert(bestopp && bestopp->flags & F_TILE_ASSOC);
2116 remove_assoc(state, rctx.best);
2117 remove_assoc(state, bestopp);
2119 if (ret == DIFF_AMBIGUOUS || ret == DIFF_UNFINISHED)
2121 else if (ret == DIFF_IMPOSSIBLE)
2124 /* precisely one solution */
2125 if (diff == DIFF_IMPOSSIBLE)
2126 diff = DIFF_UNREASONABLE;
2128 diff = DIFF_AMBIGUOUS;
2130 /* if we've found >1 solution, or ran out of recursion,
2131 * give up immediately. */
2132 if (diff == DIFF_AMBIGUOUS || diff == DIFF_UNFINISHED)
2136 #ifdef STANDALONE_SOLVER
2137 solver_recurse_depth--;
2141 /* we found (at least one) soln; copy it back to state */
2142 memcpy(state->grid, outgrid, gsz * sizeof(space));
2149 static int solver_state(game_state *state, int maxdiff)
2151 solver_ctx *sctx = new_solver(state);
2152 int ret, diff = DIFF_NORMAL;
2154 #ifdef STANDALONE_PICTURE_GENERATOR
2155 /* hack, hack: set picture to NULL during solving so that add_assoc
2156 * won't complain when we attempt recursive guessing and guess wrong */
2157 int *savepic = picture;
2161 ret = solver_obvious(state);
2163 diff = DIFF_IMPOSSIBLE;
2167 #define CHECKRET(d) do { \
2168 if (ret < 0) { diff = DIFF_IMPOSSIBLE; goto got_result; } \
2169 if (ret > 0) { diff = max(diff, (d)); goto cont; } \
2174 ret = foreach_edge(state, solver_lines_opposite_cb,
2175 IMPOSSIBLE_QUITS, sctx);
2176 CHECKRET(DIFF_NORMAL);
2178 ret = foreach_tile(state, solver_spaces_oneposs_cb,
2179 IMPOSSIBLE_QUITS, sctx);
2180 CHECKRET(DIFF_NORMAL);
2182 ret = solver_expand_dots(state, sctx);
2183 CHECKRET(DIFF_NORMAL);
2185 if (maxdiff <= DIFF_NORMAL)
2190 /* if we reach here, we've made no deductions, so we terminate. */
2194 if (check_complete(state, NULL, NULL)) goto got_result;
2196 diff = (maxdiff >= DIFF_UNREASONABLE) ?
2197 solver_recurse(state, maxdiff) : DIFF_UNFINISHED;
2201 #ifndef STANDALONE_SOLVER
2202 debug(("solver_state ends, diff %s:\n", galaxies_diffnames[diff]));
2206 #ifdef STANDALONE_PICTURE_GENERATOR
2214 static char *solve_game(const game_state *state, const game_state *currstate,
2215 const char *aux, char **error)
2217 game_state *tosolve;
2222 tosolve = dup_game(currstate);
2223 diff = solver_state(tosolve, DIFF_UNREASONABLE);
2224 if (diff != DIFF_UNFINISHED && diff != DIFF_IMPOSSIBLE) {
2225 debug(("solve_game solved with current state.\n"));
2230 tosolve = dup_game(state);
2231 diff = solver_state(tosolve, DIFF_UNREASONABLE);
2232 if (diff != DIFF_UNFINISHED && diff != DIFF_IMPOSSIBLE) {
2233 debug(("solve_game solved with original state.\n"));
2242 * Clear tile associations: the solution will only include the
2245 for (i = 0; i < tosolve->sx*tosolve->sy; i++)
2246 tosolve->grid[i].flags &= ~F_TILE_ASSOC;
2247 ret = diff_game(currstate, tosolve, 1);
2253 /* ----------------------------------------------------------
2259 int dx, dy; /* pixel coords of drag pos. */
2260 int dotx, doty; /* grid coords of dot we're dragging from. */
2261 int srcx, srcy; /* grid coords of drag start */
2262 int cur_x, cur_y, cur_visible;
2265 static game_ui *new_ui(const game_state *state)
2267 game_ui *ui = snew(game_ui);
2268 ui->dragging = FALSE;
2269 ui->cur_x = ui->cur_y = 1;
2270 ui->cur_visible = 0;
2274 static void free_ui(game_ui *ui)
2279 static char *encode_ui(const game_ui *ui)
2284 static void decode_ui(game_ui *ui, const char *encoding)
2288 static void game_changed_state(game_ui *ui, const game_state *oldstate,
2289 const game_state *newstate)
2293 #define FLASH_TIME 0.15F
2295 #define PREFERRED_TILE_SIZE 32
2296 #define TILE_SIZE (ds->tilesize)
2297 #define DOT_SIZE (TILE_SIZE / 4)
2298 #define EDGE_THICKNESS (max(TILE_SIZE / 16, 2))
2299 #define BORDER TILE_SIZE
2301 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
2302 #define SCOORD(x) ( ((x) * TILE_SIZE)/2 + BORDER )
2303 #define FROMCOORD(x) ( ((x) - BORDER) / TILE_SIZE )
2305 #define DRAW_WIDTH (BORDER * 2 + ds->w * TILE_SIZE)
2306 #define DRAW_HEIGHT (BORDER * 2 + ds->h * TILE_SIZE)
2308 #define CURSOR_SIZE DOT_SIZE
2310 struct game_drawstate {
2314 unsigned long *grid;
2318 int dragging, dragx, dragy;
2320 int *colour_scratch;
2322 int cx, cy, cur_visible;
2326 #define CORNER_TOLERANCE 0.15F
2327 #define CENTRE_TOLERANCE 0.15F
2330 * Round FP coordinates to the centre of the nearest edge.
2333 static void coord_round_to_edge(float x, float y, int *xr, int *yr)
2335 float xs, ys, xv, yv, dx, dy;
2338 * Find the nearest square-centre.
2340 xs = (float)floor(x) + 0.5F;
2341 ys = (float)floor(y) + 0.5F;
2344 * Find the nearest grid vertex.
2346 xv = (float)floor(x + 0.5F);
2347 yv = (float)floor(y + 0.5F);
2350 * Determine whether the horizontal or vertical edge from that
2351 * vertex alongside that square is closer to us, by comparing
2352 * distances from the square cente.
2354 dx = (float)fabs(x - xs);
2355 dy = (float)fabs(y - ys);
2357 /* Vertical edge: x-coord of corner,
2358 * y-coord of square centre. */
2360 *yr = 1 + 2 * (int)floor(ys);
2362 /* Horizontal edge: x-coord of square centre,
2363 * y-coord of corner. */
2364 *xr = 1 + 2 * (int)floor(xs);
2371 static char *interpret_move(const game_state *state, game_ui *ui,
2372 const game_drawstate *ds,
2373 int x, int y, int button)
2379 px = 2*FROMCOORD((float)x) + 0.5;
2380 py = 2*FROMCOORD((float)y) + 0.5;
2384 if (button == 'C' || button == 'c') return dupstr("C");
2386 if (button == 'S' || button == 's') {
2388 game_state *tmp = dup_game(state);
2389 state->cdiff = solver_state(tmp, DIFF_UNREASONABLE-1);
2390 ret = diff_game(state, tmp, 0);
2395 if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
2396 if (!INUI(state, px, py)) return NULL;
2397 sp = &SPACE(state, px, py);
2398 if (!dot_is_possible(state, sp, 1)) return NULL;
2399 sprintf(buf, "%c%d,%d",
2400 (char)((button == LEFT_BUTTON) ? 'D' : 'd'), px, py);
2407 static char *interpret_move(const game_state *state, game_ui *ui,
2408 const game_drawstate *ds,
2409 int x, int y, int button)
2411 /* UI operations (play mode):
2413 * Toggle edge (set/unset) (left-click on edge)
2414 * Associate space with dot (left-drag from dot)
2415 * Unassociate space (left-drag from space off grid)
2416 * Autofill lines around shape? (right-click?)
2418 * (edit mode; will clear all lines/associations)
2420 * Add or remove dot (left-click)
2423 const char *sep = "";
2429 if (button == 'H' || button == 'h') {
2431 game_state *tmp = dup_game(state);
2432 solver_obvious(tmp);
2433 ret = diff_game(state, tmp, 0);
2438 if (button == LEFT_BUTTON) {
2439 ui->cur_visible = 0;
2440 coord_round_to_edge(FROMCOORD((float)x), FROMCOORD((float)y),
2443 if (!INUI(state, px, py)) return NULL;
2445 sp = &SPACE(state, px, py);
2446 assert(sp->type == s_edge);
2448 sprintf(buf, "E%d,%d", px, py);
2451 } else if (button == RIGHT_BUTTON) {
2454 ui->cur_visible = 0;
2456 px = (int)(2*FROMCOORD((float)x) + 0.5);
2457 py = (int)(2*FROMCOORD((float)y) + 0.5);
2462 * If there's a dot anywhere nearby, we pick up an arrow
2463 * pointing at that dot.
2465 for (py1 = py-1; py1 <= py+1; py1++)
2466 for (px1 = px-1; px1 <= px+1; px1++) {
2467 if (px1 >= 0 && px1 < state->sx &&
2468 py1 >= 0 && py1 < state->sy &&
2469 x >= SCOORD(px1-1) && x < SCOORD(px1+1) &&
2470 y >= SCOORD(py1-1) && y < SCOORD(py1+1) &&
2471 SPACE(state, px1, py1).flags & F_DOT) {
2473 * Found a dot. Begin a drag from it.
2475 dot = &SPACE(state, px1, py1);
2478 goto done; /* multi-level break */
2483 * Otherwise, find the nearest _square_, and pick up the
2484 * same arrow as it's got on it, if any.
2487 px = 2*FROMCOORD(x+TILE_SIZE) - 1;
2488 py = 2*FROMCOORD(y+TILE_SIZE) - 1;
2489 if (px >= 0 && px < state->sx && py >= 0 && py < state->sy) {
2490 sp = &SPACE(state, px, py);
2491 if (sp->flags & F_TILE_ASSOC) {
2492 dot = &SPACE(state, sp->dotx, sp->doty);
2501 * Now, if we've managed to find a dot, begin a drag.
2504 ui->dragging = TRUE;
2511 } else if (button == RIGHT_DRAG && ui->dragging) {
2512 /* just move the drag coords. */
2516 } else if (button == RIGHT_RELEASE && ui->dragging) {
2517 ui->dragging = FALSE;
2520 * Drags are always targeted at a single square.
2522 px = 2*FROMCOORD(x+TILE_SIZE) - 1;
2523 py = 2*FROMCOORD(y+TILE_SIZE) - 1;
2526 * Dragging an arrow on to the same square it started from
2527 * is a null move; just update the ui and finish.
2529 if (px == ui->srcx && py == ui->srcy)
2533 * Otherwise, we remove the arrow from its starting
2534 * square if we didn't start from a dot...
2536 if ((ui->srcx != ui->dotx || ui->srcy != ui->doty) &&
2537 SPACE(state, ui->srcx, ui->srcy).flags & F_TILE_ASSOC) {
2538 sprintf(buf + strlen(buf), "%sU%d,%d", sep, ui->srcx, ui->srcy);
2543 * ... and if the square we're moving it _to_ is valid, we
2544 * add one there instead.
2546 if (INUI(state, px, py)) {
2547 sp = &SPACE(state, px, py);
2549 if (!(sp->flags & F_DOT) && !(sp->flags & F_TILE_ASSOC))
2550 sprintf(buf + strlen(buf), "%sA%d,%d,%d,%d",
2551 sep, px, py, ui->dotx, ui->doty);
2558 } else if (IS_CURSOR_MOVE(button)) {
2559 move_cursor(button, &ui->cur_x, &ui->cur_y, state->sx-1, state->sy-1, 0);
2560 if (ui->cur_x < 1) ui->cur_x = 1;
2561 if (ui->cur_y < 1) ui->cur_y = 1;
2562 ui->cur_visible = 1;
2564 ui->dx = SCOORD(ui->cur_x);
2565 ui->dy = SCOORD(ui->cur_y);
2568 } else if (IS_CURSOR_SELECT(button)) {
2569 if (!ui->cur_visible) {
2570 ui->cur_visible = 1;
2573 sp = &SPACE(state, ui->cur_x, ui->cur_y);
2575 ui->dragging = FALSE;
2577 if ((ui->srcx != ui->dotx || ui->srcy != ui->doty) &&
2578 SPACE(state, ui->srcx, ui->srcy).flags & F_TILE_ASSOC) {
2579 sprintf(buf, "%sU%d,%d", sep, ui->srcx, ui->srcy);
2582 if (sp->type == s_tile && !(sp->flags & F_DOT) && !(sp->flags & F_TILE_ASSOC)) {
2583 sprintf(buf + strlen(buf), "%sA%d,%d,%d,%d",
2584 sep, ui->cur_x, ui->cur_y, ui->dotx, ui->doty);
2587 } else if (sp->flags & F_DOT) {
2588 ui->dragging = TRUE;
2589 ui->dx = SCOORD(ui->cur_x);
2590 ui->dy = SCOORD(ui->cur_y);
2591 ui->dotx = ui->srcx = ui->cur_x;
2592 ui->doty = ui->srcy = ui->cur_y;
2594 } else if (sp->flags & F_TILE_ASSOC) {
2595 assert(sp->type == s_tile);
2596 ui->dragging = TRUE;
2597 ui->dx = SCOORD(ui->cur_x);
2598 ui->dy = SCOORD(ui->cur_y);
2599 ui->dotx = sp->dotx;
2600 ui->doty = sp->doty;
2601 ui->srcx = ui->cur_x;
2602 ui->srcy = ui->cur_y;
2604 } else if (sp->type == s_edge) {
2605 sprintf(buf, "E%d,%d", ui->cur_x, ui->cur_y);
2614 static int check_complete(const game_state *state, int *dsf, int *colours)
2616 int w = state->w, h = state->h;
2621 int minx, miny, maxx, maxy;
2627 dsf = snew_dsf(w*h);
2635 * During actual game play, completion checking is done on the
2636 * basis of the edges rather than the square associations. So
2637 * first we must go through the grid figuring out the connected
2638 * components into which the edges divide it.
2640 for (y = 0; y < h; y++)
2641 for (x = 0; x < w; x++) {
2642 if (y+1 < h && !(SPACE(state, 2*x+1, 2*y+2).flags & F_EDGE_SET))
2643 dsf_merge(dsf, y*w+x, (y+1)*w+x);
2644 if (x+1 < w && !(SPACE(state, 2*x+2, 2*y+1).flags & F_EDGE_SET))
2645 dsf_merge(dsf, y*w+x, y*w+(x+1));
2649 * That gives us our connected components. Now, for each
2650 * component, decide whether it's _valid_. A valid component is
2653 * - is 180-degree rotationally symmetric
2654 * - has a dot at its centre of symmetry
2655 * - has no other dots anywhere within it (including on its
2657 * - contains no internal edges (i.e. edges separating two
2658 * squares which are both part of the component).
2662 * First, go through the grid finding the bounding box of each
2665 sqdata = snewn(w*h, struct sqdata);
2666 for (i = 0; i < w*h; i++) {
2667 sqdata[i].minx = w+1;
2668 sqdata[i].miny = h+1;
2669 sqdata[i].maxx = sqdata[i].maxy = -1;
2670 sqdata[i].valid = FALSE;
2672 for (y = 0; y < h; y++)
2673 for (x = 0; x < w; x++) {
2674 i = dsf_canonify(dsf, y*w+x);
2675 if (sqdata[i].minx > x)
2677 if (sqdata[i].maxx < x)
2679 if (sqdata[i].miny > y)
2681 if (sqdata[i].maxy < y)
2683 sqdata[i].valid = TRUE;
2687 * Now we're in a position to loop over each actual component
2688 * and figure out where its centre of symmetry has to be if
2691 for (i = 0; i < w*h; i++)
2692 if (sqdata[i].valid) {
2694 cx = sqdata[i].cx = sqdata[i].minx + sqdata[i].maxx + 1;
2695 cy = sqdata[i].cy = sqdata[i].miny + sqdata[i].maxy + 1;
2696 if (!(SPACE(state, sqdata[i].cx, sqdata[i].cy).flags & F_DOT))
2697 sqdata[i].valid = FALSE; /* no dot at centre of symmetry */
2698 if (dsf_canonify(dsf, (cy-1)/2*w+(cx-1)/2) != i ||
2699 dsf_canonify(dsf, (cy)/2*w+(cx-1)/2) != i ||
2700 dsf_canonify(dsf, (cy-1)/2*w+(cx)/2) != i ||
2701 dsf_canonify(dsf, (cy)/2*w+(cx)/2) != i)
2702 sqdata[i].valid = FALSE; /* dot at cx,cy isn't ours */
2703 if (SPACE(state, sqdata[i].cx, sqdata[i].cy).flags & F_DOT_BLACK)
2704 sqdata[i].colour = 2;
2706 sqdata[i].colour = 1;
2710 * Now we loop over the whole grid again, this time finding
2711 * extraneous dots (any dot which wholly or partially overlaps
2712 * a square and is not at the centre of symmetry of that
2713 * square's component disqualifies the component from validity)
2714 * and extraneous edges (any edge separating two squares
2715 * belonging to the same component also disqualifies that
2718 for (y = 1; y < state->sy-1; y++)
2719 for (x = 1; x < state->sx-1; x++) {
2720 space *sp = &SPACE(state, x, y);
2722 if (sp->flags & F_DOT) {
2724 * There's a dot here. Use it to disqualify any
2725 * component which deserves it.
2728 for (cy = (y-1) >> 1; cy <= y >> 1; cy++)
2729 for (cx = (x-1) >> 1; cx <= x >> 1; cx++) {
2730 i = dsf_canonify(dsf, cy*w+cx);
2731 if (x != sqdata[i].cx || y != sqdata[i].cy)
2732 sqdata[i].valid = FALSE;
2736 if (sp->flags & F_EDGE_SET) {
2738 * There's an edge here. Use it to disqualify a
2739 * component if necessary.
2741 int cx1 = (x-1) >> 1, cx2 = x >> 1;
2742 int cy1 = (y-1) >> 1, cy2 = y >> 1;
2743 assert((cx1==cx2) ^ (cy1==cy2));
2744 i = dsf_canonify(dsf, cy1*w+cx1);
2745 if (i == dsf_canonify(dsf, cy2*w+cx2))
2746 sqdata[i].valid = FALSE;
2751 * And finally we test rotational symmetry: for each square in
2752 * the grid, find which component it's in, test that that
2753 * component also has a square in the symmetric position, and
2754 * disqualify it if it doesn't.
2756 for (y = 0; y < h; y++)
2757 for (x = 0; x < w; x++) {
2760 i = dsf_canonify(dsf, y*w+x);
2762 x2 = sqdata[i].cx - 1 - x;
2763 y2 = sqdata[i].cy - 1 - y;
2764 if (i != dsf_canonify(dsf, y2*w+x2))
2765 sqdata[i].valid = FALSE;
2769 * That's it. We now have all the connected components marked
2770 * as valid or not valid. So now we return a `colours' array if
2771 * we were asked for one, and also we return an overall
2772 * true/false value depending on whether _every_ square in the
2773 * grid is part of a valid component.
2776 for (i = 0; i < w*h; i++) {
2777 int ci = dsf_canonify(dsf, i);
2778 int thisok = sqdata[ci].valid;
2780 colours[i] = thisok ? sqdata[ci].colour : 0;
2781 ret = ret && thisok;
2791 static game_state *execute_move(const game_state *state, const char *move)
2793 int x, y, ax, ay, n, dx, dy;
2794 game_state *ret = dup_game(state);
2797 debug(("%s\n", move));
2801 if (c == 'E' || c == 'U' || c == 'M'
2803 || c == 'D' || c == 'd'
2807 if (sscanf(move, "%d,%d%n", &x, &y, &n) != 2 ||
2811 sp = &SPACE(ret, x, y);
2813 if (c == 'D' || c == 'd') {
2814 unsigned int currf, newf, maskf;
2816 if (!dot_is_possible(ret, sp, 1)) goto badmove;
2818 newf = F_DOT | (c == 'd' ? F_DOT_BLACK : 0);
2819 currf = GRID(ret, grid, x, y).flags;
2820 maskf = F_DOT | F_DOT_BLACK;
2821 /* if we clicked 'white dot':
2822 * white --> empty, empty --> white, black --> white.
2823 * if we clicked 'black dot':
2824 * black --> empty, empty --> black, white --> black.
2826 if (currf & maskf) {
2827 sp->flags &= ~maskf;
2828 if ((currf & maskf) != newf)
2832 sp->nassoc = 0; /* edit-mode disallows associations. */
2833 game_update_dots(ret);
2837 if (sp->type != s_edge) goto badmove;
2838 sp->flags ^= F_EDGE_SET;
2839 } else if (c == 'U') {
2840 if (sp->type != s_tile || !(sp->flags & F_TILE_ASSOC))
2842 remove_assoc(ret, sp);
2843 } else if (c == 'M') {
2844 if (!(sp->flags & F_DOT)) goto badmove;
2845 sp->flags ^= F_DOT_HOLD;
2848 } else if (c == 'A' || c == 'a') {
2850 if (sscanf(move, "%d,%d,%d,%d%n", &x, &y, &ax, &ay, &n) != 4 ||
2851 x < 1 || y < 1 || x >= (ret->sx-1) || y >= (ret->sy-1) ||
2852 ax < 1 || ay < 1 || ax >= (ret->sx-1) || ay >= (ret->sy-1))
2855 dot = &GRID(ret, grid, ax, ay);
2856 if (!(dot->flags & F_DOT))goto badmove;
2857 if (dot->flags & F_DOT_HOLD) goto badmove;
2859 for (dx = -1; dx <= 1; dx++) {
2860 for (dy = -1; dy <= 1; dy++) {
2861 sp = &GRID(ret, grid, x+dx, y+dy);
2862 if (sp->type != s_tile) continue;
2863 if (sp->flags & F_TILE_ASSOC) {
2864 space *dot = &SPACE(ret, sp->dotx, sp->doty);
2865 if (dot->flags & F_DOT_HOLD) continue;
2867 add_assoc(ret, sp, dot);
2872 } else if (c == 'C') {
2876 } else if (c == 'S') {
2878 ret->used_solve = 1;
2887 if (check_complete(ret, NULL, NULL))
2896 /* ----------------------------------------------------------------------
2900 /* Lines will be much smaller size than squares; say, 1/8 the size?
2902 * Need a 'top-left corner of location XxY' to take this into account;
2903 * alternaticaly, that could give the middle of that location, and the
2904 * drawing code would just know the expected dimensions.
2906 * We also need something to take a click and work out what it was
2907 * we were interested in. Clicking on vertices is required because
2908 * we may want to drag from them, for example.
2911 static void game_compute_size(const game_params *params, int sz,
2914 struct { int tilesize, w, h; } ads, *ds = &ads;
2924 static void game_set_size(drawing *dr, game_drawstate *ds,
2925 const game_params *params, int sz)
2929 assert(TILE_SIZE > 0);
2932 ds->bl = blitter_new(dr, TILE_SIZE, TILE_SIZE);
2934 assert(!ds->cur_bl);
2935 ds->cur_bl = blitter_new(dr, TILE_SIZE, TILE_SIZE);
2938 static float *game_colours(frontend *fe, int *ncolours)
2940 float *ret = snewn(3 * NCOLOURS, float);
2944 * We call game_mkhighlight to ensure the background colour
2945 * isn't completely white. We don't actually use the high- and
2946 * lowlight colours it generates.
2948 game_mkhighlight(fe, ret, COL_BACKGROUND, COL_WHITEBG, COL_BLACKBG);
2950 for (i = 0; i < 3; i++) {
2952 * Currently, white dots and white-background squares are
2955 ret[COL_WHITEDOT * 3 + i] = 1.0F;
2956 ret[COL_WHITEBG * 3 + i] = 1.0F;
2959 * But black-background squares are a dark grey, whereas
2960 * black dots are really black.
2962 ret[COL_BLACKDOT * 3 + i] = 0.0F;
2963 ret[COL_BLACKBG * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.3F;
2966 * In unfilled squares, we draw a faint gridwork.
2968 ret[COL_GRID * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.8F;
2971 * Edges and arrows are filled in in pure black.
2973 ret[COL_EDGE * 3 + i] = 0.0F;
2974 ret[COL_ARROW * 3 + i] = 0.0F;
2978 /* tinge the edit background to bluey */
2979 ret[COL_BACKGROUND * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2980 ret[COL_BACKGROUND * 3 + 1] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2981 ret[COL_BACKGROUND * 3 + 2] = min(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
2984 ret[COL_CURSOR * 3 + 0] = min(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
2985 ret[COL_CURSOR * 3 + 1] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2986 ret[COL_CURSOR * 3 + 2] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2988 *ncolours = NCOLOURS;
2992 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
2994 struct game_drawstate *ds = snew(struct game_drawstate);
3001 ds->grid = snewn(ds->w*ds->h, unsigned long);
3002 for (i = 0; i < ds->w*ds->h; i++)
3003 ds->grid[i] = 0xFFFFFFFFUL;
3004 ds->dx = snewn(ds->w*ds->h, int);
3005 ds->dy = snewn(ds->w*ds->h, int);
3008 ds->dragging = FALSE;
3009 ds->dragx = ds->dragy = 0;
3011 ds->colour_scratch = snewn(ds->w * ds->h, int);
3014 ds->cx = ds->cy = 0;
3015 ds->cur_visible = 0;
3020 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
3022 if (ds->cur_bl) blitter_free(dr, ds->cur_bl);
3023 sfree(ds->colour_scratch);
3024 if (ds->bl) blitter_free(dr, ds->bl);
3031 #define DRAW_EDGE_L 0x0001
3032 #define DRAW_EDGE_R 0x0002
3033 #define DRAW_EDGE_U 0x0004
3034 #define DRAW_EDGE_D 0x0008
3035 #define DRAW_CORNER_UL 0x0010
3036 #define DRAW_CORNER_UR 0x0020
3037 #define DRAW_CORNER_DL 0x0040
3038 #define DRAW_CORNER_DR 0x0080
3039 #define DRAW_WHITE 0x0100
3040 #define DRAW_BLACK 0x0200
3041 #define DRAW_ARROW 0x0400
3042 #define DRAW_CURSOR 0x0800
3043 #define DOT_SHIFT_C 12
3044 #define DOT_SHIFT_M 2
3045 #define DOT_WHITE 1UL
3046 #define DOT_BLACK 2UL
3049 * Draw an arrow centred on (cx,cy), pointing in the direction
3050 * (ddx,ddy). (I.e. pointing at the point (cx+ddx, cy+ddy).
3052 static void draw_arrow(drawing *dr, game_drawstate *ds,
3053 int cx, int cy, int ddx, int ddy, int col)
3055 float vlen = (float)sqrt(ddx*ddx+ddy*ddy);
3056 float xdx = ddx/vlen, xdy = ddy/vlen;
3057 float ydx = -xdy, ydy = xdx;
3058 int e1x = cx + (int)(xdx*TILE_SIZE/3), e1y = cy + (int)(xdy*TILE_SIZE/3);
3059 int e2x = cx - (int)(xdx*TILE_SIZE/3), e2y = cy - (int)(xdy*TILE_SIZE/3);
3060 int adx = (int)((ydx-xdx)*TILE_SIZE/8), ady = (int)((ydy-xdy)*TILE_SIZE/8);
3061 int adx2 = (int)((-ydx-xdx)*TILE_SIZE/8), ady2 = (int)((-ydy-xdy)*TILE_SIZE/8);
3063 draw_line(dr, e1x, e1y, e2x, e2y, col);
3064 draw_line(dr, e1x, e1y, e1x+adx, e1y+ady, col);
3065 draw_line(dr, e1x, e1y, e1x+adx2, e1y+ady2, col);
3068 static void draw_square(drawing *dr, game_drawstate *ds, int x, int y,
3069 unsigned long flags, int ddx, int ddy)
3071 int lx = COORD(x), ly = COORD(y);
3075 clip(dr, lx, ly, TILE_SIZE, TILE_SIZE);
3078 * Draw the tile background.
3080 draw_rect(dr, lx, ly, TILE_SIZE, TILE_SIZE,
3081 (flags & DRAW_WHITE ? COL_WHITEBG :
3082 flags & DRAW_BLACK ? COL_BLACKBG : COL_BACKGROUND));
3087 gridcol = (flags & DRAW_BLACK ? COL_BLACKDOT : COL_GRID);
3088 draw_rect(dr, lx, ly, 1, TILE_SIZE, gridcol);
3089 draw_rect(dr, lx, ly, TILE_SIZE, 1, gridcol);
3092 * Draw the arrow, if present, or the cursor, if here.
3094 if (flags & DRAW_ARROW)
3095 draw_arrow(dr, ds, lx + TILE_SIZE/2, ly + TILE_SIZE/2, ddx, ddy,
3096 (flags & DRAW_CURSOR) ? COL_CURSOR : COL_ARROW);
3097 else if (flags & DRAW_CURSOR)
3098 draw_rect_outline(dr,
3099 lx + TILE_SIZE/2 - CURSOR_SIZE,
3100 ly + TILE_SIZE/2 - CURSOR_SIZE,
3101 2*CURSOR_SIZE+1, 2*CURSOR_SIZE+1,
3107 if (flags & DRAW_EDGE_L)
3108 draw_rect(dr, lx, ly, EDGE_THICKNESS, TILE_SIZE, COL_EDGE);
3109 if (flags & DRAW_EDGE_R)
3110 draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1, ly,
3111 EDGE_THICKNESS - 1, TILE_SIZE, COL_EDGE);
3112 if (flags & DRAW_EDGE_U)
3113 draw_rect(dr, lx, ly, TILE_SIZE, EDGE_THICKNESS, COL_EDGE);
3114 if (flags & DRAW_EDGE_D)
3115 draw_rect(dr, lx, ly + TILE_SIZE - EDGE_THICKNESS + 1,
3116 TILE_SIZE, EDGE_THICKNESS - 1, COL_EDGE);
3117 if (flags & DRAW_CORNER_UL)
3118 draw_rect(dr, lx, ly, EDGE_THICKNESS, EDGE_THICKNESS, COL_EDGE);
3119 if (flags & DRAW_CORNER_UR)
3120 draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1, ly,
3121 EDGE_THICKNESS - 1, EDGE_THICKNESS, COL_EDGE);
3122 if (flags & DRAW_CORNER_DL)
3123 draw_rect(dr, lx, ly + TILE_SIZE - EDGE_THICKNESS + 1,
3124 EDGE_THICKNESS, EDGE_THICKNESS - 1, COL_EDGE);
3125 if (flags & DRAW_CORNER_DR)
3126 draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1,
3127 ly + TILE_SIZE - EDGE_THICKNESS + 1,
3128 EDGE_THICKNESS - 1, EDGE_THICKNESS - 1, COL_EDGE);
3133 for (dy = 0; dy < 3; dy++)
3134 for (dx = 0; dx < 3; dx++) {
3135 int dotval = (flags >> (DOT_SHIFT_C + DOT_SHIFT_M*(dy*3+dx)));
3136 dotval &= (1 << DOT_SHIFT_M)-1;
3139 draw_circle(dr, lx+dx*TILE_SIZE/2, ly+dy*TILE_SIZE/2,
3141 (dotval == 1 ? COL_WHITEDOT : COL_BLACKDOT),
3146 draw_update(dr, lx, ly, TILE_SIZE, TILE_SIZE);
3149 static void game_redraw(drawing *dr, game_drawstate *ds,
3150 const game_state *oldstate, const game_state *state,
3151 int dir, const game_ui *ui,
3152 float animtime, float flashtime)
3154 int w = ds->w, h = ds->h;
3155 int x, y, flashing = FALSE;
3157 if (flashtime > 0) {
3158 int frame = (int)(flashtime / FLASH_TIME);
3159 flashing = (frame % 2 == 0);
3164 blitter_load(dr, ds->bl, ds->dragx, ds->dragy);
3165 draw_update(dr, ds->dragx, ds->dragy, TILE_SIZE, TILE_SIZE);
3166 ds->dragging = FALSE;
3168 if (ds->cur_visible) {
3170 blitter_load(dr, ds->cur_bl, ds->cx, ds->cy);
3171 draw_update(dr, ds->cx, ds->cy, CURSOR_SIZE*2+1, CURSOR_SIZE*2+1);
3172 ds->cur_visible = FALSE;
3176 draw_rect(dr, 0, 0, DRAW_WIDTH, DRAW_HEIGHT, COL_BACKGROUND);
3177 draw_rect(dr, BORDER - EDGE_THICKNESS + 1, BORDER - EDGE_THICKNESS + 1,
3178 w*TILE_SIZE + EDGE_THICKNESS*2 - 1,
3179 h*TILE_SIZE + EDGE_THICKNESS*2 - 1, COL_EDGE);
3180 draw_update(dr, 0, 0, DRAW_WIDTH, DRAW_HEIGHT);
3184 check_complete(state, NULL, ds->colour_scratch);
3186 for (y = 0; y < h; y++)
3187 for (x = 0; x < w; x++) {
3188 unsigned long flags = 0;
3189 int ddx = 0, ddy = 0;
3194 * Set up the flags for this square. Firstly, see if we
3197 if (SPACE(state, x*2, y*2+1).flags & F_EDGE_SET)
3198 flags |= DRAW_EDGE_L;
3199 if (SPACE(state, x*2+2, y*2+1).flags & F_EDGE_SET)
3200 flags |= DRAW_EDGE_R;
3201 if (SPACE(state, x*2+1, y*2).flags & F_EDGE_SET)
3202 flags |= DRAW_EDGE_U;
3203 if (SPACE(state, x*2+1, y*2+2).flags & F_EDGE_SET)
3204 flags |= DRAW_EDGE_D;
3207 * Also, mark corners of neighbouring edges.
3209 if ((x > 0 && SPACE(state, x*2-1, y*2).flags & F_EDGE_SET) ||
3210 (y > 0 && SPACE(state, x*2, y*2-1).flags & F_EDGE_SET))
3211 flags |= DRAW_CORNER_UL;
3212 if ((x+1 < w && SPACE(state, x*2+3, y*2).flags & F_EDGE_SET) ||
3213 (y > 0 && SPACE(state, x*2+2, y*2-1).flags & F_EDGE_SET))
3214 flags |= DRAW_CORNER_UR;
3215 if ((x > 0 && SPACE(state, x*2-1, y*2+2).flags & F_EDGE_SET) ||
3216 (y+1 < h && SPACE(state, x*2, y*2+3).flags & F_EDGE_SET))
3217 flags |= DRAW_CORNER_DL;
3218 if ((x+1 < w && SPACE(state, x*2+3, y*2+2).flags & F_EDGE_SET) ||
3219 (y+1 < h && SPACE(state, x*2+2, y*2+3).flags & F_EDGE_SET))
3220 flags |= DRAW_CORNER_DR;
3223 * If this square is part of a valid region, paint it
3224 * that region's colour. Exception: if we're flashing,
3225 * everything goes briefly back to background colour.
3227 sp = &SPACE(state, x*2+1, y*2+1);
3228 if (ds->colour_scratch[y*w+x] && !flashing) {
3229 flags |= (ds->colour_scratch[y*w+x] == 2 ?
3230 DRAW_BLACK : DRAW_WHITE);
3234 * If this square is associated with a dot but it isn't
3235 * part of a valid region, draw an arrow in it pointing
3236 * in the direction of that dot.
3238 * Exception: if this is the source point of an active
3239 * drag, we don't draw the arrow.
3241 if ((sp->flags & F_TILE_ASSOC) && !ds->colour_scratch[y*w+x]) {
3242 if (ui->dragging && ui->srcx == x*2+1 && ui->srcy == y*2+1) {
3244 } else if (sp->doty != y*2+1 || sp->dotx != x*2+1) {
3245 flags |= DRAW_ARROW;
3246 ddy = sp->doty - (y*2+1);
3247 ddx = sp->dotx - (x*2+1);
3252 * Now go through the nine possible places we could
3255 for (dy = 0; dy < 3; dy++)
3256 for (dx = 0; dx < 3; dx++) {
3257 sp = &SPACE(state, x*2+dx, y*2+dy);
3258 if (sp->flags & F_DOT) {
3259 unsigned long dotval = (sp->flags & F_DOT_BLACK ?
3260 DOT_BLACK : DOT_WHITE);
3261 flags |= dotval << (DOT_SHIFT_C +
3262 DOT_SHIFT_M*(dy*3+dx));
3267 * Now work out if we have to draw a cursor for this square;
3268 * cursors-on-lines are taken care of below.
3270 if (ui->cur_visible &&
3271 ui->cur_x == x*2+1 && ui->cur_y == y*2+1 &&
3272 !(SPACE(state, x*2+1, y*2+1).flags & F_DOT))
3273 flags |= DRAW_CURSOR;
3276 * Now we have everything we're going to need. Draw the
3279 if (ds->grid[y*w+x] != flags ||
3280 ds->dx[y*w+x] != ddx ||
3281 ds->dy[y*w+x] != ddy) {
3282 draw_square(dr, ds, x, y, flags, ddx, ddy);
3283 ds->grid[y*w+x] = flags;
3284 ds->dx[y*w+x] = ddx;
3285 ds->dy[y*w+x] = ddy;
3290 * Draw a cursor. This secondary blitter is much less invasive than trying
3291 * to fix up all of the rest of the code with sufficient flags to be able to
3292 * display this sensibly.
3294 if (ui->cur_visible) {
3295 space *sp = &SPACE(state, ui->cur_x, ui->cur_y);
3296 ds->cur_visible = TRUE;
3297 ds->cx = SCOORD(ui->cur_x) - CURSOR_SIZE;
3298 ds->cy = SCOORD(ui->cur_y) - CURSOR_SIZE;
3299 blitter_save(dr, ds->cur_bl, ds->cx, ds->cy);
3300 if (sp->flags & F_DOT) {
3301 /* draw a red dot (over the top of whatever would be there already) */
3302 draw_circle(dr, SCOORD(ui->cur_x), SCOORD(ui->cur_y), DOT_SIZE,
3303 COL_CURSOR, COL_BLACKDOT);
3304 } else if (sp->type != s_tile) {
3305 /* draw an edge/vertex square; tile cursors are dealt with above. */
3306 int dx = (ui->cur_x % 2) ? CURSOR_SIZE : CURSOR_SIZE/3;
3307 int dy = (ui->cur_y % 2) ? CURSOR_SIZE : CURSOR_SIZE/3;
3308 int x1 = SCOORD(ui->cur_x)-dx, y1 = SCOORD(ui->cur_y)-dy;
3309 int xs = dx*2+1, ys = dy*2+1;
3311 draw_rect(dr, x1, y1, xs, ys, COL_CURSOR);
3313 draw_update(dr, ds->cx, ds->cy, CURSOR_SIZE*2+1, CURSOR_SIZE*2+1);
3317 ds->dragging = TRUE;
3318 ds->dragx = ui->dx - TILE_SIZE/2;
3319 ds->dragy = ui->dy - TILE_SIZE/2;
3320 blitter_save(dr, ds->bl, ds->dragx, ds->dragy);
3321 draw_arrow(dr, ds, ui->dx, ui->dy,
3322 SCOORD(ui->dotx) - ui->dx,
3323 SCOORD(ui->doty) - ui->dy, COL_ARROW);
3328 if (state->cdiff != -1)
3329 sprintf(buf, "Puzzle is %s.", galaxies_diffnames[state->cdiff]);
3332 status_bar(dr, buf);
3337 static float game_anim_length(const game_state *oldstate,
3338 const game_state *newstate, int dir, game_ui *ui)
3343 static float game_flash_length(const game_state *oldstate,
3344 const game_state *newstate, int dir, game_ui *ui)
3346 if ((!oldstate->completed && newstate->completed) &&
3347 !(newstate->used_solve))
3348 return 3 * FLASH_TIME;
3353 static int game_status(const game_state *state)
3355 return state->completed ? +1 : 0;
3358 static int game_timing_state(const game_state *state, game_ui *ui)
3364 static void game_print_size(const game_params *params, float *x, float *y)
3369 * 8mm squares by default. (There isn't all that much detail
3370 * that needs to go in each square.)
3372 game_compute_size(params, 800, &pw, &ph);
3377 static void game_print(drawing *dr, const game_state *state, int sz)
3379 int w = state->w, h = state->h;
3380 int white, black, blackish;
3384 int ncoords = 0, coordsize = 0;
3386 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3387 game_drawstate ads, *ds = &ads;
3390 white = print_mono_colour(dr, 1);
3391 black = print_mono_colour(dr, 0);
3392 blackish = print_hatched_colour(dr, HATCH_X);
3395 * Get the completion information.
3397 dsf = snewn(w * h, int);
3398 colours = snewn(w * h, int);
3399 check_complete(state, dsf, colours);
3404 print_line_width(dr, TILE_SIZE / 64);
3405 for (x = 1; x < w; x++)
3406 draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h), black);
3407 for (y = 1; y < h; y++)
3408 draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y), black);
3411 * Shade the completed regions. Just in case any particular
3412 * printing platform deals badly with adjacent
3413 * similarly-hatched regions, we'll fill each one as a single
3416 for (i = 0; i < w*h; i++) {
3417 j = dsf_canonify(dsf, i);
3418 if (colours[j] != 0) {
3422 * This is the first square we've run into belonging to
3423 * this polyomino, which means an edge of the polyomino
3424 * is certain to be to our left. (After we finish
3425 * tracing round it, we'll set the colours[] entry to
3426 * zero to prevent accidentally doing it again.)
3436 * We are currently sitting on square (x,y), which
3437 * we know to be in our polyomino, and we also know
3438 * that (x+dx,y+dy) is not. The way I visualise
3439 * this is that we're standing to the right of a
3440 * boundary line, stretching our left arm out to
3441 * point to the exterior square on the far side.
3445 * First, check if we've gone round the entire
3449 (x == i%w && y == i/w && dx == -1 && dy == 0))
3453 * Add to our coordinate list the coordinate
3454 * backwards and to the left of where we are.
3456 if (ncoords + 2 > coordsize) {
3457 coordsize = (ncoords * 3 / 2) + 64;
3458 coords = sresize(coords, coordsize, int);
3460 coords[ncoords++] = COORD((2*x+1 + dx + dy) / 2);
3461 coords[ncoords++] = COORD((2*y+1 + dy - dx) / 2);
3464 * Follow the edge round. If the square directly in
3465 * front of us is not part of the polyomino, we
3466 * turn right; if it is and so is the square in
3467 * front of (x+dx,y+dy), we turn left; otherwise we
3470 if (x-dy < 0 || x-dy >= w || y+dx < 0 || y+dx >= h ||
3471 dsf_canonify(dsf, (y+dx)*w+(x-dy)) != j) {
3476 } else if (x+dx-dy >= 0 && x+dx-dy < w &&
3477 y+dy+dx >= 0 && y+dy+dx < h &&
3478 dsf_canonify(dsf, (y+dy+dx)*w+(x+dx-dy)) == j) {
3495 * Now we have our polygon complete, so fill it.
3497 draw_polygon(dr, coords, ncoords/2,
3498 colours[j] == 2 ? blackish : -1, black);
3501 * And mark this polyomino as done.
3510 for (y = 0; y <= h; y++)
3511 for (x = 0; x <= w; x++) {
3512 if (x < w && SPACE(state, x*2+1, y*2).flags & F_EDGE_SET)
3513 draw_rect(dr, COORD(x)-EDGE_THICKNESS, COORD(y)-EDGE_THICKNESS,
3514 EDGE_THICKNESS * 2 + TILE_SIZE, EDGE_THICKNESS * 2,
3516 if (y < h && SPACE(state, x*2, y*2+1).flags & F_EDGE_SET)
3517 draw_rect(dr, COORD(x)-EDGE_THICKNESS, COORD(y)-EDGE_THICKNESS,
3518 EDGE_THICKNESS * 2, EDGE_THICKNESS * 2 + TILE_SIZE,
3525 for (y = 0; y <= 2*h; y++)
3526 for (x = 0; x <= 2*w; x++)
3527 if (SPACE(state, x, y).flags & F_DOT) {
3528 draw_circle(dr, (int)COORD(x/2.0), (int)COORD(y/2.0), DOT_SIZE,
3529 (SPACE(state, x, y).flags & F_DOT_BLACK ?
3530 black : white), black);
3540 #define thegame galaxies
3543 const struct game thegame = {
3544 "Galaxies", "games.galaxies", "galaxies",
3551 TRUE, game_configure, custom_params,
3563 TRUE, game_can_format_as_text_now, game_text_format,
3571 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3574 game_free_drawstate,
3580 FALSE, FALSE, NULL, NULL,
3581 TRUE, /* wants_statusbar */
3583 TRUE, FALSE, game_print_size, game_print,
3584 FALSE, /* wants_statusbar */
3586 FALSE, game_timing_state,
3587 REQUIRE_RBUTTON, /* flags */
3590 #ifdef STANDALONE_SOLVER
3596 static void usage_exit(const char *msg)
3599 fprintf(stderr, "%s: %s\n", quis, msg);
3600 fprintf(stderr, "Usage: %s [--seed SEED] --soak <params> | [game_id [game_id ...]]\n", quis);
3604 static void dump_state(game_state *state)
3606 char *temp = game_text_format(state);
3607 printf("%s\n", temp);
3611 static int gen(game_params *p, random_state *rs, int debug)
3618 solver_show_working = debug;
3620 printf("Generating a %dx%d %s puzzle.\n",
3621 p->w, p->h, galaxies_diffnames[p->diff]);
3623 desc = new_game_desc(p, rs, NULL, 0);
3624 state = new_game(NULL, p, desc);
3627 diff = solver_state(state, DIFF_UNREASONABLE);
3628 printf("Generated %s game %dx%d:%s\n",
3629 galaxies_diffnames[diff], p->w, p->h, desc);
3638 static void soak(game_params *p, random_state *rs)
3640 time_t tt_start, tt_now, tt_last;
3643 int diff, n = 0, i, diffs[DIFF_MAX], ndots = 0, nspaces = 0;
3646 solver_show_working = 0;
3648 tt_start = tt_now = time(NULL);
3649 for (i = 0; i < DIFF_MAX; i++) diffs[i] = 0;
3652 printf("Soak-generating a %dx%d grid, max. diff %s.\n",
3653 p->w, p->h, galaxies_diffnames[p->diff]);
3655 for (i = 0; i < DIFF_MAX; i++)
3656 printf("%s%s", (i == 0) ? "" : ", ", galaxies_diffnames[i]);
3660 desc = new_game_desc(p, rs, NULL, 0);
3661 st = new_game(NULL, p, desc);
3662 diff = solver_state(st, p->diff);
3663 nspaces += st->w*st->h;
3664 for (i = 0; i < st->sx*st->sy; i++)
3665 if (st->grid[i].flags & F_DOT) ndots++;
3671 tt_last = time(NULL);
3672 if (tt_last > tt_now) {
3674 printf("%d total, %3.1f/s, [",
3675 n, (double)n / ((double)tt_now - tt_start));
3676 for (i = 0; i < DIFF_MAX; i++)
3677 printf("%s%.1f%%", (i == 0) ? "" : ", ",
3678 100.0 * ((double)diffs[i] / (double)n));
3679 printf("], %.1f%% dots\n",
3680 100.0 * ((double)ndots / (double)nspaces));
3685 int main(int argc, char **argv)
3688 char *id = NULL, *desc, *err;
3690 int diff, do_soak = 0, verbose = 0;
3692 time_t seed = time(NULL);
3695 while (--argc > 0) {
3697 if (!strcmp(p, "-v")) {
3699 } else if (!strcmp(p, "--seed")) {
3700 if (argc == 0) usage_exit("--seed needs an argument");
3701 seed = (time_t)atoi(*++argv);
3703 } else if (!strcmp(p, "--soak")) {
3705 } else if (*p == '-') {
3706 usage_exit("unrecognised option");
3714 p = default_params();
3715 rs = random_new((void*)&seed, sizeof(time_t));
3718 if (!id) usage_exit("need one argument for --soak");
3719 decode_params(p, *argv);
3726 p->w = random_upto(rs, 15) + 3;
3727 p->h = random_upto(rs, 15) + 3;
3728 p->diff = random_upto(rs, DIFF_UNREASONABLE);
3729 diff = gen(p, rs, 0);
3734 desc = strchr(id, ':');
3736 decode_params(p, id);
3737 gen(p, rs, verbose);
3740 solver_show_working = 1;
3743 decode_params(p, id);
3744 err = validate_desc(p, desc);
3746 fprintf(stderr, "%s: %s\n", argv[0], err);
3749 s = new_game(NULL, p, desc);
3750 diff = solver_state(s, DIFF_UNREASONABLE);
3752 printf("Puzzle is %s.\n", galaxies_diffnames[diff]);
3763 #ifdef STANDALONE_PICTURE_GENERATOR
3766 * Main program for the standalone picture generator. To use it,
3767 * simply provide it with an XBM-format bitmap file (note XBM, not
3768 * XPM) on standard input, and it will output a game ID in return.
3771 * $ ./galaxiespicture < badly-drawn-cat.xbm
3772 * 11x11:eloMBLzFeEzLNMWifhaWYdDbixCymBbBMLoDdewGg
3774 * If you want a puzzle with a non-standard difficulty level, pass
3775 * a partial parameters string as a command-line argument (e.g.
3776 * `./galaxiespicture du < foo.xbm', where `du' is the same suffix
3777 * which if it appeared in a random-seed game ID would set the
3778 * difficulty level to Unreasonable). However, be aware that if the
3779 * generator fails to produce an adequately difficult puzzle too
3780 * many times then it will give up and return an easier one (just
3781 * as it does during normal GUI play). To be sure you really have
3782 * the difficulty you asked for, use galaxiessolver to
3785 * (Perhaps I ought to include an option to make this standalone
3786 * generator carry on looping until it really does get the right
3787 * difficulty. Hmmm.)
3792 int main(int argc, char **argv)
3795 char *params, *desc;
3797 time_t seed = time(NULL);
3802 par = default_params();
3804 decode_params(par, argv[1]); /* get difficulty */
3805 par->w = par->h = -1;
3808 * Now read an XBM file from standard input. This is simple and
3809 * hacky and will do very little error detection, so don't feed
3814 while (fgets(buf, sizeof(buf), stdin)) {
3815 buf[strcspn(buf, "\r\n")] = '\0';
3816 if (!strncmp(buf, "#define", 7)) {
3818 * Lines starting `#define' give the width and height.
3820 char *num = buf + strlen(buf);
3823 while (num > buf && isdigit((unsigned char)num[-1]))
3826 while (symend > buf && isspace((unsigned char)symend[-1]))
3829 if (symend-5 >= buf && !strncmp(symend-5, "width", 5))
3831 else if (symend-6 >= buf && !strncmp(symend-6, "height", 6))
3835 * Otherwise, break the string up into words and take
3836 * any word of the form `0x' plus hex digits to be a
3839 char *p, *wordstart;
3842 if (par->w < 0 || par->h < 0) {
3843 printf("failed to read width and height\n");
3846 picture = snewn(par->w * par->h, int);
3847 for (i = 0; i < par->w * par->h; i++)
3853 while (*p && (*p == ',' || isspace((unsigned char)*p)))
3856 while (*p && !(*p == ',' || *p == '}' ||
3857 isspace((unsigned char)*p)))
3862 if (wordstart[0] == '0' &&
3863 (wordstart[1] == 'x' || wordstart[1] == 'X') &&
3864 !wordstart[2 + strspn(wordstart+2,
3865 "0123456789abcdefABCDEF")]) {
3866 unsigned long byte = strtoul(wordstart+2, NULL, 16);
3867 for (i = 0; i < 8; i++) {
3868 int bit = (byte >> i) & 1;
3869 if (y < par->h && x < par->w)
3870 picture[y * par->w + x] = bit;
3883 for (i = 0; i < par->w * par->h; i++)
3884 if (picture[i] < 0) {
3885 fprintf(stderr, "failed to read enough bitmap data\n");
3889 rs = random_new((void*)&seed, sizeof(time_t));
3891 desc = new_game_desc(par, rs, NULL, FALSE);
3892 params = encode_params(par, FALSE);
3893 printf("%s:%s\n", params, desc);
3905 /* vim: set shiftwidth=4 tabstop=8: */