2 * signpost.c: implementation of the janko game 'arrow path'
14 #define PREFERRED_TILE_SIZE 48
15 #define TILE_SIZE (ds->tilesize)
16 #define BLITTER_SIZE TILE_SIZE
17 #define BORDER (TILE_SIZE / 2)
19 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
20 #define FROMCOORD(x) ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
22 #define INGRID(s,x,y) ((x) >= 0 && (x) < (s)->w && (y) >= 0 && (y) < (s)->h)
24 #define FLASH_SPIN 0.7F
26 #define NBACKGROUNDS 16
29 COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT,
30 COL_GRID, COL_CURSOR, COL_ERROR, COL_DRAG_ORIGIN,
31 COL_ARROW, COL_ARROW_BG_DIM,
32 COL_NUMBER, COL_NUMBER_SET, COL_NUMBER_SET_MID,
33 COL_B0, /* background colours */
34 COL_M0 = COL_B0 + 1*NBACKGROUNDS, /* mid arrow colours */
35 COL_D0 = COL_B0 + 2*NBACKGROUNDS, /* dim arrow colours */
36 COL_X0 = COL_B0 + 3*NBACKGROUNDS, /* dim arrow colours */
37 NCOLOURS = COL_B0 + 4*NBACKGROUNDS
42 int force_corner_start;
45 enum { DIR_N = 0, DIR_NE, DIR_E, DIR_SE, DIR_S, DIR_SW, DIR_W, DIR_NW, DIR_MAX };
46 static const char *dirstrings[8] = { "N ", "NE", "E ", "SE", "S ", "SW", "W ", "NW" };
48 static const int dxs[DIR_MAX] = { 0, 1, 1, 1, 0, -1, -1, -1 };
49 static const int dys[DIR_MAX] = { -1, -1, 0, 1, 1, 1, 0, -1 };
51 #define DIR_OPPOSITE(d) ((d+4)%8)
55 int completed, used_solve, impossible;
56 int *dirs; /* direction enums, size n */
57 int *nums; /* numbers, size n */
58 unsigned int *flags; /* flags, size n */
59 int *next, *prev; /* links to other cell indexes, size n (-1 absent) */
60 int *dsf; /* connects regions with a dsf. */
61 int *numsi; /* for each number, which index is it in? (-1 absent) */
64 #define FLAG_IMMUTABLE 1
67 /* --- Generally useful functions --- */
69 #define ISREALNUM(state, num) ((num) > 0 && (num) <= (state)->n)
71 static int whichdir(int fromx, int fromy, int tox, int toy)
78 if (dx && dy && abs(dx) != abs(dy)) return -1;
80 if (dx) dx = dx / abs(dx); /* limit to (-1, 0, 1) */
81 if (dy) dy = dy / abs(dy); /* ditto */
83 for (i = 0; i < DIR_MAX; i++) {
84 if (dx == dxs[i] && dy == dys[i]) return i;
89 static int whichdiri(game_state *state, int fromi, int toi)
92 return whichdir(fromi%w, fromi/w, toi%w, toi/w);
95 static int ispointing(const game_state *state, int fromx, int fromy,
98 int w = state->w, dir = state->dirs[fromy*w+fromx];
100 /* (by convention) squares do not point to themselves. */
101 if (fromx == tox && fromy == toy) return 0;
103 /* the final number points to nothing. */
104 if (state->nums[fromy*w + fromx] == state->n) return 0;
107 if (!INGRID(state, fromx, fromy)) return 0;
108 if (fromx == tox && fromy == toy) return 1;
109 fromx += dxs[dir]; fromy += dys[dir];
111 return 0; /* not reached */
114 static int ispointingi(game_state *state, int fromi, int toi)
117 return ispointing(state, fromi%w, fromi/w, toi%w, toi/w);
120 /* Taking the number 'num', work out the gap between it and the next
121 * available number up or down (depending on d). Return 1 if the region
122 * at (x,y) will fit in that gap, or 0 otherwise. */
123 static int move_couldfit(const game_state *state, int num, int d, int x, int y)
125 int n, gap, i = y*state->w+x, sz;
128 /* The 'gap' is the number of missing numbers in the grid between
129 * our number and the next one in the sequence (up or down), or
130 * the end of the sequence (if we happen not to have 1/n present) */
131 for (n = num + d, gap = 0;
132 ISREALNUM(state, n) && state->numsi[n] == -1;
133 n += d, gap++) ; /* empty loop */
136 /* no gap, so the only allowable move is that that directly
137 * links the two numbers. */
139 return (n == num+d) ? 0 : 1;
141 if (state->prev[i] == -1 && state->next[i] == -1)
142 return 1; /* single unconnected square, always OK */
144 sz = dsf_size(state->dsf, i);
145 return (sz > gap) ? 0 : 1;
148 static int isvalidmove(const game_state *state, int clever,
149 int fromx, int fromy, int tox, int toy)
151 int w = state->w, from = fromy*w+fromx, to = toy*w+tox;
154 if (!INGRID(state, fromx, fromy) || !INGRID(state, tox, toy))
157 /* can only move where we point */
158 if (!ispointing(state, fromx, fromy, tox, toy))
161 nfrom = state->nums[from]; nto = state->nums[to];
163 /* can't move _from_ the preset final number, or _to_ the preset 1. */
164 if (((nfrom == state->n) && (state->flags[from] & FLAG_IMMUTABLE)) ||
165 ((nto == 1) && (state->flags[to] & FLAG_IMMUTABLE)))
168 /* can't create a new connection between cells in the same region
169 * as that would create a loop. */
170 if (dsf_canonify(state->dsf, from) == dsf_canonify(state->dsf, to))
173 /* if both cells are actual numbers, can't drag if we're not
174 * one digit apart. */
175 if (ISREALNUM(state, nfrom) && ISREALNUM(state, nto)) {
178 } else if (clever && ISREALNUM(state, nfrom)) {
179 if (!move_couldfit(state, nfrom, +1, tox, toy))
181 } else if (clever && ISREALNUM(state, nto)) {
182 if (!move_couldfit(state, nto, -1, fromx, fromy))
189 static void makelink(game_state *state, int from, int to)
191 if (state->next[from] != -1)
192 state->prev[state->next[from]] = -1;
193 state->next[from] = to;
195 if (state->prev[to] != -1)
196 state->next[state->prev[to]] = -1;
197 state->prev[to] = from;
200 static int game_can_format_as_text_now(const game_params *params)
202 if (params->w * params->h >= 100) return 0;
206 static char *game_text_format(const game_state *state)
208 int len = state->h * 2 * (4*state->w + 1) + state->h + 2;
209 int x, y, i, num, n, set;
212 p = ret = snewn(len, char);
214 for (y = 0; y < state->h; y++) {
215 for (x = 0; x < state->h; x++) {
217 *p++ = dirstrings[state->dirs[i]][0];
218 *p++ = dirstrings[state->dirs[i]][1];
219 *p++ = (state->flags[i] & FLAG_IMMUTABLE) ? 'I' : ' ';
223 for (x = 0; x < state->h; x++) {
225 num = state->nums[i];
231 n = num % (state->n+1);
232 set = num / (state->n+1);
234 assert(n <= 99); /* two digits only! */
239 *p++ = (n >= 10) ? ('0' + (n/10)) : ' ';
255 static void debug_state(const char *desc, game_state *state)
259 if (state->n >= 100) {
260 debug(("[ no game_text_format for this size ]"));
263 dbg = game_text_format(state);
264 debug(("%s\n%s", desc, dbg));
270 static void strip_nums(game_state *state) {
272 for (i = 0; i < state->n; i++) {
273 if (!(state->flags[i] & FLAG_IMMUTABLE))
276 memset(state->next, -1, state->n*sizeof(int));
277 memset(state->prev, -1, state->n*sizeof(int));
278 memset(state->numsi, -1, (state->n+1)*sizeof(int));
279 dsf_init(state->dsf, state->n);
282 static int check_nums(game_state *orig, game_state *copy, int only_immutable)
285 assert(copy->n == orig->n);
286 for (i = 0; i < copy->n; i++) {
287 if (only_immutable && !(copy->flags[i] & FLAG_IMMUTABLE)) continue;
288 assert(copy->nums[i] >= 0);
289 assert(copy->nums[i] <= copy->n);
290 if (copy->nums[i] != orig->nums[i]) {
291 debug(("check_nums: (%d,%d) copy=%d, orig=%d.",
292 i%orig->w, i/orig->w, copy->nums[i], orig->nums[i]));
299 /* --- Game parameter/presets functions --- */
301 static game_params *default_params(void)
303 game_params *ret = snew(game_params);
305 ret->force_corner_start = 1;
310 static const struct game_params signpost_presets[] = {
319 static int game_fetch_preset(int i, char **name, game_params **params)
324 if (i < 0 || i >= lenof(signpost_presets))
327 ret = default_params();
328 *ret = signpost_presets[i];
331 sprintf(buf, "%dx%d%s", ret->w, ret->h,
332 ret->force_corner_start ? "" : ", free ends");
338 static void free_params(game_params *params)
343 static game_params *dup_params(const game_params *params)
345 game_params *ret = snew(game_params);
346 *ret = *params; /* structure copy */
350 static void decode_params(game_params *ret, char const *string)
352 ret->w = ret->h = atoi(string);
353 while (*string && isdigit((unsigned char)*string)) string++;
354 if (*string == 'x') {
356 ret->h = atoi(string);
357 while (*string && isdigit((unsigned char)*string)) string++;
359 ret->force_corner_start = 0;
360 if (*string == 'c') {
362 ret->force_corner_start = 1;
367 static char *encode_params(const game_params *params, int full)
372 sprintf(data, "%dx%d%s", params->w, params->h,
373 params->force_corner_start ? "c" : "");
375 sprintf(data, "%dx%d", params->w, params->h);
380 static config_item *game_configure(const game_params *params)
385 ret = snewn(4, config_item);
387 ret[0].name = "Width";
388 ret[0].type = C_STRING;
389 sprintf(buf, "%d", params->w);
390 ret[0].u.string.sval = dupstr(buf);
392 ret[1].name = "Height";
393 ret[1].type = C_STRING;
394 sprintf(buf, "%d", params->h);
395 ret[1].u.string.sval = dupstr(buf);
397 ret[2].name = "Start and end in corners";
398 ret[2].type = C_BOOLEAN;
399 ret[2].u.boolean.bval = params->force_corner_start;
407 static game_params *custom_params(const config_item *cfg)
409 game_params *ret = snew(game_params);
411 ret->w = atoi(cfg[0].u.string.sval);
412 ret->h = atoi(cfg[1].u.string.sval);
413 ret->force_corner_start = cfg[2].u.boolean.bval;
418 static char *validate_params(const game_params *params, int full)
420 if (params->w < 1) return "Width must be at least one";
421 if (params->h < 1) return "Height must be at least one";
422 if (full && params->w == 1 && params->h == 1)
423 /* The UI doesn't let us move these from unsolved to solved,
424 * so we disallow generating (but not playing) them. */
425 return "Width and height cannot both be one";
429 /* --- Game description string generation and unpicking --- */
431 static void blank_game_into(game_state *state)
433 memset(state->dirs, 0, state->n*sizeof(int));
434 memset(state->nums, 0, state->n*sizeof(int));
435 memset(state->flags, 0, state->n*sizeof(unsigned int));
436 memset(state->next, -1, state->n*sizeof(int));
437 memset(state->prev, -1, state->n*sizeof(int));
438 memset(state->numsi, -1, (state->n+1)*sizeof(int));
441 static game_state *blank_game(int w, int h)
443 game_state *state = snew(game_state);
445 memset(state, 0, sizeof(game_state));
450 state->dirs = snewn(state->n, int);
451 state->nums = snewn(state->n, int);
452 state->flags = snewn(state->n, unsigned int);
453 state->next = snewn(state->n, int);
454 state->prev = snewn(state->n, int);
455 state->dsf = snew_dsf(state->n);
456 state->numsi = snewn(state->n+1, int);
458 blank_game_into(state);
463 static void dup_game_to(game_state *to, const game_state *from)
465 to->completed = from->completed;
466 to->used_solve = from->used_solve;
467 to->impossible = from->impossible;
469 memcpy(to->dirs, from->dirs, to->n*sizeof(int));
470 memcpy(to->flags, from->flags, to->n*sizeof(unsigned int));
471 memcpy(to->nums, from->nums, to->n*sizeof(int));
473 memcpy(to->next, from->next, to->n*sizeof(int));
474 memcpy(to->prev, from->prev, to->n*sizeof(int));
476 memcpy(to->dsf, from->dsf, to->n*sizeof(int));
477 memcpy(to->numsi, from->numsi, (to->n+1)*sizeof(int));
480 static game_state *dup_game(const game_state *state)
482 game_state *ret = blank_game(state->w, state->h);
483 dup_game_to(ret, state);
487 static void free_game(game_state *state)
499 static void unpick_desc(const game_params *params, const char *desc,
500 game_state **sout, char **mout)
502 game_state *state = blank_game(params->w, params->h);
508 msg = "Game description longer than expected";
513 if (isdigit((unsigned char)c)) {
514 num = (num*10) + (int)(c-'0');
515 if (num > state->n) {
516 msg = "Number too large";
519 } else if ((c-'a') >= 0 && (c-'a') < DIR_MAX) {
520 state->nums[i] = num;
521 state->flags[i] = num ? FLAG_IMMUTABLE : 0;
524 state->dirs[i] = c - 'a';
527 msg = "Game description shorter than expected";
530 msg = "Game description contains unexpected characters";
536 msg = "Game description shorter than expected";
541 if (msg) { /* sth went wrong. */
542 if (mout) *mout = msg;
545 if (mout) *mout = NULL;
546 if (sout) *sout = state;
547 else free_game(state);
551 static char *generate_desc(game_state *state, int issolve)
556 ret = NULL; retlen = 0;
558 ret = sresize(ret, 2, char);
559 ret[0] = 'S'; ret[1] = '\0';
562 for (i = 0; i < state->n; i++) {
564 k = sprintf(buf, "%d%c", state->nums[i], (int)(state->dirs[i]+'a'));
566 k = sprintf(buf, "%c", (int)(state->dirs[i]+'a'));
567 ret = sresize(ret, retlen + k + 1, char);
568 strcpy(ret + retlen, buf);
574 /* --- Game generation --- */
576 /* Fills in preallocated arrays ai (indices) and ad (directions)
577 * showing all non-numbered cells adjacent to index i, returns length */
578 /* This function has been somewhat optimised... */
579 static int cell_adj(game_state *state, int i, int *ai, int *ad)
581 int n = 0, a, x, y, sx, sy, dx, dy, newi;
582 int w = state->w, h = state->h;
584 sx = i % w; sy = i / w;
586 for (a = 0; a < DIR_MAX; a++) {
588 dx = dxs[a]; dy = dys[a];
591 if (x < 0 || y < 0 || x >= w || y >= h) break;
594 if (state->nums[newi] == 0) {
604 static int new_game_fill(game_state *state, random_state *rs,
605 int headi, int taili)
607 int nfilled, an, ret = 0, j;
610 aidx = snewn(state->n, int);
611 adir = snewn(state->n, int);
613 debug(("new_game_fill: headi=%d, taili=%d.", headi, taili));
615 memset(state->nums, 0, state->n*sizeof(int));
617 state->nums[headi] = 1;
618 state->nums[taili] = state->n;
620 state->dirs[taili] = 0;
622 assert(state->n > 1);
624 while (nfilled < state->n) {
625 /* Try and expand _from_ headi; keep going if there's only one
627 an = cell_adj(state, headi, aidx, adir);
629 if (an == 0) goto done;
630 j = random_upto(rs, an);
631 state->dirs[headi] = adir[j];
632 state->nums[aidx[j]] = state->nums[headi] + 1;
635 an = cell_adj(state, headi, aidx, adir);
638 if (nfilled == state->n) break;
640 /* Try and expand _to_ taili; keep going if there's only one
642 an = cell_adj(state, taili, aidx, adir);
644 if (an == 0) goto done;
645 j = random_upto(rs, an);
646 state->dirs[aidx[j]] = DIR_OPPOSITE(adir[j]);
647 state->nums[aidx[j]] = state->nums[taili] - 1;
650 an = cell_adj(state, taili, aidx, adir);
653 /* If we get here we have headi and taili set but unconnected
654 * by direction: we need to set headi's direction so as to point
656 state->dirs[headi] = whichdiri(state, headi, taili);
658 /* it could happen that our last two weren't in line; if that's the
659 * case, we have to start again. */
660 if (state->dirs[headi] != -1) ret = 1;
668 /* Better generator: with the 'generate, sprinkle numbers, solve,
669 * repeat' algorithm we're _never_ generating anything greater than
670 * 6x6, and spending all of our time in new_game_fill (and very little
673 * So, new generator steps:
674 * generate the grid, at random (same as now). Numbers 1 and N get
675 immutable flag immediately.
676 * squirrel that away for the solved state.
678 * (solve:) Try and solve it.
679 * If we solved it, we're done:
680 * generate the description from current immutable numbers,
681 * free stuff that needs freeing,
682 * return description + solved state.
683 * If we didn't solve it:
684 * count #tiles in state we've made deductions about.
686 * randomise a scratch array.
687 * for each index in scratch (in turn):
688 * if the cell isn't empty, continue (through scratch array)
689 * set number + immutable in state.
690 * try and solve state.
691 * if we've solved it, we're done.
692 * otherwise, count #tiles. If it's more than we had before:
693 * good, break from this loop and re-randomise.
694 * otherwise (number didn't help):
695 * remove number and try next in scratch array.
696 * if we've got to the end of the scratch array, no luck:
697 free everything we need to, and go back to regenerate the grid.
700 static int solve_state(game_state *state);
702 static void debug_desc(const char *what, game_state *state)
706 char *desc = generate_desc(state, 0);
707 debug(("%s game state: %dx%d:%s", what, state->w, state->h, desc));
713 /* Expects a fully-numbered game_state on input, and makes sure
714 * FLAG_IMMUTABLE is only set on those numbers we need to solve
715 * (as for a real new-game); returns 1 if it managed
716 * this (such that it could solve it), or 0 if not. */
717 static int new_game_strip(game_state *state, random_state *rs)
719 int *scratch, i, j, ret = 1;
720 game_state *copy = dup_game(state);
722 debug(("new_game_strip."));
725 debug_desc("Stripped", copy);
727 if (solve_state(copy) > 0) {
728 debug(("new_game_strip: soluble immediately after strip."));
733 scratch = snewn(state->n, int);
734 for (i = 0; i < state->n; i++) scratch[i] = i;
735 shuffle(scratch, state->n, sizeof(int), rs);
737 /* This is scungy. It might just be quick enough.
738 * It goes through, adding set numbers in empty squares
739 * until either we run out of empty squares (in the one
740 * we're half-solving) or else we solve it properly.
741 * NB that we run the entire solver each time, which
742 * strips the grid beforehand; we will save time if we
744 for (i = 0; i < state->n; i++) {
746 if (copy->nums[j] > 0 && copy->nums[j] <= state->n)
747 continue; /* already solved to a real number here. */
748 assert(state->nums[j] <= state->n);
749 debug(("new_game_strip: testing add IMMUTABLE number %d at square (%d,%d).",
750 state->nums[j], j%state->w, j/state->w));
751 copy->nums[j] = state->nums[j];
752 copy->flags[j] |= FLAG_IMMUTABLE;
753 state->flags[j] |= FLAG_IMMUTABLE;
754 debug_state("Copy of state: ", copy);
756 if (solve_state(copy) > 0) goto solved;
757 assert(check_nums(state, copy, 1));
763 debug(("new_game_strip: now solved."));
764 /* Since we added basically at random, try now to remove numbers
765 * and see if we can still solve it; if we can (still), really
766 * remove the number. Make sure we don't remove the anchor numbers
768 for (i = 0; i < state->n; i++) {
770 if ((state->flags[j] & FLAG_IMMUTABLE) &&
771 (state->nums[j] != 1 && state->nums[j] != state->n)) {
772 debug(("new_game_strip: testing remove IMMUTABLE number %d at square (%d,%d).",
773 state->nums[j], j%state->w, j/state->w));
774 state->flags[j] &= ~FLAG_IMMUTABLE;
775 dup_game_to(copy, state);
777 if (solve_state(copy) > 0) {
778 assert(check_nums(state, copy, 0));
779 debug(("new_game_strip: OK, removing number"));
781 assert(state->nums[j] <= state->n);
782 debug(("new_game_strip: cannot solve, putting IMMUTABLE back."));
783 copy->nums[j] = state->nums[j];
784 state->flags[j] |= FLAG_IMMUTABLE;
790 debug(("new_game_strip: %ssuccessful.", ret ? "" : "not "));
796 static char *new_game_desc(const game_params *params, random_state *rs,
797 char **aux, int interactive)
799 game_state *state = blank_game(params->w, params->h);
803 /* this shouldn't happen (validate_params), but let's play it safe */
804 if (params->w == 1 && params->h == 1) return dupstr("1a");
807 blank_game_into(state);
809 /* keep trying until we fill successfully. */
811 if (params->force_corner_start) {
816 headi = random_upto(rs, state->n);
817 taili = random_upto(rs, state->n);
818 } while (headi == taili);
820 } while (!new_game_fill(state, rs, headi, taili));
822 debug_state("Filled game:", state);
824 assert(state->nums[headi] <= state->n);
825 assert(state->nums[taili] <= state->n);
827 state->flags[headi] |= FLAG_IMMUTABLE;
828 state->flags[taili] |= FLAG_IMMUTABLE;
830 /* This will have filled in directions and _all_ numbers.
831 * Store the game definition for this, as the solved-state. */
832 if (!new_game_strip(state, rs)) {
837 game_state *tosolve = dup_game(state);
838 assert(solve_state(tosolve) > 0);
841 ret = generate_desc(state, 0);
846 static char *validate_desc(const game_params *params, const char *desc)
850 unpick_desc(params, desc, NULL, &ret);
854 /* --- Linked-list and numbers array --- */
856 /* Assuming numbers are always up-to-date, there are only four possibilities
857 * for regions changing after a single valid move:
859 * 1) two differently-coloured regions being combined (the resulting colouring
860 * should be based on the larger of the two regions)
861 * 2) a numbered region having a single number added to the start (the
862 * region's colour will remain, and the numbers will shift by 1)
863 * 3) a numbered region having a single number added to the end (the
864 * region's colour and numbering remains as-is)
865 * 4) two unnumbered squares being joined (will pick the smallest unused set
866 * of colours to use for the new region).
868 * There should never be any complications with regions containing 3 colours
869 * being combined, since two of those colours should have been merged on a
872 * Most of the complications are in ensuring we don't accidentally set two
873 * regions with the same colour (e.g. if a region was split). If this happens
874 * we always try and give the largest original portion the original colour.
877 #define COLOUR(a) ((a) / (state->n+1))
878 #define START(c) ((c) * (state->n+1))
881 int i; /* position */
882 int sz; /* size of region */
883 int start; /* region start number preferred, or 0 if !preference */
884 int preference; /* 0 if we have no preference (and should just pick one) */
888 static void head_number(game_state *state, int i, struct head_meta *head)
890 int off = 0, ss, j = i, c, n, sz;
892 /* Insist we really were passed the head of a chain. */
893 assert(state->prev[i] == -1 && state->next[i] != -1);
896 head->sz = dsf_size(state->dsf, i);
899 /* Search through this chain looking for real numbers, checking that
900 * they match up (if there are more than one). */
901 head->preference = 0;
903 if (state->flags[j] & FLAG_IMMUTABLE) {
904 ss = state->nums[j] - off;
905 if (!head->preference) {
907 head->preference = 1;
908 head->why = "contains cell with immutable number";
909 } else if (head->start != ss) {
910 debug(("head_number: chain with non-sequential numbers!"));
911 state->impossible = 1;
916 assert(j != i); /* we have created a loop, obviously wrong */
918 if (head->preference) goto done;
920 if (state->nums[i] == 0 && state->nums[state->next[i]] > state->n) {
921 /* (probably) empty cell onto the head of a coloured region:
922 * make sure we start at a 0 offset. */
923 head->start = START(COLOUR(state->nums[state->next[i]]));
924 head->preference = 1;
925 head->why = "adding blank cell to head of numbered region";
926 } else if (state->nums[i] <= state->n) {
927 /* if we're 0 we're probably just blank -- but even if we're a
928 * (real) numbered region, we don't have an immutable number
929 * in it (any more) otherwise it'd have been caught above, so
930 * reassign the colour. */
932 head->preference = 0;
933 head->why = "lowest available colour group";
935 c = COLOUR(state->nums[i]);
937 sz = dsf_size(state->dsf, i);
939 while (state->next[j] != -1) {
941 if (state->nums[j] == 0 && state->next[j] == -1) {
942 head->start = START(c);
943 head->preference = 1;
944 head->why = "adding blank cell to end of numbered region";
947 if (COLOUR(state->nums[j]) == c)
950 int start_alternate = START(COLOUR(state->nums[j]));
952 head->start = start_alternate;
953 head->preference = 1;
954 head->why = "joining two coloured regions, swapping to larger colour";
956 head->start = START(c);
957 head->preference = 1;
958 head->why = "joining two coloured regions, taking largest";
963 /* If we got here then we may have split a region into
964 * two; make sure we don't assign a colour we've already used. */
966 /* not convinced this shouldn't be an assertion failure here. */
968 head->preference = 0;
970 head->start = START(c);
971 head->preference = 1;
973 head->why = "got to end of coloured region";
977 assert(head->why != NULL);
978 if (head->preference)
979 debug(("Chain at (%d,%d) numbered for preference at %d (colour %d): %s.",
980 head->i%state->w, head->i/state->w,
981 head->start, COLOUR(head->start), head->why));
983 debug(("Chain at (%d,%d) using next available colour: %s.",
984 head->i%state->w, head->i/state->w,
989 static void debug_numbers(game_state *state)
993 for (i = 0; i < state->n; i++) {
994 debug(("(%d,%d) --> (%d,%d) --> (%d,%d)",
995 state->prev[i]==-1 ? -1 : state->prev[i]%w,
996 state->prev[i]==-1 ? -1 : state->prev[i]/w,
998 state->next[i]==-1 ? -1 : state->next[i]%w,
999 state->next[i]==-1 ? -1 : state->next[i]/w));
1005 static void connect_numbers(game_state *state)
1009 dsf_init(state->dsf, state->n);
1010 for (i = 0; i < state->n; i++) {
1011 if (state->next[i] != -1) {
1012 assert(state->prev[state->next[i]] == i);
1013 di = dsf_canonify(state->dsf, i);
1014 dni = dsf_canonify(state->dsf, state->next[i]);
1016 debug(("connect_numbers: chain forms a loop."));
1017 state->impossible = 1;
1019 dsf_merge(state->dsf, di, dni);
1024 static int compare_heads(const void *a, const void *b)
1026 struct head_meta *ha = (struct head_meta *)a;
1027 struct head_meta *hb = (struct head_meta *)b;
1029 /* Heads with preferred colours first... */
1030 if (ha->preference && !hb->preference) return -1;
1031 if (hb->preference && !ha->preference) return 1;
1033 /* ...then heads with low colours first... */
1034 if (ha->start < hb->start) return -1;
1035 if (ha->start > hb->start) return 1;
1037 /* ... then large regions first... */
1038 if (ha->sz > hb->sz) return -1;
1039 if (ha->sz < hb->sz) return 1;
1041 /* ... then position. */
1042 if (ha->i > hb->i) return -1;
1043 if (ha->i < hb->i) return 1;
1048 static int lowest_start(game_state *state, struct head_meta *heads, int nheads)
1052 /* NB start at 1: colour 0 is real numbers */
1053 for (c = 1; c < state->n; c++) {
1054 for (n = 0; n < nheads; n++) {
1055 if (COLOUR(heads[n].start) == c)
1062 assert(!"No available colours!");
1066 static void update_numbers(game_state *state)
1068 int i, j, n, nnum, nheads;
1069 struct head_meta *heads = snewn(state->n, struct head_meta);
1071 for (n = 0; n < state->n; n++)
1072 state->numsi[n] = -1;
1074 for (i = 0; i < state->n; i++) {
1075 if (state->flags[i] & FLAG_IMMUTABLE) {
1076 assert(state->nums[i] > 0);
1077 assert(state->nums[i] <= state->n);
1078 state->numsi[state->nums[i]] = i;
1080 else if (state->prev[i] == -1 && state->next[i] == -1)
1083 connect_numbers(state);
1085 /* Construct an array of the heads of all current regions, together
1086 * with their preferred colours. */
1088 for (i = 0; i < state->n; i++) {
1089 /* Look for a cell that is the start of a chain
1090 * (has a next but no prev). */
1091 if (state->prev[i] != -1 || state->next[i] == -1) continue;
1093 head_number(state, i, &heads[nheads++]);
1097 * - heads with preferred colours first, then
1098 * - heads with low colours first, then
1099 * - large regions first
1101 qsort(heads, nheads, sizeof(struct head_meta), compare_heads);
1103 /* Remove duplicate-coloured regions. */
1104 for (n = nheads-1; n >= 0; n--) { /* order is important! */
1105 if ((n != 0) && (heads[n].start == heads[n-1].start)) {
1106 /* We have a duplicate-coloured region: since we're
1107 * sorted in size order and this is not the first
1108 * of its colour it's not the largest: recolour it. */
1109 heads[n].start = START(lowest_start(state, heads, nheads));
1110 heads[n].preference = -1; /* '-1' means 'was duplicate' */
1112 else if (!heads[n].preference) {
1113 assert(heads[n].start == 0);
1114 heads[n].start = START(lowest_start(state, heads, nheads));
1118 debug(("Region colouring after duplicate removal:"));
1120 for (n = 0; n < nheads; n++) {
1121 debug((" Chain at (%d,%d) sz %d numbered at %d (colour %d): %s%s",
1122 heads[n].i % state->w, heads[n].i / state->w, heads[n].sz,
1123 heads[n].start, COLOUR(heads[n].start), heads[n].why,
1124 heads[n].preference == 0 ? " (next available)" :
1125 heads[n].preference < 0 ? " (duplicate, next available)" : ""));
1127 nnum = heads[n].start;
1130 if (!(state->flags[j] & FLAG_IMMUTABLE)) {
1131 if (nnum > 0 && nnum <= state->n)
1132 state->numsi[nnum] = j;
1133 state->nums[j] = nnum;
1137 assert(j != heads[n].i); /* loop?! */
1140 /*debug_numbers(state);*/
1144 static int check_completion(game_state *state, int mark_errors)
1146 int n, j, k, error = 0, complete;
1148 /* NB This only marks errors that are possible to perpetrate with
1149 * the current UI in interpret_move. Things like forming loops in
1150 * linked sections and having numbers not add up should be forbidden
1151 * by the code elsewhere, so we don't bother marking those (because
1152 * it would add lots of tricky drawing code for very little gain). */
1154 for (j = 0; j < state->n; j++)
1155 state->flags[j] &= ~FLAG_ERROR;
1158 /* Search for repeated numbers. */
1159 for (j = 0; j < state->n; j++) {
1160 if (state->nums[j] > 0 && state->nums[j] <= state->n) {
1161 for (k = j+1; k < state->n; k++) {
1162 if (state->nums[k] == state->nums[j]) {
1164 state->flags[j] |= FLAG_ERROR;
1165 state->flags[k] |= FLAG_ERROR;
1173 /* Search and mark numbers n not pointing to n+1; if any numbers
1174 * are missing we know we've not completed. */
1176 for (n = 1; n < state->n; n++) {
1177 if (state->numsi[n] == -1 || state->numsi[n+1] == -1)
1179 else if (!ispointingi(state, state->numsi[n], state->numsi[n+1])) {
1181 state->flags[state->numsi[n]] |= FLAG_ERROR;
1182 state->flags[state->numsi[n+1]] |= FLAG_ERROR;
1186 /* make sure the link is explicitly made here; for instance, this
1187 * is nice if the user drags from 2 out (making 3) and a 4 is also
1188 * visible; this ensures that the link from 3 to 4 is also made. */
1190 makelink(state, state->numsi[n], state->numsi[n+1]);
1194 /* Search and mark numbers less than 0, or 0 with links. */
1195 for (n = 1; n < state->n; n++) {
1196 if ((state->nums[n] < 0) ||
1197 (state->nums[n] == 0 &&
1198 (state->next[n] != -1 || state->prev[n] != -1))) {
1201 state->flags[n] |= FLAG_ERROR;
1205 if (error) return 0;
1208 static game_state *new_game(midend *me, const game_params *params,
1211 game_state *state = NULL;
1213 unpick_desc(params, desc, &state, NULL);
1214 if (!state) assert(!"new_game failed to unpick");
1216 update_numbers(state);
1217 check_completion(state, 1); /* update any auto-links */
1222 /* --- Solver --- */
1224 /* If a tile has a single tile it can link _to_, or there's only a single
1225 * location that can link to a given tile, fill that link in. */
1226 static int solve_single(game_state *state, game_state *copy, int *from)
1228 int i, j, sx, sy, x, y, d, poss, w=state->w, nlinks = 0;
1230 /* The from array is a list of 'which square can link _to_ us';
1231 * we start off with from as '-1' (meaning 'not found'); if we find
1232 * something that can link to us it is set to that index, and then if
1233 * we find another we set it to -2. */
1235 memset(from, -1, state->n*sizeof(int));
1237 /* poss is 'can I link to anything' with the same meanings. */
1239 for (i = 0; i < state->n; i++) {
1240 if (state->next[i] != -1) continue;
1241 if (state->nums[i] == state->n) continue; /* no next from last no. */
1245 sx = x = i%w; sy = y = i/w;
1247 x += dxs[d]; y += dys[d];
1248 if (!INGRID(state, x, y)) break;
1249 if (!isvalidmove(state, 1, sx, sy, x, y)) continue;
1251 /* can't link to somewhere with a back-link we would have to
1252 * break (the solver just doesn't work like this). */
1254 if (state->prev[j] != -1) continue;
1256 if (state->nums[i] > 0 && state->nums[j] > 0 &&
1257 state->nums[i] <= state->n && state->nums[j] <= state->n &&
1258 state->nums[j] == state->nums[i]+1) {
1259 debug(("Solver: forcing link through existing consecutive numbers."));
1265 /* if there's been a valid move already, we have to move on;
1266 * we can't make any deductions here. */
1267 poss = (poss == -1) ? j : -2;
1269 /* Modify the from array as described above (which is enumerating
1270 * what points to 'j' in a similar way). */
1271 from[j] = (from[j] == -1) ? i : -2;
1274 /*debug(("Solver: (%d,%d) has multiple possible next squares.", sx, sy));*/
1276 } else if (poss == -1) {
1277 debug(("Solver: nowhere possible for (%d,%d) to link to.", sx, sy));
1278 copy->impossible = 1;
1281 debug(("Solver: linking (%d,%d) to only possible next (%d,%d).",
1282 sx, sy, poss%w, poss/w));
1283 makelink(copy, i, poss);
1288 for (i = 0; i < state->n; i++) {
1289 if (state->prev[i] != -1) continue;
1290 if (state->nums[i] == 1) continue; /* no prev from 1st no. */
1293 if (from[i] == -1) {
1294 debug(("Solver: nowhere possible to link to (%d,%d)", x, y));
1295 copy->impossible = 1;
1297 } else if (from[i] == -2) {
1298 /*debug(("Solver: (%d,%d) has multiple possible prev squares.", x, y));*/
1301 debug(("Solver: linking only possible prev (%d,%d) to (%d,%d).",
1302 from[i]%w, from[i]/w, x, y));
1303 makelink(copy, from[i], i);
1311 /* Returns 1 if we managed to solve it, 0 otherwise. */
1312 static int solve_state(game_state *state)
1314 game_state *copy = dup_game(state);
1315 int *scratch = snewn(state->n, int), ret;
1317 debug_state("Before solver: ", state);
1320 update_numbers(state);
1322 if (solve_single(state, copy, scratch)) {
1323 dup_game_to(state, copy);
1324 if (state->impossible) break; else continue;
1331 update_numbers(state);
1332 ret = state->impossible ? -1 : check_completion(state, 0);
1333 debug(("Solver finished: %s",
1334 ret < 0 ? "impossible" : ret > 0 ? "solved" : "not solved"));
1335 debug_state("After solver: ", state);
1339 static char *solve_game(const game_state *state, const game_state *currstate,
1340 const char *aux, char **error)
1342 game_state *tosolve;
1346 tosolve = dup_game(currstate);
1347 result = solve_state(tosolve);
1349 ret = generate_desc(tosolve, 1);
1351 if (ret) return ret;
1353 tosolve = dup_game(state);
1354 result = solve_state(tosolve);
1356 *error = "Puzzle is impossible.";
1357 else if (result == 0)
1358 *error = "Unable to solve puzzle.";
1360 ret = generate_desc(tosolve, 1);
1367 /* --- UI and move routines. --- */
1373 int dragging, drag_is_from;
1374 int sx, sy; /* grid coords of start cell */
1375 int dx, dy; /* pixel coords of drag posn */
1378 static game_ui *new_ui(const game_state *state)
1380 game_ui *ui = snew(game_ui);
1382 /* NB: if this is ever changed to as to require more than a structure
1383 * copy to clone, there's code that needs fixing in game_redraw too. */
1385 ui->cx = ui->cy = ui->cshow = 0;
1388 ui->sx = ui->sy = ui->dx = ui->dy = 0;
1393 static void free_ui(game_ui *ui)
1398 static char *encode_ui(const game_ui *ui)
1403 static void decode_ui(game_ui *ui, const char *encoding)
1407 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1408 const game_state *newstate)
1410 if (!oldstate->completed && newstate->completed)
1411 ui->cshow = ui->dragging = 0;
1414 struct game_drawstate {
1415 int tilesize, started, solved;
1419 double angle_offset;
1421 int dragging, dx, dy;
1425 static char *interpret_move(const game_state *state, game_ui *ui,
1426 const game_drawstate *ds,
1427 int mx, int my, int button)
1429 int x = FROMCOORD(mx), y = FROMCOORD(my), w = state->w;
1432 if (IS_CURSOR_MOVE(button)) {
1433 move_cursor(button, &ui->cx, &ui->cy, state->w, state->h, 0);
1436 ui->dx = COORD(ui->cx) + TILE_SIZE/2;
1437 ui->dy = COORD(ui->cy) + TILE_SIZE/2;
1440 } else if (IS_CURSOR_SELECT(button)) {
1443 else if (ui->dragging) {
1444 ui->dragging = FALSE;
1445 if (ui->sx == ui->cx && ui->sy == ui->cy) return UI_UPDATE;
1446 if (ui->drag_is_from) {
1447 if (!isvalidmove(state, 0, ui->sx, ui->sy, ui->cx, ui->cy))
1449 sprintf(buf, "L%d,%d-%d,%d", ui->sx, ui->sy, ui->cx, ui->cy);
1451 if (!isvalidmove(state, 0, ui->cx, ui->cy, ui->sx, ui->sy))
1453 sprintf(buf, "L%d,%d-%d,%d", ui->cx, ui->cy, ui->sx, ui->sy);
1457 ui->dragging = TRUE;
1460 ui->dx = COORD(ui->cx) + TILE_SIZE/2;
1461 ui->dy = COORD(ui->cy) + TILE_SIZE/2;
1462 ui->drag_is_from = (button == CURSOR_SELECT) ? 1 : 0;
1466 if (IS_MOUSE_DOWN(button)) {
1468 ui->cshow = ui->dragging = 0;
1470 assert(!ui->dragging);
1471 if (!INGRID(state, x, y)) return NULL;
1473 if (button == LEFT_BUTTON) {
1474 /* disallow dragging from the final number. */
1475 if ((state->nums[y*w+x] == state->n) &&
1476 (state->flags[y*w+x] & FLAG_IMMUTABLE))
1478 } else if (button == RIGHT_BUTTON) {
1479 /* disallow dragging to the first number. */
1480 if ((state->nums[y*w+x] == 1) &&
1481 (state->flags[y*w+x] & FLAG_IMMUTABLE))
1485 ui->dragging = TRUE;
1486 ui->drag_is_from = (button == LEFT_BUTTON) ? 1 : 0;
1493 } else if (IS_MOUSE_DRAG(button) && ui->dragging) {
1497 } else if (IS_MOUSE_RELEASE(button) && ui->dragging) {
1498 ui->dragging = FALSE;
1499 if (ui->sx == x && ui->sy == y) return UI_UPDATE; /* single click */
1501 if (!INGRID(state, x, y)) {
1502 int si = ui->sy*w+ui->sx;
1503 if (state->prev[si] == -1 && state->next[si] == -1)
1505 sprintf(buf, "%c%d,%d",
1506 (int)(ui->drag_is_from ? 'C' : 'X'), ui->sx, ui->sy);
1510 if (ui->drag_is_from) {
1511 if (!isvalidmove(state, 0, ui->sx, ui->sy, x, y))
1513 sprintf(buf, "L%d,%d-%d,%d", ui->sx, ui->sy, x, y);
1515 if (!isvalidmove(state, 0, x, y, ui->sx, ui->sy))
1517 sprintf(buf, "L%d,%d-%d,%d", x, y, ui->sx, ui->sy);
1520 } /* else if (button == 'H' || button == 'h')
1521 return dupstr("H"); */
1522 else if ((button == 'x' || button == 'X') && ui->cshow) {
1523 int si = ui->cy*w + ui->cx;
1524 if (state->prev[si] == -1 && state->next[si] == -1)
1526 sprintf(buf, "%c%d,%d",
1527 (int)((button == 'x') ? 'C' : 'X'), ui->cx, ui->cy);
1534 static void unlink_cell(game_state *state, int si)
1536 debug(("Unlinking (%d,%d).", si%state->w, si/state->w));
1537 if (state->prev[si] != -1) {
1538 debug((" ... removing prev link from (%d,%d).",
1539 state->prev[si]%state->w, state->prev[si]/state->w));
1540 state->next[state->prev[si]] = -1;
1541 state->prev[si] = -1;
1543 if (state->next[si] != -1) {
1544 debug((" ... removing next link to (%d,%d).",
1545 state->next[si]%state->w, state->next[si]/state->w));
1546 state->prev[state->next[si]] = -1;
1547 state->next[si] = -1;
1551 static game_state *execute_move(const game_state *state, const char *move)
1553 game_state *ret = NULL;
1554 int sx, sy, ex, ey, si, ei, w = state->w;
1557 debug(("move: %s", move));
1559 if (move[0] == 'S') {
1565 p.w = state->w; p.h = state->h;
1566 valid = validate_desc(&p, move+1);
1568 debug(("execute_move: move not valid: %s", valid));
1571 ret = dup_game(state);
1572 tmp = new_game(NULL, &p, move+1);
1573 for (i = 0; i < state->n; i++) {
1574 ret->prev[i] = tmp->prev[i];
1575 ret->next[i] = tmp->next[i];
1578 ret->used_solve = 1;
1579 } else if (sscanf(move, "L%d,%d-%d,%d", &sx, &sy, &ex, &ey) == 4) {
1580 if (!isvalidmove(state, 0, sx, sy, ex, ey)) return NULL;
1582 ret = dup_game(state);
1584 si = sy*w+sx; ei = ey*w+ex;
1585 makelink(ret, si, ei);
1586 } else if (sscanf(move, "%c%d,%d", &c, &sx, &sy) == 3) {
1589 if (c != 'C' && c != 'X') return NULL;
1590 if (!INGRID(state, sx, sy)) return NULL;
1592 if (state->prev[si] == -1 && state->next[si] == -1)
1595 ret = dup_game(state);
1597 sset = state->nums[si] / (state->n+1);
1598 if (c == 'C' || (c == 'X' && sset == 0)) {
1599 /* Unlink the single cell we dragged from the board. */
1600 unlink_cell(ret, si);
1603 for (i = 0; i < state->n; i++) {
1604 /* Unlink all cells in the same set as the one we dragged
1605 * from the board. */
1607 if (state->nums[i] == 0) continue;
1608 set = state->nums[i] / (state->n+1);
1609 if (set != sset) continue;
1611 unlink_cell(ret, i);
1614 } else if (strcmp(move, "H") == 0) {
1615 ret = dup_game(state);
1619 update_numbers(ret);
1620 if (check_completion(ret, 1)) ret->completed = 1;
1626 /* ----------------------------------------------------------------------
1630 static void game_compute_size(const game_params *params, int tilesize,
1633 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1634 struct { int tilesize, order; } ads, *ds = &ads;
1635 ads.tilesize = tilesize;
1637 *x = TILE_SIZE * params->w + 2 * BORDER;
1638 *y = TILE_SIZE * params->h + 2 * BORDER;
1641 static void game_set_size(drawing *dr, game_drawstate *ds,
1642 const game_params *params, int tilesize)
1644 ds->tilesize = tilesize;
1645 assert(TILE_SIZE > 0);
1648 ds->dragb = blitter_new(dr, BLITTER_SIZE, BLITTER_SIZE);
1651 /* Colours chosen from the webby palette to work as a background to black text,
1652 * W then some plausible approximation to pastelly ROYGBIV; we then interpolate
1653 * between consecutive pairs to give another 8 (and then the drawing routine
1654 * will reuse backgrounds). */
1655 static const unsigned long bgcols[8] = {
1656 0xffffff, /* white */
1657 0xffa07a, /* lightsalmon */
1658 0x98fb98, /* green */
1659 0x7fffd4, /* aquamarine */
1660 0x9370db, /* medium purple */
1661 0xffa500, /* orange */
1662 0x87cefa, /* lightskyblue */
1663 0xffff00, /* yellow */
1666 static float *game_colours(frontend *fe, int *ncolours)
1668 float *ret = snewn(3 * NCOLOURS, float);
1671 game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
1673 for (i = 0; i < 3; i++) {
1674 ret[COL_NUMBER * 3 + i] = 0.0F;
1675 ret[COL_ARROW * 3 + i] = 0.0F;
1676 ret[COL_CURSOR * 3 + i] = ret[COL_BACKGROUND * 3 + i] / 2.0F;
1677 ret[COL_GRID * 3 + i] = ret[COL_BACKGROUND * 3 + i] / 1.3F;
1679 ret[COL_NUMBER_SET * 3 + 0] = 0.0F;
1680 ret[COL_NUMBER_SET * 3 + 1] = 0.0F;
1681 ret[COL_NUMBER_SET * 3 + 2] = 0.9F;
1683 ret[COL_ERROR * 3 + 0] = 1.0F;
1684 ret[COL_ERROR * 3 + 1] = 0.0F;
1685 ret[COL_ERROR * 3 + 2] = 0.0F;
1687 ret[COL_DRAG_ORIGIN * 3 + 0] = 0.2F;
1688 ret[COL_DRAG_ORIGIN * 3 + 1] = 1.0F;
1689 ret[COL_DRAG_ORIGIN * 3 + 2] = 0.2F;
1691 for (c = 0; c < 8; c++) {
1692 ret[(COL_B0 + c) * 3 + 0] = (float)((bgcols[c] & 0xff0000) >> 16) / 256.0F;
1693 ret[(COL_B0 + c) * 3 + 1] = (float)((bgcols[c] & 0xff00) >> 8) / 256.0F;
1694 ret[(COL_B0 + c) * 3 + 2] = (float)((bgcols[c] & 0xff)) / 256.0F;
1696 for (c = 0; c < 8; c++) {
1697 for (i = 0; i < 3; i++) {
1698 ret[(COL_B0 + 8 + c) * 3 + i] =
1699 (ret[(COL_B0 + c) * 3 + i] + ret[(COL_B0 + c + 1) * 3 + i]) / 2.0F;
1703 #define average(r,a,b,w) do { \
1704 for (i = 0; i < 3; i++) \
1705 ret[(r)*3+i] = ret[(a)*3+i] + w * (ret[(b)*3+i] - ret[(a)*3+i]); \
1707 average(COL_ARROW_BG_DIM, COL_BACKGROUND, COL_ARROW, 0.1F);
1708 average(COL_NUMBER_SET_MID, COL_B0, COL_NUMBER_SET, 0.3F);
1709 for (c = 0; c < NBACKGROUNDS; c++) {
1710 /* I assume here that COL_ARROW and COL_NUMBER are the same.
1711 * Otherwise I'd need two sets of COL_M*. */
1712 average(COL_M0 + c, COL_B0 + c, COL_NUMBER, 0.3F);
1713 average(COL_D0 + c, COL_B0 + c, COL_NUMBER, 0.1F);
1714 average(COL_X0 + c, COL_BACKGROUND, COL_B0 + c, 0.5F);
1717 *ncolours = NCOLOURS;
1721 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1723 struct game_drawstate *ds = snew(struct game_drawstate);
1726 ds->tilesize = ds->started = ds->solved = 0;
1731 ds->nums = snewn(state->n, int);
1732 ds->dirp = snewn(state->n, int);
1733 ds->f = snewn(state->n, unsigned int);
1734 for (i = 0; i < state->n; i++) {
1740 ds->angle_offset = 0.0F;
1742 ds->dragging = ds->dx = ds->dy = 0;
1748 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1753 if (ds->dragb) blitter_free(dr, ds->dragb);
1758 /* cx, cy are top-left corner. sz is the 'radius' of the arrow.
1759 * ang is in radians, clockwise from 0 == straight up. */
1760 static void draw_arrow(drawing *dr, int cx, int cy, int sz, double ang,
1761 int cfill, int cout)
1764 int xdx, ydx, xdy, ydy, xdx3, xdy3;
1765 double s = sin(ang), c = cos(ang);
1767 xdx3 = (int)(sz * (c/3 + 1) + 0.5) - sz;
1768 xdy3 = (int)(sz * (s/3 + 1) + 0.5) - sz;
1769 xdx = (int)(sz * (c + 1) + 0.5) - sz;
1770 xdy = (int)(sz * (s + 1) + 0.5) - sz;
1775 coords[2*0 + 0] = cx - ydx;
1776 coords[2*0 + 1] = cy - ydy;
1777 coords[2*1 + 0] = cx + xdx;
1778 coords[2*1 + 1] = cy + xdy;
1779 coords[2*2 + 0] = cx + xdx3;
1780 coords[2*2 + 1] = cy + xdy3;
1781 coords[2*3 + 0] = cx + xdx3 + ydx;
1782 coords[2*3 + 1] = cy + xdy3 + ydy;
1783 coords[2*4 + 0] = cx - xdx3 + ydx;
1784 coords[2*4 + 1] = cy - xdy3 + ydy;
1785 coords[2*5 + 0] = cx - xdx3;
1786 coords[2*5 + 1] = cy - xdy3;
1787 coords[2*6 + 0] = cx - xdx;
1788 coords[2*6 + 1] = cy - xdy;
1790 draw_polygon(dr, coords, 7, cfill, cout);
1793 static void draw_arrow_dir(drawing *dr, int cx, int cy, int sz, int dir,
1794 int cfill, int cout, double angle_offset)
1796 double ang = 2.0 * PI * (double)dir / 8.0 + angle_offset;
1797 draw_arrow(dr, cx, cy, sz, ang, cfill, cout);
1800 /* cx, cy are centre coordinates.. */
1801 static void draw_star(drawing *dr, int cx, int cy, int rad, int npoints,
1802 int cfill, int cout, double angle_offset)
1807 assert(npoints > 0);
1809 coords = snewn(npoints * 2 * 2, int);
1811 for (n = 0; n < npoints * 2; n++) {
1812 a = 2.0 * PI * ((double)n / ((double)npoints * 2.0)) + angle_offset;
1813 r = (n % 2) ? (double)rad/2.0 : (double)rad;
1815 /* We're rotating the point at (0, -r) by a degrees */
1816 coords[2*n+0] = cx + (int)( r * sin(a));
1817 coords[2*n+1] = cy + (int)(-r * cos(a));
1819 draw_polygon(dr, coords, npoints*2, cfill, cout);
1823 static int num2col(game_drawstate *ds, int num)
1825 int set = num / (ds->n+1);
1827 if (num <= 0 || set == 0) return COL_B0;
1828 return COL_B0 + 1 + ((set-1) % 15);
1831 #define ARROW_HALFSZ (7 * TILE_SIZE / 32)
1833 #define F_CUR 0x001 /* Cursor on this tile. */
1834 #define F_DRAG_SRC 0x002 /* Tile is source of a drag. */
1835 #define F_ERROR 0x004 /* Tile marked in error. */
1836 #define F_IMMUTABLE 0x008 /* Tile (number) is immutable. */
1837 #define F_ARROW_POINT 0x010 /* Tile points to other tile */
1838 #define F_ARROW_INPOINT 0x020 /* Other tile points in here. */
1839 #define F_DIM 0x040 /* Tile is dim */
1841 static void tile_redraw(drawing *dr, game_drawstate *ds, int tx, int ty,
1842 int dir, int dirp, int num, unsigned int f,
1843 double angle_offset, int print_ink)
1845 int cb = TILE_SIZE / 16, textsz;
1847 int arrowcol, sarrowcol, setcol, textcol;
1848 int acx, acy, asz, empty = 0;
1850 if (num == 0 && !(f & F_ARROW_POINT) && !(f & F_ARROW_INPOINT)) {
1853 * We don't display text in empty cells: typically these are
1854 * signified by num=0. However, in some cases a cell could
1855 * have had the number 0 assigned to it if the user made an
1856 * error (e.g. tried to connect a chain of length 5 to the
1857 * immutable number 4) so we _do_ display the 0 if the cell
1858 * has a link in or a link out.
1862 /* Calculate colours. */
1864 if (print_ink >= 0) {
1866 * We're printing, so just do everything in black.
1868 arrowcol = textcol = print_ink;
1869 setcol = sarrowcol = -1; /* placate optimiser */
1872 setcol = empty ? COL_BACKGROUND : num2col(ds, num);
1874 #define dim(fg,bg) ( \
1875 (bg)==COL_BACKGROUND ? COL_ARROW_BG_DIM : \
1876 (bg) + COL_D0 - COL_B0 \
1879 #define mid(fg,bg) ( \
1880 (fg)==COL_NUMBER_SET ? COL_NUMBER_SET_MID : \
1881 (bg) + COL_M0 - COL_B0 \
1884 #define dimbg(bg) ( \
1885 (bg)==COL_BACKGROUND ? COL_BACKGROUND : \
1886 (bg) + COL_X0 - COL_B0 \
1889 if (f & F_DRAG_SRC) arrowcol = COL_DRAG_ORIGIN;
1890 else if (f & F_DIM) arrowcol = dim(COL_ARROW, setcol);
1891 else if (f & F_ARROW_POINT) arrowcol = mid(COL_ARROW, setcol);
1892 else arrowcol = COL_ARROW;
1894 if ((f & F_ERROR) && !(f & F_IMMUTABLE)) textcol = COL_ERROR;
1896 if (f & F_IMMUTABLE) textcol = COL_NUMBER_SET;
1897 else textcol = COL_NUMBER;
1899 if (f & F_DIM) textcol = dim(textcol, setcol);
1900 else if (((f & F_ARROW_POINT) || num==ds->n) &&
1901 ((f & F_ARROW_INPOINT) || num==1))
1902 textcol = mid(textcol, setcol);
1905 if (f & F_DIM) sarrowcol = dim(COL_ARROW, setcol);
1906 else sarrowcol = COL_ARROW;
1909 /* Clear tile background */
1911 if (print_ink < 0) {
1912 draw_rect(dr, tx, ty, TILE_SIZE, TILE_SIZE,
1913 (f & F_DIM) ? dimbg(setcol) : setcol);
1916 /* Draw large (outwards-pointing) arrow. */
1918 asz = ARROW_HALFSZ; /* 'radius' of arrow/star. */
1919 acx = tx+TILE_SIZE/2+asz; /* centre x */
1920 acy = ty+TILE_SIZE/2+asz; /* centre y */
1922 if (num == ds->n && (f & F_IMMUTABLE))
1923 draw_star(dr, acx, acy, asz, 5, arrowcol, arrowcol, angle_offset);
1925 draw_arrow_dir(dr, acx, acy, asz, dir, arrowcol, arrowcol, angle_offset);
1926 if (print_ink < 0 && (f & F_CUR))
1927 draw_rect_corners(dr, acx, acy, asz+1, COL_CURSOR);
1929 /* Draw dot iff this tile requires a predecessor and doesn't have one. */
1931 if (print_ink < 0) {
1932 acx = tx+TILE_SIZE/2-asz;
1933 acy = ty+TILE_SIZE/2+asz;
1935 if (!(f & F_ARROW_INPOINT) && num != 1) {
1936 draw_circle(dr, acx, acy, asz / 4, sarrowcol, sarrowcol);
1940 /* Draw text (number or set). */
1943 int set = (num <= 0) ? 0 : num / (ds->n+1);
1946 if (set == 0 || num <= 0) {
1947 sprintf(buf, "%d", num);
1949 int n = num % (ds->n+1);
1950 p += sizeof(buf) - 1;
1953 sprintf(buf, "+%d", n); /* Just to get the length... */
1955 sprintf(p, "+%d", n);
1962 *p = (char)((set % 26)+'a');
1966 textsz = min(2*asz, (TILE_SIZE - 2 * cb) / (int)strlen(p));
1967 draw_text(dr, tx + cb, ty + TILE_SIZE/4, FONT_VARIABLE, textsz,
1968 ALIGN_VCENTRE | ALIGN_HLEFT, textcol, p);
1971 if (print_ink < 0) {
1972 draw_rect_outline(dr, tx, ty, TILE_SIZE, TILE_SIZE, COL_GRID);
1973 draw_update(dr, tx, ty, TILE_SIZE, TILE_SIZE);
1977 static void draw_drag_indicator(drawing *dr, game_drawstate *ds,
1978 const game_state *state, const game_ui *ui,
1981 int dir, w = ds->w, acol = COL_ARROW;
1982 int fx = FROMCOORD(ui->dx), fy = FROMCOORD(ui->dy);
1986 /* If we could move here, lock the arrow to the appropriate direction. */
1987 dir = ui->drag_is_from ? state->dirs[ui->sy*w+ui->sx] : state->dirs[fy*w+fx];
1989 ang = (2.0 * PI * dir) / 8.0; /* similar to calculation in draw_arrow_dir. */
1991 /* Draw an arrow pointing away from/towards the origin cell. */
1992 int ox = COORD(ui->sx) + TILE_SIZE/2, oy = COORD(ui->sy) + TILE_SIZE/2;
1993 double tana, offset;
1994 double xdiff = abs(ox - ui->dx), ydiff = abs(oy - ui->dy);
1997 ang = (oy > ui->dy) ? 0.0F : PI;
1998 } else if (ydiff == 0) {
1999 ang = (ox > ui->dx) ? 3.0F*PI/2.0F : PI/2.0F;
2001 if (ui->dx > ox && ui->dy < oy) {
2002 tana = xdiff / ydiff;
2004 } else if (ui->dx > ox && ui->dy > oy) {
2005 tana = ydiff / xdiff;
2007 } else if (ui->dx < ox && ui->dy > oy) {
2008 tana = xdiff / ydiff;
2011 tana = ydiff / xdiff;
2012 offset = 3.0F * PI / 2.0F;
2014 ang = atan(tana) + offset;
2017 if (!ui->drag_is_from) ang += PI; /* point to origin, not away from. */
2020 draw_arrow(dr, ui->dx, ui->dy, ARROW_HALFSZ, ang, acol, acol);
2023 static void game_redraw(drawing *dr, game_drawstate *ds,
2024 const game_state *oldstate, const game_state *state,
2025 int dir, const game_ui *ui,
2026 float animtime, float flashtime)
2028 int x, y, i, w = ds->w, dirp, force = 0;
2030 double angle_offset = 0.0;
2031 game_state *postdrop = NULL;
2033 if (flashtime > 0.0F)
2034 angle_offset = 2.0 * PI * (flashtime / FLASH_SPIN);
2035 if (angle_offset != ds->angle_offset) {
2036 ds->angle_offset = angle_offset;
2042 blitter_load(dr, ds->dragb, ds->dx, ds->dy);
2043 draw_update(dr, ds->dx, ds->dy, BLITTER_SIZE, BLITTER_SIZE);
2044 ds->dragging = FALSE;
2047 /* If an in-progress drag would make a valid move if finished, we
2048 * reflect that move in the board display. We let interpret_move do
2049 * most of the heavy lifting for us: we have to copy the game_ui so
2050 * as not to stomp on the real UI's drag state. */
2052 game_ui uicopy = *ui;
2053 char *movestr = interpret_move(state, &uicopy, ds, ui->dx, ui->dy, LEFT_RELEASE);
2055 if (movestr != NULL && strcmp(movestr, "") != 0) {
2056 postdrop = execute_move(state, movestr);
2064 int aw = TILE_SIZE * state->w;
2065 int ah = TILE_SIZE * state->h;
2066 draw_rect(dr, 0, 0, aw + 2 * BORDER, ah + 2 * BORDER, COL_BACKGROUND);
2067 draw_rect_outline(dr, BORDER - 1, BORDER - 1, aw + 2, ah + 2, COL_GRID);
2068 draw_update(dr, 0, 0, aw + 2 * BORDER, ah + 2 * BORDER);
2070 for (x = 0; x < state->w; x++) {
2071 for (y = 0; y < state->h; y++) {
2076 if (ui->cshow && x == ui->cx && y == ui->cy)
2080 if (x == ui->sx && y == ui->sy)
2082 else if (ui->drag_is_from) {
2083 if (!ispointing(state, ui->sx, ui->sy, x, y))
2086 if (!ispointing(state, x, y, ui->sx, ui->sy))
2091 if (state->impossible ||
2092 state->nums[i] < 0 || state->flags[i] & FLAG_ERROR)
2094 if (state->flags[i] & FLAG_IMMUTABLE)
2097 if (state->next[i] != -1)
2100 if (state->prev[i] != -1) {
2101 /* Currently the direction here is from our square _back_
2102 * to its previous. We could change this to give the opposite
2103 * sense to the direction. */
2104 f |= F_ARROW_INPOINT;
2105 dirp = whichdir(x, y, state->prev[i]%w, state->prev[i]/w);
2108 if (state->nums[i] != ds->nums[i] ||
2109 f != ds->f[i] || dirp != ds->dirp[i] ||
2110 force || !ds->started) {
2114 * Trivial and foolish configurable option done on
2115 * purest whim. With this option enabled, the
2116 * victory flash is done by rotating each square
2117 * in the opposite direction from its immediate
2118 * neighbours, so that they behave like a field of
2119 * interlocking gears. With it disabled, they all
2120 * rotate in the same direction. Choose for
2121 * yourself which is more brain-twisting :-)
2123 static int gear_mode = -1;
2124 if (gear_mode < 0) {
2125 char *env = getenv("SIGNPOST_GEARS");
2126 gear_mode = (env && (env[0] == 'y' || env[0] == 'Y'));
2129 sign = 1 - 2 * ((x ^ y) & 1);
2134 BORDER + x * TILE_SIZE,
2135 BORDER + y * TILE_SIZE,
2136 state->dirs[i], dirp, state->nums[i], f,
2137 sign * angle_offset, -1);
2138 ds->nums[i] = state->nums[i];
2145 ds->dragging = TRUE;
2146 ds->dx = ui->dx - BLITTER_SIZE/2;
2147 ds->dy = ui->dy - BLITTER_SIZE/2;
2148 blitter_save(dr, ds->dragb, ds->dx, ds->dy);
2150 draw_drag_indicator(dr, ds, state, ui, postdrop ? 1 : 0);
2152 if (postdrop) free_game(postdrop);
2153 if (!ds->started) ds->started = TRUE;
2156 static float game_anim_length(const game_state *oldstate,
2157 const game_state *newstate, int dir, game_ui *ui)
2162 static float game_flash_length(const game_state *oldstate,
2163 const game_state *newstate, int dir, game_ui *ui)
2165 if (!oldstate->completed &&
2166 newstate->completed && !newstate->used_solve)
2172 static int game_status(const game_state *state)
2174 return state->completed ? +1 : 0;
2177 static int game_timing_state(const game_state *state, game_ui *ui)
2182 static void game_print_size(const game_params *params, float *x, float *y)
2186 game_compute_size(params, 1300, &pw, &ph);
2191 static void game_print(drawing *dr, const game_state *state, int tilesize)
2193 int ink = print_mono_colour(dr, 0);
2196 /* Fake up just enough of a drawstate */
2197 game_drawstate ads, *ds = &ads;
2198 ds->tilesize = tilesize;
2204 print_line_width(dr, TILE_SIZE / 40);
2205 for (x = 1; x < state->w; x++)
2206 draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(state->h), ink);
2207 for (y = 1; y < state->h; y++)
2208 draw_line(dr, COORD(0), COORD(y), COORD(state->w), COORD(y), ink);
2209 print_line_width(dr, 2*TILE_SIZE / 40);
2210 draw_rect_outline(dr, COORD(0), COORD(0), TILE_SIZE*state->w,
2211 TILE_SIZE*state->h, ink);
2214 * Arrows and numbers.
2216 print_line_width(dr, 0);
2217 for (y = 0; y < state->h; y++)
2218 for (x = 0; x < state->w; x++)
2219 tile_redraw(dr, ds, COORD(x), COORD(y), state->dirs[y*state->w+x],
2220 0, state->nums[y*state->w+x], 0, 0.0, ink);
2224 #define thegame signpost
2227 const struct game thegame = {
2228 "Signpost", "games.signpost", "signpost",
2230 game_fetch_preset, NULL,
2235 TRUE, game_configure, custom_params,
2243 TRUE, game_can_format_as_text_now, game_text_format,
2251 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2254 game_free_drawstate,
2259 TRUE, FALSE, game_print_size, game_print,
2260 FALSE, /* wants_statusbar */
2261 FALSE, game_timing_state,
2262 REQUIRE_RBUTTON, /* flags */
2265 #ifdef STANDALONE_SOLVER
2270 const char *quis = NULL;
2273 void usage(FILE *out) {
2274 fprintf(out, "usage: %s [--stdin] [--soak] [--seed SEED] <params>|<game id>\n", quis);
2277 static void cycle_seed(char **seedstr, random_state *rs)
2283 newseed[0] = '1' + (char)random_upto(rs, 9);
2284 for (j = 1; j < 15; j++)
2285 newseed[j] = '0' + (char)random_upto(rs, 10);
2287 *seedstr = dupstr(newseed);
2290 static void start_soak(game_params *p, char *seedstr)
2292 time_t tt_start, tt_now, tt_last;
2295 long n = 0, nnums = 0, i;
2298 tt_start = tt_now = time(NULL);
2299 printf("Soak-generating a %dx%d grid.\n", p->w, p->h);
2302 rs = random_new(seedstr, strlen(seedstr));
2303 desc = thegame.new_desc(p, rs, &aux, 0);
2305 state = thegame.new_game(NULL, p, desc);
2306 for (i = 0; i < state->n; i++) {
2307 if (state->flags[i] & FLAG_IMMUTABLE)
2310 thegame.free_game(state);
2313 cycle_seed(&seedstr, rs);
2317 tt_last = time(NULL);
2318 if (tt_last > tt_now) {
2320 printf("%ld total, %3.1f/s, %3.1f nums/grid (%3.1f%%).\n",
2322 (double)n / ((double)tt_now - tt_start),
2323 (double)nnums / (double)n,
2324 ((double)nnums * 100.0) / ((double)n * (double)p->w * (double)p->h) );
2329 static void process_desc(char *id)
2331 char *desc, *err, *solvestr;
2335 printf("%s\n ", id);
2337 desc = strchr(id, ':');
2339 fprintf(stderr, "%s: expecting game description.", quis);
2345 p = thegame.default_params();
2346 thegame.decode_params(p, id);
2347 err = thegame.validate_params(p, 1);
2349 fprintf(stderr, "%s: %s", quis, err);
2350 thegame.free_params(p);
2354 err = thegame.validate_desc(p, desc);
2356 fprintf(stderr, "%s: %s\nDescription: %s\n", quis, err, desc);
2357 thegame.free_params(p);
2361 s = thegame.new_game(NULL, p, desc);
2363 solvestr = thegame.solve(s, s, NULL, &err);
2365 fprintf(stderr, "%s\n", err);
2367 printf("Puzzle is soluble.\n");
2369 thegame.free_game(s);
2370 thegame.free_params(p);
2373 int main(int argc, const char *argv[])
2375 char *id = NULL, *desc, *err, *aux = NULL;
2376 int soak = 0, verbose = 0, stdin_desc = 0, n = 1, i;
2377 char *seedstr = NULL, newseed[16];
2379 setvbuf(stdout, NULL, _IONBF, 0);
2382 while (--argc > 0) {
2383 char *p = (char*)(*++argv);
2384 if (!strcmp(p, "-v") || !strcmp(p, "--verbose"))
2386 else if (!strcmp(p, "--stdin"))
2388 else if (!strcmp(p, "-e") || !strcmp(p, "--seed")) {
2389 seedstr = dupstr(*++argv);
2391 } else if (!strcmp(p, "-n") || !strcmp(p, "--number")) {
2394 } else if (!strcmp(p, "-s") || !strcmp(p, "--soak")) {
2396 } else if (*p == '-') {
2397 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2405 sprintf(newseed, "%lu", (unsigned long) time(NULL));
2406 seedstr = dupstr(newseed);
2408 if (id || !stdin_desc) {
2409 if (id && strchr(id, ':')) {
2410 /* Parameters and description passed on cmd-line:
2411 * try and solve it. */
2414 /* No description passed on cmd-line: decode parameters
2415 * (with optional seed too) */
2417 game_params *p = thegame.default_params();
2420 char *cmdseed = strchr(id, '#');
2424 seedstr = dupstr(cmdseed);
2427 thegame.decode_params(p, id);
2430 err = thegame.validate_params(p, 1);
2432 fprintf(stderr, "%s: %s", quis, err);
2433 thegame.free_params(p);
2437 /* We have a set of valid parameters; either soak with it
2438 * or generate a single game description and print to stdout. */
2440 start_soak(p, seedstr);
2442 char *pstring = thegame.encode_params(p, 0);
2444 for (i = 0; i < n; i++) {
2445 random_state *rs = random_new(seedstr, strlen(seedstr));
2447 if (verbose) printf("%s#%s\n", pstring, seedstr);
2448 desc = thegame.new_desc(p, rs, &aux, 0);
2449 printf("%s:%s\n", pstring, desc);
2452 cycle_seed(&seedstr, rs);
2459 thegame.free_params(p);
2466 while (fgets(buf, sizeof(buf), stdin)) {
2467 buf[strcspn(buf, "\r\n")] = '\0';
2479 /* vim: set shiftwidth=4 tabstop=8: */