Add '-v' option to patternsolver, to make it show its working.
[sgt/puzzles] / signpost.c
CommitLineData
4cbcbfca 1/*
2 * signpost.c: implementation of the janko game 'arrow path'
4cbcbfca 3 */
4
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8#include <assert.h>
9#include <ctype.h>
10#include <math.h>
11
12#include "puzzles.h"
13
14#define PREFERRED_TILE_SIZE 48
15#define TILE_SIZE (ds->tilesize)
16#define BLITTER_SIZE TILE_SIZE
17#define BORDER (TILE_SIZE / 2)
18
19#define COORD(x) ( (x) * TILE_SIZE + BORDER )
20#define FROMCOORD(x) ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
21
22#define INGRID(s,x,y) ((x) >= 0 && (x) < (s)->w && (y) >= 0 && (y) < (s)->h)
23
24#define FLASH_SPIN 0.7F
25
26#define NBACKGROUNDS 16
27
28enum {
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
38};
39
40struct game_params {
41 int w, h;
42 int force_corner_start;
43};
44
45enum { DIR_N = 0, DIR_NE, DIR_E, DIR_SE, DIR_S, DIR_SW, DIR_W, DIR_NW, DIR_MAX };
46static const char *dirstrings[8] = { "N ", "NE", "E ", "SE", "S ", "SW", "W ", "NW" };
47
48static const int dxs[DIR_MAX] = { 0, 1, 1, 1, 0, -1, -1, -1 };
49static const int dys[DIR_MAX] = { -1, -1, 0, 1, 1, 1, 0, -1 };
50
51#define DIR_OPPOSITE(d) ((d+4)%8)
52
53struct game_state {
54 int w, h, n;
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) */
62};
63
64#define FLAG_IMMUTABLE 1
65#define FLAG_ERROR 2
66
67/* --- Generally useful functions --- */
68
69#define ISREALNUM(state, num) ((num) > 0 && (num) <= (state)->n)
70
71static int whichdir(int fromx, int fromy, int tox, int toy)
72{
73 int i, dx, dy;
74
75 dx = tox - fromx;
76 dy = toy - fromy;
77
78 if (dx && dy && abs(dx) != abs(dy)) return -1;
79
80 if (dx) dx = dx / abs(dx); /* limit to (-1, 0, 1) */
81 if (dy) dy = dy / abs(dy); /* ditto */
82
83 for (i = 0; i < DIR_MAX; i++) {
84 if (dx == dxs[i] && dy == dys[i]) return i;
85 }
86 return -1;
87}
88
89static int whichdiri(game_state *state, int fromi, int toi)
90{
91 int w = state->w;
92 return whichdir(fromi%w, fromi/w, toi%w, toi/w);
93}
94
95static int ispointing(game_state *state, int fromx, int fromy, int tox, int toy)
96{
97 int w = state->w, dir = state->dirs[fromy*w+fromx];
98
99 /* (by convention) squares do not point to themselves. */
100 if (fromx == tox && fromy == toy) return 0;
101
102 /* the final number points to nothing. */
103 if (state->nums[fromy*w + fromx] == state->n) return 0;
104
105 while (1) {
106 if (!INGRID(state, fromx, fromy)) return 0;
107 if (fromx == tox && fromy == toy) return 1;
108 fromx += dxs[dir]; fromy += dys[dir];
109 }
110 return 0; /* not reached */
111}
112
113static int ispointingi(game_state *state, int fromi, int toi)
114{
115 int w = state->w;
116 return ispointing(state, fromi%w, fromi/w, toi%w, toi/w);
117}
118
119/* Taking the number 'num', work out the gap between it and the next
120 * available number up or down (depending on d). Return 1 if the region
121 * at (x,y) will fit in that gap, or 0 otherwise. */
122static int move_couldfit(game_state *state, int num, int d, int x, int y)
123{
124 int n, gap, i = y*state->w+x, sz;
125
126 assert(d != 0);
127 /* The 'gap' is the number of missing numbers in the grid between
128 * our number and the next one in the sequence (up or down), or
129 * the end of the sequence (if we happen not to have 1/n present) */
130 for (n = num + d, gap = 0;
131 ISREALNUM(state, n) && state->numsi[n] == -1;
132 n += d, gap++) ; /* empty loop */
133
134 if (gap == 0) {
135 /* no gap, so the only allowable move is that that directly
136 * links the two numbers. */
137 n = state->nums[i];
138 return (n == num+d) ? 0 : 1;
139 }
140 if (state->prev[i] == -1 && state->next[i] == -1)
141 return 1; /* single unconnected square, always OK */
142
143 sz = dsf_size(state->dsf, i);
144 return (sz > gap) ? 0 : 1;
145}
146
147static int isvalidmove(game_state *state, int clever,
148 int fromx, int fromy, int tox, int toy)
149{
150 int w = state->w, from = fromy*w+fromx, to = toy*w+tox;
151 int nfrom, nto;
152
153 if (!INGRID(state, fromx, fromy) || !INGRID(state, tox, toy))
154 return 0;
155
156 /* can only move where we point */
157 if (!ispointing(state, fromx, fromy, tox, toy))
158 return 0;
159
160 nfrom = state->nums[from]; nto = state->nums[to];
161
51990f54 162 /* can't move _from_ the preset final number, or _to_ the preset 1. */
163 if (((nfrom == state->n) && (state->flags[from] & FLAG_IMMUTABLE)) ||
164 ((nto == 1) && (state->flags[to] & FLAG_IMMUTABLE)))
4cbcbfca 165 return 0;
166
167 /* can't create a new connection between cells in the same region
168 * as that would create a loop. */
169 if (dsf_canonify(state->dsf, from) == dsf_canonify(state->dsf, to))
170 return 0;
171
172 /* if both cells are actual numbers, can't drag if we're not
173 * one digit apart. */
174 if (ISREALNUM(state, nfrom) && ISREALNUM(state, nto)) {
175 if (nfrom != nto-1)
176 return 0;
177 } else if (clever && ISREALNUM(state, nfrom)) {
178 if (!move_couldfit(state, nfrom, +1, tox, toy))
179 return 0;
180 } else if (clever && ISREALNUM(state, nto)) {
181 if (!move_couldfit(state, nto, -1, fromx, fromy))
182 return 0;
183 }
184
185 return 1;
186}
187
188static void makelink(game_state *state, int from, int to)
189{
190 if (state->next[from] != -1)
191 state->prev[state->next[from]] = -1;
192 state->next[from] = to;
193
194 if (state->prev[to] != -1)
195 state->next[state->prev[to]] = -1;
196 state->prev[to] = from;
197}
198
199static int game_can_format_as_text_now(game_params *params)
200{
201 if (params->w * params->h >= 100) return 0;
202 return 1;
203}
204
205static char *game_text_format(game_state *state)
206{
207 int len = state->h * 2 * (4*state->w + 1) + state->h + 2;
208 int x, y, i, num, n, set;
209 char *ret, *p;
210
211 p = ret = snewn(len, char);
212
213 for (y = 0; y < state->h; y++) {
214 for (x = 0; x < state->h; x++) {
215 i = y*state->w+x;
216 *p++ = dirstrings[state->dirs[i]][0];
217 *p++ = dirstrings[state->dirs[i]][1];
218 *p++ = (state->flags[i] & FLAG_IMMUTABLE) ? 'I' : ' ';
219 *p++ = ' ';
220 }
221 *p++ = '\n';
222 for (x = 0; x < state->h; x++) {
223 i = y*state->w+x;
224 num = state->nums[i];
225 if (num == 0) {
226 *p++ = ' ';
227 *p++ = ' ';
228 *p++ = ' ';
229 } else {
230 n = num % (state->n+1);
231 set = num / (state->n+1);
232
233 assert(n <= 99); /* two digits only! */
234
235 if (set != 0)
236 *p++ = set+'a'-1;
237
238 *p++ = (n >= 10) ? ('0' + (n/10)) : ' ';
239 *p++ = '0' + (n%10);
240
241 if (set == 0)
242 *p++ = ' ';
243 }
244 *p++ = ' ';
245 }
246 *p++ = '\n';
247 *p++ = '\n';
248 }
249 *p++ = '\0';
250
251 return ret;
252}
253
254static void debug_state(const char *desc, game_state *state)
255{
256#ifdef DEBUGGING
257 char *dbg;
258 if (state->n >= 100) {
259 debug(("[ no game_text_format for this size ]"));
260 return;
261 }
262 dbg = game_text_format(state);
263 debug(("%s\n%s", desc, dbg));
264 sfree(dbg);
265#endif
266}
267
268
269static void strip_nums(game_state *state) {
270 int i;
271 for (i = 0; i < state->n; i++) {
272 if (!(state->flags[i] & FLAG_IMMUTABLE))
273 state->nums[i] = 0;
274 }
275 memset(state->next, -1, state->n*sizeof(int));
276 memset(state->prev, -1, state->n*sizeof(int));
277 memset(state->numsi, -1, (state->n+1)*sizeof(int));
278 dsf_init(state->dsf, state->n);
279}
280
281static int check_nums(game_state *orig, game_state *copy, int only_immutable)
282{
283 int i, ret = 1;
284 assert(copy->n == orig->n);
285 for (i = 0; i < copy->n; i++) {
286 if (only_immutable && !copy->flags[i] & FLAG_IMMUTABLE) continue;
287 assert(copy->nums[i] >= 0);
288 assert(copy->nums[i] <= copy->n);
289 if (copy->nums[i] != orig->nums[i]) {
290 debug(("check_nums: (%d,%d) copy=%d, orig=%d.",
291 i%orig->w, i/orig->w, copy->nums[i], orig->nums[i]));
292 ret = 0;
293 }
294 }
295 return ret;
296}
297
298/* --- Game parameter/presets functions --- */
299
300static game_params *default_params(void)
301{
302 game_params *ret = snew(game_params);
303 ret->w = ret->h = 4;
304 ret->force_corner_start = 1;
305
306 return ret;
307}
308
309static const struct game_params signpost_presets[] = {
310 { 4, 4, 1 },
311 { 4, 4, 0 },
312 { 5, 5, 1 },
313 { 5, 5, 0 },
314 { 6, 6, 1 },
315 { 7, 7, 1 }
316};
317
318static int game_fetch_preset(int i, char **name, game_params **params)
319{
320 game_params *ret;
321 char buf[80];
322
323 if (i < 0 || i >= lenof(signpost_presets))
324 return FALSE;
325
326 ret = default_params();
327 *ret = signpost_presets[i];
328 *params = ret;
329
330 sprintf(buf, "%dx%d%s", ret->w, ret->h,
331 ret->force_corner_start ? "" : ", free ends");
332 *name = dupstr(buf);
333
334 return TRUE;
335}
336
337static void free_params(game_params *params)
338{
339 sfree(params);
340}
341
342static game_params *dup_params(game_params *params)
343{
344 game_params *ret = snew(game_params);
345 *ret = *params; /* structure copy */
346 return ret;
347}
348
349static void decode_params(game_params *ret, char const *string)
350{
351 ret->w = ret->h = atoi(string);
352 while (*string && isdigit((unsigned char)*string)) string++;
353 if (*string == 'x') {
354 string++;
355 ret->h = atoi(string);
356 while (*string && isdigit((unsigned char)*string)) string++;
357 }
358 ret->force_corner_start = 0;
359 if (*string == 'c') {
360 string++;
361 ret->force_corner_start = 1;
362 }
363
364}
365
366static char *encode_params(game_params *params, int full)
367{
368 char data[256];
369
370 if (full)
371 sprintf(data, "%dx%d%s", params->w, params->h,
372 params->force_corner_start ? "c" : "");
373 else
374 sprintf(data, "%dx%d", params->w, params->h);
375
376 return dupstr(data);
377}
378
379static config_item *game_configure(game_params *params)
380{
381 config_item *ret;
382 char buf[80];
383
384 ret = snewn(4, config_item);
385
386 ret[0].name = "Width";
387 ret[0].type = C_STRING;
388 sprintf(buf, "%d", params->w);
389 ret[0].sval = dupstr(buf);
390 ret[0].ival = 0;
391
392 ret[1].name = "Height";
393 ret[1].type = C_STRING;
394 sprintf(buf, "%d", params->h);
395 ret[1].sval = dupstr(buf);
396 ret[1].ival = 0;
397
398 ret[2].name = "Start and end in corners";
399 ret[2].type = C_BOOLEAN;
400 ret[2].sval = NULL;
401 ret[2].ival = params->force_corner_start;
402
403 ret[3].name = NULL;
404 ret[3].type = C_END;
405 ret[3].sval = NULL;
406 ret[3].ival = 0;
407
408 return ret;
409}
410
411static game_params *custom_params(config_item *cfg)
412{
413 game_params *ret = snew(game_params);
414
415 ret->w = atoi(cfg[0].sval);
416 ret->h = atoi(cfg[1].sval);
417 ret->force_corner_start = cfg[2].ival;
418
419 return ret;
420}
421
422static char *validate_params(game_params *params, int full)
423{
424 if (params->w < 2 || params->h < 2)
425 return "Width and height must both be at least two";
f43cb411 426 if (params->w == 2 && params->h == 2) /* leads to generation hang */
427 return "Width and height cannot both be two";
4cbcbfca 428
429 return NULL;
430}
431
432/* --- Game description string generation and unpicking --- */
433
434static void blank_game_into(game_state *state)
435{
436 memset(state->dirs, 0, state->n*sizeof(int));
437 memset(state->nums, 0, state->n*sizeof(int));
438 memset(state->flags, 0, state->n*sizeof(unsigned int));
439 memset(state->next, -1, state->n*sizeof(int));
440 memset(state->prev, -1, state->n*sizeof(int));
441 memset(state->numsi, -1, (state->n+1)*sizeof(int));
442}
443
444static game_state *blank_game(int w, int h)
445{
446 game_state *state = snew(game_state);
447
448 memset(state, 0, sizeof(game_state));
449 state->w = w;
450 state->h = h;
451 state->n = w*h;
452
453 state->dirs = snewn(state->n, int);
454 state->nums = snewn(state->n, int);
455 state->flags = snewn(state->n, unsigned int);
456 state->next = snewn(state->n, int);
457 state->prev = snewn(state->n, int);
458 state->dsf = snew_dsf(state->n);
459 state->numsi = snewn(state->n+1, int);
460
461 blank_game_into(state);
462
463 return state;
464}
465
466static void dup_game_to(game_state *to, game_state *from)
467{
468 to->completed = from->completed;
469 to->used_solve = from->used_solve;
470 to->impossible = from->impossible;
471
472 memcpy(to->dirs, from->dirs, to->n*sizeof(int));
473 memcpy(to->flags, from->flags, to->n*sizeof(unsigned int));
474 memcpy(to->nums, from->nums, to->n*sizeof(int));
475
476 memcpy(to->next, from->next, to->n*sizeof(int));
477 memcpy(to->prev, from->prev, to->n*sizeof(int));
478
479 memcpy(to->dsf, from->dsf, to->n*sizeof(int));
480 memcpy(to->numsi, from->numsi, (to->n+1)*sizeof(int));
481}
482
483static game_state *dup_game(game_state *state)
484{
485 game_state *ret = blank_game(state->w, state->h);
486 dup_game_to(ret, state);
487 return ret;
488}
489
490static void free_game(game_state *state)
491{
492 sfree(state->dirs);
493 sfree(state->nums);
494 sfree(state->flags);
495 sfree(state->next);
496 sfree(state->prev);
497 sfree(state->dsf);
498 sfree(state->numsi);
499 sfree(state);
500}
501
502static void unpick_desc(game_params *params, char *desc,
503 game_state **sout, char **mout)
504{
505 game_state *state = blank_game(params->w, params->h);
506 char *msg = NULL, c;
507 int num = 0, i = 0;
508
509 while (*desc) {
510 if (i >= state->n) {
511 msg = "Game description longer than expected";
512 goto done;
513 }
514
515 c = *desc;
516 if (isdigit(c)) {
517 num = (num*10) + (int)(c-'0');
518 if (num > state->n) {
519 msg = "Number too large";
520 goto done;
521 }
522 } else if ((c-'a') >= 0 && (c-'a') < DIR_MAX) {
523 state->nums[i] = num;
524 state->flags[i] = num ? FLAG_IMMUTABLE : 0;
525 num = 0;
526
527 state->dirs[i] = c - 'a';
528 i++;
529 } else if (!*desc) {
530 msg = "Game description shorter than expected";
531 goto done;
532 } else {
533 msg = "Game description contains unexpected characters";
534 goto done;
535 }
536 desc++;
537 }
538 if (i < state->n) {
539 msg = "Game description shorter than expected";
540 goto done;
541 }
542
543done:
544 if (msg) { /* sth went wrong. */
545 if (mout) *mout = msg;
546 free_game(state);
547 } else {
548 if (mout) *mout = NULL;
549 if (sout) *sout = state;
550 else free_game(state);
551 }
552}
553
554static char *generate_desc(game_state *state, int issolve)
555{
556 char *ret, buf[80];
557 int retlen, i, k;
558
559 ret = NULL; retlen = 0;
560 if (issolve) {
561 ret = sresize(ret, 2, char);
562 ret[0] = 'S'; ret[1] = '\0';
563 retlen += 1;
564 }
565 for (i = 0; i < state->n; i++) {
566 if (state->nums[i])
567 k = sprintf(buf, "%d%c", state->nums[i], (int)(state->dirs[i]+'a'));
568 else
569 k = sprintf(buf, "%c", (int)(state->dirs[i]+'a'));
570 ret = sresize(ret, retlen + k + 1, char);
571 strcpy(ret + retlen, buf);
572 retlen += k;
573 }
574 return ret;
575}
576
577/* --- Game generation --- */
578
579/* Fills in preallocated arrays ai (indices) and ad (directions)
580 * showing all non-numbered cells adjacent to index i, returns length */
581/* This function has been somewhat optimised... */
582static int cell_adj(game_state *state, int i, int *ai, int *ad)
583{
584 int n = 0, a, x, y, sx, sy, dx, dy, newi;
585 int w = state->w, h = state->h;
586
587 sx = i % w; sy = i / w;
588
589 for (a = 0; a < DIR_MAX; a++) {
590 x = sx; y = sy;
591 dx = dxs[a]; dy = dys[a];
592 while (1) {
593 x += dx; y += dy;
594 if (x < 0 || y < 0 || x >= w || y >= h) break;
595
596 newi = y*w + x;
597 if (state->nums[newi] == 0) {
598 ai[n] = newi;
599 ad[n] = a;
600 n++;
601 }
602 }
603 }
604 return n;
605}
606
607static int new_game_fill(game_state *state, random_state *rs,
608 int headi, int taili)
609{
610 int nfilled, an, ret = 0, j;
611 int *aidx, *adir;
612
613 aidx = snewn(state->n, int);
614 adir = snewn(state->n, int);
615
616 debug(("new_game_fill: headi=%d, taili=%d.", headi, taili));
617
618 memset(state->nums, 0, state->n*sizeof(int));
619
620 state->nums[headi] = 1;
621 state->nums[taili] = state->n;
622
623 state->dirs[taili] = 0;
624 nfilled = 2;
625
626 while (nfilled < state->n) {
627 /* Try and expand _from_ headi; keep going if there's only one
628 * place to go to. */
629 an = cell_adj(state, headi, aidx, adir);
630 do {
631 if (an == 0) goto done;
632 j = random_upto(rs, an);
633 state->dirs[headi] = adir[j];
634 state->nums[aidx[j]] = state->nums[headi] + 1;
635 nfilled++;
636 headi = aidx[j];
637 an = cell_adj(state, headi, aidx, adir);
638 } while (an == 1);
639
640 /* Try and expand _to_ taili; keep going if there's only one
641 * place to go to. */
642 an = cell_adj(state, taili, aidx, adir);
643 do {
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;
648 nfilled++;
649 taili = aidx[j];
650 an = cell_adj(state, taili, aidx, adir);
651 } while (an == 1);
652 }
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
655 * at taili. */
656 state->dirs[headi] = whichdiri(state, headi, taili);
657
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;
661
662done:
663 sfree(aidx);
664 sfree(adir);
665 return ret;
666}
667
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
671 * in solve_state).
672 *
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.
677 *
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.
685 * while (1):
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.
698 */
699
700static int solve_state(game_state *state);
701
702static void debug_desc(const char *what, game_state *state)
703{
704#if DEBUGGING
705 {
706 char *desc = generate_desc(state, 0);
707 debug(("%s game state: %dx%d:%s", what, state->w, state->h, desc));
708 sfree(desc);
709 }
710#endif
711}
712
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. */
717static int new_game_strip(game_state *state, random_state *rs)
718{
719 int *scratch, i, j, ret = 1;
720 game_state *copy = dup_game(state);
721
722 debug(("new_game_strip."));
723
724 strip_nums(copy);
725 debug_desc("Stripped", copy);
726
727 if (solve_state(copy) > 0) {
728 debug(("new_game_strip: soluble immediately after strip."));
729 free_game(copy);
730 return 1;
731 }
732
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);
736
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
743 * avoid that. */
744 for (i = 0; i < state->n; i++) {
745 j = scratch[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);
755 if (solve_state(copy) > 0) goto solved;
756 assert(check_nums(state, copy, 1));
757 }
758 ret = 0;
759 goto done;
760
761solved:
762 debug(("new_game_strip: now solved."));
763 /* Since we added basically at random, try now to remove numbers
764 * and see if we can still solve it; if we can (still), really
765 * remove the number. Make sure we don't remove the anchor numbers
766 * 1 and N. */
767 for (i = 0; i < state->n; i++) {
768 j = scratch[i];
769 if ((state->flags[j] & FLAG_IMMUTABLE) &&
770 (state->nums[j] != 1 && state->nums[j] != state->n)) {
771 debug(("new_game_strip: testing remove IMMUTABLE number %d at square (%d,%d).",
772 state->nums[j], j%state->w, j/state->w));
773 state->flags[j] &= ~FLAG_IMMUTABLE;
774 dup_game_to(copy, state);
775 strip_nums(copy);
776 if (solve_state(copy) > 0) {
777 assert(check_nums(state, copy, 0));
778 debug(("new_game_strip: OK, removing number"));
779 } else {
780 assert(state->nums[j] <= state->n);
781 debug(("new_game_strip: cannot solve, putting IMMUTABLE back."));
782 copy->nums[j] = state->nums[j];
783 state->flags[j] |= FLAG_IMMUTABLE;
784 }
785 }
786 }
787
788done:
789 debug(("new_game_strip: %ssuccessful.", ret ? "" : "not "));
790 sfree(scratch);
791 free_game(copy);
792 return ret;
793}
794
795static char *new_game_desc(game_params *params, random_state *rs,
796 char **aux, int interactive)
797{
798 game_state *state = blank_game(params->w, params->h);
799 char *ret;
800 int headi, taili;
801
802generate:
803 blank_game_into(state);
804
805 /* keep trying until we fill successfully. */
806 do {
807 if (params->force_corner_start) {
808 headi = 0;
809 taili = state->n-1;
810 } else {
811 do {
812 headi = random_upto(rs, state->n);
813 taili = random_upto(rs, state->n);
814 } while (headi == taili);
815 }
816 } while (!new_game_fill(state, rs, headi, taili));
817
818 debug_state("Filled game:", state);
819
820 assert(state->nums[headi] <= state->n);
821 assert(state->nums[taili] <= state->n);
822
823 state->flags[headi] |= FLAG_IMMUTABLE;
824 state->flags[taili] |= FLAG_IMMUTABLE;
825
826 /* This will have filled in directions and _all_ numbers.
827 * Store the game definition for this, as the solved-state. */
828 if (!new_game_strip(state, rs)) {
829 goto generate;
830 }
831 strip_nums(state);
832 {
833 game_state *tosolve = dup_game(state);
834 assert(solve_state(tosolve) > 0);
835 free_game(tosolve);
836 }
837 ret = generate_desc(state, 0);
838 free_game(state);
839 return ret;
840}
841
842static char *validate_desc(game_params *params, char *desc)
843{
844 char *ret = NULL;
845
846 unpick_desc(params, desc, NULL, &ret);
847 return ret;
848}
849
850/* --- Linked-list and numbers array --- */
851
852/* Assuming numbers are always up-to-date, there are only four possibilities
51990f54 853 * for regions changing after a single valid move:
4cbcbfca 854 *
855 * 1) two differently-coloured regions being combined (the resulting colouring
856 * should be based on the larger of the two regions)
857 * 2) a numbered region having a single number added to the start (the
858 * region's colour will remain, and the numbers will shift by 1)
859 * 3) a numbered region having a single number added to the end (the
860 * region's colour and numbering remains as-is)
861 * 4) two unnumbered squares being joined (will pick the smallest unused set
862 * of colours to use for the new region).
863 *
864 * There should never be any complications with regions containing 3 colours
865 * being combined, since two of those colours should have been merged on a
866 * previous move.
4cbcbfca 867 *
51990f54 868 * Most of the complications are in ensuring we don't accidentally set two
869 * regions with the same colour (e.g. if a region was split). If this happens
870 * we always try and give the largest original portion the original colour.
4cbcbfca 871 */
872
873#define COLOUR(a) ((a) / (state->n+1))
874#define START(c) ((c) * (state->n+1))
875
51990f54 876struct head_meta {
877 int i; /* position */
878 int sz; /* size of region */
879 int start; /* region start number preferred, or 0 if !preference */
880 int preference; /* 0 if we have no preference (and should just pick one) */
881 const char *why;
882};
4cbcbfca 883
51990f54 884static void head_number(game_state *state, int i, struct head_meta *head)
4cbcbfca 885{
51990f54 886 int off = 0, ss, j = i, c, n, sz;
4cbcbfca 887
51990f54 888 /* Insist we really were passed the head of a chain. */
4cbcbfca 889 assert(state->prev[i] == -1 && state->next[i] != -1);
890
51990f54 891 head->i = i;
892 head->sz = dsf_size(state->dsf, i);
893 head->why = NULL;
894
4cbcbfca 895 /* Search through this chain looking for real numbers, checking that
896 * they match up (if there are more than one). */
51990f54 897 head->preference = 0;
4cbcbfca 898 while (j != -1) {
899 if (state->flags[j] & FLAG_IMMUTABLE) {
900 ss = state->nums[j] - off;
51990f54 901 if (!head->preference) {
902 head->start = ss;
903 head->preference = 1;
904 head->why = "contains cell with immutable number";
905 } else if (head->start != ss) {
33c2bb47 906 debug(("head_number: chain with non-sequential numbers!"));
4cbcbfca 907 state->impossible = 1;
908 }
909 }
910 off++;
911 j = state->next[j];
912 assert(j != i); /* we have created a loop, obviously wrong */
913 }
51990f54 914 if (head->preference) goto done;
915
916 if (state->nums[i] == 0 && state->nums[state->next[i]] > state->n) {
917 /* (probably) empty cell onto the head of a coloured region:
918 * make sure we start at a 0 offset. */
919 head->start = START(COLOUR(state->nums[state->next[i]]));
920 head->preference = 1;
921 head->why = "adding blank cell to head of numbered region";
922 } else if (state->nums[i] <= state->n) {
923 /* if we're 0 we're probably just blank -- but even if we're a
924 * (real) numbered region, we don't have an immutable number
925 * in it (any more) otherwise it'd have been caught above, so
926 * reassign the colour. */
927 head->start = 0;
928 head->preference = 0;
929 head->why = "lowest available colour group";
4cbcbfca 930 } else {
931 c = COLOUR(state->nums[i]);
932 n = 1;
933 sz = dsf_size(state->dsf, i);
934 j = i;
935 while (state->next[j] != -1) {
936 j = state->next[j];
51990f54 937 if (state->nums[j] == 0 && state->next[j] == -1) {
938 head->start = START(c);
939 head->preference = 1;
940 head->why = "adding blank cell to end of numbered region";
941 goto done;
4cbcbfca 942 }
943 if (COLOUR(state->nums[j]) == c)
944 n++;
945 else {
946 int start_alternate = START(COLOUR(state->nums[j]));
51990f54 947 if (n < (sz - n)) {
948 head->start = start_alternate;
949 head->preference = 1;
950 head->why = "joining two coloured regions, swapping to larger colour";
4cbcbfca 951 } else {
51990f54 952 head->start = START(c);
953 head->preference = 1;
954 head->why = "joining two coloured regions, taking largest";
4cbcbfca 955 }
51990f54 956 goto done;
4cbcbfca 957 }
958 }
959 /* If we got here then we may have split a region into
960 * two; make sure we don't assign a colour we've already used. */
51990f54 961 if (c == 0) {
962 /* not convinced this shouldn't be an assertion failure here. */
963 head->start = 0;
964 head->preference = 0;
965 } else {
966 head->start = START(c);
967 head->preference = 1;
4cbcbfca 968 }
51990f54 969 head->why = "got to end of coloured region";
4cbcbfca 970 }
971
33c2bb47 972done:
51990f54 973 assert(head->why != NULL);
974 if (head->preference)
975 debug(("Chain at (%d,%d) numbered for preference at %d (colour %d): %s.",
976 head->i%state->w, head->i/state->w,
977 head->start, COLOUR(head->start), head->why));
978 else
979 debug(("Chain at (%d,%d) using next available colour: %s.",
980 head->i%state->w, head->i/state->w,
981 head->why));
4cbcbfca 982}
983
984#if 0
985static void debug_numbers(game_state *state)
986{
987 int i, w=state->w;
988
989 for (i = 0; i < state->n; i++) {
990 debug(("(%d,%d) --> (%d,%d) --> (%d,%d)",
991 state->prev[i]==-1 ? -1 : state->prev[i]%w,
992 state->prev[i]==-1 ? -1 : state->prev[i]/w,
993 i%w, i/w,
994 state->next[i]==-1 ? -1 : state->next[i]%w,
995 state->next[i]==-1 ? -1 : state->next[i]/w));
996 }
997 w = w+1;
998}
999#endif
1000
1001static void connect_numbers(game_state *state)
1002{
1003 int i, di, dni;
1004
1005 dsf_init(state->dsf, state->n);
1006 for (i = 0; i < state->n; i++) {
1007 if (state->next[i] != -1) {
1008 assert(state->prev[state->next[i]] == i);
1009 di = dsf_canonify(state->dsf, i);
1010 dni = dsf_canonify(state->dsf, state->next[i]);
1011 if (di == dni) {
1012 debug(("connect_numbers: chain forms a loop."));
1013 state->impossible = 1;
1014 }
1015 dsf_merge(state->dsf, di, dni);
1016 }
1017 }
1018}
1019
51990f54 1020static int compare_heads(const void *a, const void *b)
1021{
1022 struct head_meta *ha = (struct head_meta *)a;
1023 struct head_meta *hb = (struct head_meta *)b;
1024
1025 /* Heads with preferred colours first... */
1026 if (ha->preference && !hb->preference) return -1;
1027 if (hb->preference && !ha->preference) return 1;
1028
1029 /* ...then heads with low colours first... */
1030 if (ha->start < hb->start) return -1;
1031 if (ha->start > hb->start) return 1;
1032
1033 /* ... then large regions first... */
1034 if (ha->sz > hb->sz) return -1;
1035 if (ha->sz < hb->sz) return 1;
1036
1037 /* ... then position. */
1038 if (ha->i > hb->i) return -1;
1039 if (ha->i < hb->i) return 1;
1040
1041 return 0;
1042}
1043
1044static int lowest_start(game_state *state, struct head_meta *heads, int nheads)
1045{
1046 int n, c;
1047
1048 /* NB start at 1: colour 0 is real numbers */
1049 for (c = 1; c < state->n; c++) {
1050 for (n = 0; n < nheads; n++) {
1051 if (COLOUR(heads[n].start) == c)
1052 goto used;
1053 }
1054 return c;
1055used:
1056 ;
1057 }
1058 assert(!"No available colours!");
1059 return 0;
1060}
1061
4cbcbfca 1062static void update_numbers(game_state *state)
1063{
51990f54 1064 int i, j, n, nnum, nheads;
1065 struct head_meta *heads = snewn(state->n, struct head_meta);
4cbcbfca 1066
51990f54 1067 for (n = 0; n < state->n; n++)
1068 state->numsi[n] = -1;
4cbcbfca 1069
1070 for (i = 0; i < state->n; i++) {
1071 if (state->flags[i] & FLAG_IMMUTABLE) {
51990f54 1072 assert(state->nums[i] > 0);
4cbcbfca 1073 assert(state->nums[i] <= state->n);
1074 state->numsi[state->nums[i]] = i;
1075 }
1076 else if (state->prev[i] == -1 && state->next[i] == -1)
1077 state->nums[i] = 0;
1078 }
1079 connect_numbers(state);
1080
51990f54 1081 /* Construct an array of the heads of all current regions, together
1082 * with their preferred colours. */
1083 nheads = 0;
4cbcbfca 1084 for (i = 0; i < state->n; i++) {
1085 /* Look for a cell that is the start of a chain
1086 * (has a next but no prev). */
1087 if (state->prev[i] != -1 || state->next[i] == -1) continue;
1088
51990f54 1089 head_number(state, i, &heads[nheads++]);
1090 }
1091
1092 /* Sort that array:
1093 * - heads with preferred colours first, then
1094 * - heads with low colours first, then
1095 * - large regions first
1096 */
1097 qsort(heads, nheads, sizeof(struct head_meta), compare_heads);
1098
1099 /* Remove duplicate-coloured regions. */
1100 for (n = nheads-1; n >= 0; n--) { /* order is important! */
1101 if ((n != 0) && (heads[n].start == heads[n-1].start)) {
1102 /* We have a duplicate-coloured region: since we're
1103 * sorted in size order and this is not the first
1104 * of its colour it's not the largest: recolour it. */
1105 heads[n].start = START(lowest_start(state, heads, nheads));
1106 heads[n].preference = -1; /* '-1' means 'was duplicate' */
1107 }
1108 else if (!heads[n].preference) {
1109 assert(heads[n].start == 0);
1110 heads[n].start = START(lowest_start(state, heads, nheads));
1111 }
1112 }
1113
1114 debug(("Region colouring after duplicate removal:"));
1115
1116 for (n = 0; n < nheads; n++) {
1117 debug((" Chain at (%d,%d) sz %d numbered at %d (colour %d): %s%s",
1118 heads[n].i % state->w, heads[n].i / state->w, heads[n].sz,
1119 heads[n].start, COLOUR(heads[n].start), heads[n].why,
1120 heads[n].preference == 0 ? " (next available)" :
1121 heads[n].preference < 0 ? " (duplicate, next available)" : ""));
1122
1123 nnum = heads[n].start;
1124 j = heads[n].i;
4cbcbfca 1125 while (j != -1) {
51990f54 1126 if (!(state->flags[j] & FLAG_IMMUTABLE)) {
1127 if (nnum > 0 && nnum <= state->n)
1128 state->numsi[nnum] = j;
1129 state->nums[j] = nnum;
1130 }
1131 nnum++;
4cbcbfca 1132 j = state->next[j];
51990f54 1133 assert(j != heads[n].i); /* loop?! */
4cbcbfca 1134 }
1135 }
1136 /*debug_numbers(state);*/
51990f54 1137 sfree(heads);
4cbcbfca 1138}
1139
1140static int check_completion(game_state *state, int mark_errors)
1141{
1142 int n, j, k, error = 0, complete;
1143
1144 /* NB This only marks errors that are possible to perpetrate with
1145 * the current UI in interpret_move. Things like forming loops in
1146 * linked sections and having numbers not add up should be forbidden
1147 * by the code elsewhere, so we don't bother marking those (because
1148 * it would add lots of tricky drawing code for very little gain). */
1149 if (mark_errors) {
1150 for (j = 0; j < state->n; j++)
1151 state->flags[j] &= ~FLAG_ERROR;
1152 }
1153
1154 /* Search for repeated numbers. */
1155 for (j = 0; j < state->n; j++) {
1156 if (state->nums[j] > 0 && state->nums[j] <= state->n) {
1157 for (k = j+1; k < state->n; k++) {
1158 if (state->nums[k] == state->nums[j]) {
1159 if (mark_errors) {
1160 state->flags[j] |= FLAG_ERROR;
1161 state->flags[k] |= FLAG_ERROR;
1162 }
1163 error = 1;
1164 }
1165 }
1166 }
1167 }
1168
1169 /* Search and mark numbers n not pointing to n+1; if any numbers
1170 * are missing we know we've not completed. */
1171 complete = 1;
1172 for (n = 1; n < state->n; n++) {
1173 if (state->numsi[n] == -1 || state->numsi[n+1] == -1)
1174 complete = 0;
1175 else if (!ispointingi(state, state->numsi[n], state->numsi[n+1])) {
1176 if (mark_errors) {
1177 state->flags[state->numsi[n]] |= FLAG_ERROR;
1178 state->flags[state->numsi[n+1]] |= FLAG_ERROR;
1179 }
1180 error = 1;
1181 } else {
1182 /* make sure the link is explicitly made here; for instance, this
1183 * is nice if the user drags from 2 out (making 3) and a 4 is also
1184 * visible; this ensures that the link from 3 to 4 is also made. */
1185 if (mark_errors)
1186 makelink(state, state->numsi[n], state->numsi[n+1]);
1187 }
1188 }
1189
33c2bb47 1190 /* Search and mark numbers less than 0, or 0 with links. */
1191 for (n = 1; n < state->n; n++) {
1192 if ((state->nums[n] < 0) ||
1193 (state->nums[n] == 0 &&
1194 (state->next[n] != -1 || state->prev[n] != -1))) {
1195 error = 1;
1196 if (mark_errors)
1197 state->flags[n] |= FLAG_ERROR;
1198 }
1199 }
1200
4cbcbfca 1201 if (error) return 0;
1202 return complete;
1203}
1204static game_state *new_game(midend *me, game_params *params, char *desc)
1205{
1206 game_state *state = NULL;
1207
1208 unpick_desc(params, desc, &state, NULL);
1209 if (!state) assert(!"new_game failed to unpick");
1210
1211 update_numbers(state);
1212 check_completion(state, 1); /* update any auto-links */
1213
1214 return state;
1215}
1216
1217/* --- Solver --- */
1218
1219/* If a tile has a single tile it can link _to_, or there's only a single
1220 * location that can link to a given tile, fill that link in. */
1221static int solve_single(game_state *state, game_state *copy, int *from)
1222{
1223 int i, j, sx, sy, x, y, d, poss, w=state->w, nlinks = 0;
1224
1225 /* The from array is a list of 'which square can link _to_ us';
1226 * we start off with from as '-1' (meaning 'not found'); if we find
1227 * something that can link to us it is set to that index, and then if
1228 * we find another we set it to -2. */
1229
1230 memset(from, -1, state->n*sizeof(int));
1231
1232 /* poss is 'can I link to anything' with the same meanings. */
1233
1234 for (i = 0; i < state->n; i++) {
1235 if (state->next[i] != -1) continue;
1236 if (state->nums[i] == state->n) continue; /* no next from last no. */
1237
1238 d = state->dirs[i];
1239 poss = -1;
1240 sx = x = i%w; sy = y = i/w;
1241 while (1) {
1242 x += dxs[d]; y += dys[d];
1243 if (!INGRID(state, x, y)) break;
1244 if (!isvalidmove(state, 1, sx, sy, x, y)) continue;
1245
1246 /* can't link to somewhere with a back-link we would have to
1247 * break (the solver just doesn't work like this). */
1248 j = y*w+x;
1249 if (state->prev[j] != -1) continue;
1250
1251 if (state->nums[i] > 0 && state->nums[j] > 0 &&
1252 state->nums[i] <= state->n && state->nums[j] <= state->n &&
1253 state->nums[j] == state->nums[i]+1) {
1254 debug(("Solver: forcing link through existing consecutive numbers."));
1255 poss = j;
1256 from[j] = i;
1257 break;
1258 }
1259
1260 /* if there's been a valid move already, we have to move on;
1261 * we can't make any deductions here. */
1262 poss = (poss == -1) ? j : -2;
1263
1264 /* Modify the from array as described above (which is enumerating
1265 * what points to 'j' in a similar way). */
1266 from[j] = (from[j] == -1) ? i : -2;
1267 }
1268 if (poss == -2) {
1269 /*debug(("Solver: (%d,%d) has multiple possible next squares.", sx, sy));*/
1270 ;
1271 } else if (poss == -1) {
1272 debug(("Solver: nowhere possible for (%d,%d) to link to.", sx, sy));
1273 copy->impossible = 1;
1274 return -1;
1275 } else {
1276 debug(("Solver: linking (%d,%d) to only possible next (%d,%d).",
1277 sx, sy, poss%w, poss/w));
1278 makelink(copy, i, poss);
1279 nlinks++;
1280 }
1281 }
1282
1283 for (i = 0; i < state->n; i++) {
1284 if (state->prev[i] != -1) continue;
1285 if (state->nums[i] == 1) continue; /* no prev from 1st no. */
1286
1287 x = i%w; y = i/w;
1288 if (from[i] == -1) {
1289 debug(("Solver: nowhere possible to link to (%d,%d)", x, y));
1290 copy->impossible = 1;
1291 return -1;
1292 } else if (from[i] == -2) {
1293 /*debug(("Solver: (%d,%d) has multiple possible prev squares.", x, y));*/
1294 ;
1295 } else {
1296 debug(("Solver: linking only possible prev (%d,%d) to (%d,%d).",
1297 from[i]%w, from[i]/w, x, y));
1298 makelink(copy, from[i], i);
1299 nlinks++;
1300 }
1301 }
1302
1303 return nlinks;
1304}
1305
1306/* Returns 1 if we managed to solve it, 0 otherwise. */
1307static int solve_state(game_state *state)
1308{
1309 game_state *copy = dup_game(state);
1310 int *scratch = snewn(state->n, int), ret;
1311
1312 debug_state("Before solver: ", state);
1313
1314 while (1) {
1315 update_numbers(state);
1316
1317 if (solve_single(state, copy, scratch)) {
1318 dup_game_to(state, copy);
1319 if (state->impossible) break; else continue;
1320 }
1321 break;
1322 }
1323 free_game(copy);
1324 sfree(scratch);
1325
1326 update_numbers(state);
1327 ret = state->impossible ? -1 : check_completion(state, 0);
1328 debug(("Solver finished: %s",
1329 ret < 0 ? "impossible" : ret > 0 ? "solved" : "not solved"));
1330 debug_state("After solver: ", state);
1331 return ret;
1332}
1333
1334static char *solve_game(game_state *state, game_state *currstate,
1335 char *aux, char **error)
1336{
1337 game_state *tosolve;
1338 char *ret = NULL;
1339 int result;
1340
1341 tosolve = dup_game(currstate);
1342 result = solve_state(tosolve);
1343 if (result > 0)
1344 ret = generate_desc(tosolve, 1);
1345 free_game(tosolve);
1346 if (ret) return ret;
1347
1348 tosolve = dup_game(state);
1349 result = solve_state(tosolve);
1350 if (result < 0)
1351 *error = "Puzzle is impossible.";
1352 else if (result == 0)
1353 *error = "Unable to solve puzzle.";
1354 else
1355 ret = generate_desc(tosolve, 1);
1356
1357 free_game(tosolve);
1358
1359 return ret;
1360}
1361
1362/* --- UI and move routines. --- */
1363
1364
1365struct game_ui {
1366 int cx, cy, cshow;
1367
1368 int dragging, drag_is_from;
1369 int sx, sy; /* grid coords of start cell */
1370 int dx, dy; /* pixel coords of drag posn */
1371};
1372
1373static game_ui *new_ui(game_state *state)
1374{
1375 game_ui *ui = snew(game_ui);
1376
1377 /* NB: if this is ever changed to as to require more than a structure
1378 * copy to clone, there's code that needs fixing in game_redraw too. */
1379
1380 ui->cx = ui->cy = ui->cshow = 0;
1381
1382 ui->dragging = 0;
1383 ui->sx = ui->sy = ui->dx = ui->dy = 0;
1384
1385 return ui;
1386}
1387
1388static void free_ui(game_ui *ui)
1389{
1390 sfree(ui);
1391}
1392
1393static char *encode_ui(game_ui *ui)
1394{
1395 return NULL;
1396}
1397
1398static void decode_ui(game_ui *ui, char *encoding)
1399{
1400}
1401
1402static void game_changed_state(game_ui *ui, game_state *oldstate,
1403 game_state *newstate)
1404{
1405 if (!oldstate->completed && newstate->completed)
1406 ui->cshow = ui->dragging = 0;
1407}
1408
1409struct game_drawstate {
1410 int tilesize, started, solved;
1411 int w, h, n;
1412 int *nums, *dirp;
1413 unsigned int *f;
1414 double angle_offset;
1415
1416 int dragging, dx, dy;
1417 blitter *dragb;
1418};
1419
1420static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
1421 int mx, int my, int button)
1422{
1423 int x = FROMCOORD(mx), y = FROMCOORD(my), w = state->w;
1424 char buf[80];
1425
1426 if (IS_CURSOR_MOVE(button)) {
1427 move_cursor(button, &ui->cx, &ui->cy, state->w, state->h, 0);
1428 ui->cshow = 1;
1429 if (ui->dragging) {
1430 ui->dx = COORD(ui->cx) + TILE_SIZE/2;
1431 ui->dy = COORD(ui->cy) + TILE_SIZE/2;
1432 }
1433 return "";
1434 } else if (IS_CURSOR_SELECT(button)) {
1435 if (!ui->cshow)
1436 ui->cshow = 1;
1437 else if (ui->dragging) {
1438 ui->dragging = FALSE;
1439 if (ui->sx == ui->cx && ui->sy == ui->cy) return "";
1440 if (ui->drag_is_from) {
1441 if (!isvalidmove(state, 0, ui->sx, ui->sy, ui->cx, ui->cy)) return "";
1442 sprintf(buf, "L%d,%d-%d,%d", ui->sx, ui->sy, ui->cx, ui->cy);
1443 } else {
1444 if (!isvalidmove(state, 0, ui->cx, ui->cy, ui->sx, ui->sy)) return "";
1445 sprintf(buf, "L%d,%d-%d,%d", ui->cx, ui->cy, ui->sx, ui->sy);
1446 }
1447 return dupstr(buf);
1448 } else {
1449 ui->dragging = TRUE;
1450 ui->sx = ui->cx;
1451 ui->sy = ui->cy;
1452 ui->dx = COORD(ui->cx) + TILE_SIZE/2;
1453 ui->dy = COORD(ui->cy) + TILE_SIZE/2;
1454 ui->drag_is_from = (button == CURSOR_SELECT) ? 1 : 0;
1455 }
1456 return "";
1457 }
1458 if (IS_MOUSE_DOWN(button)) {
1459 if (ui->cshow) {
1460 ui->cshow = ui->dragging = 0;
1461 }
1462 assert(!ui->dragging);
1463 if (!INGRID(state, x, y)) return NULL;
1464
1465 if (button == LEFT_BUTTON) {
1466 /* disallow dragging from the final number. */
51990f54 1467 if ((state->nums[y*w+x] == state->n) &&
1468 (state->flags[y*w+x] & FLAG_IMMUTABLE))
1469 return NULL;
4cbcbfca 1470 } else if (button == RIGHT_BUTTON) {
1471 /* disallow dragging to the first number. */
51990f54 1472 if ((state->nums[y*w+x] == 1) &&
1473 (state->flags[y*w+x] & FLAG_IMMUTABLE))
1474 return NULL;
4cbcbfca 1475 }
1476
1477 ui->dragging = TRUE;
1478 ui->drag_is_from = (button == LEFT_BUTTON) ? 1 : 0;
1479 ui->sx = x;
1480 ui->sy = y;
1481 ui->dx = mx;
1482 ui->dy = my;
1483 ui->cshow = 0;
1484 return "";
1485 } else if (IS_MOUSE_DRAG(button) && ui->dragging) {
1486 ui->dx = mx;
1487 ui->dy = my;
1488 return "";
1489 } else if (IS_MOUSE_RELEASE(button) && ui->dragging) {
1490 ui->dragging = FALSE;
1491 if (ui->sx == x && ui->sy == y) return ""; /* single click */
1492
1493 if (!INGRID(state, x, y)) {
1494 int si = ui->sy*w+ui->sx;
1495 if (state->prev[si] == -1 && state->next[si] == -1)
1496 return "";
1497 sprintf(buf, "%c%d,%d",
1498 ui->drag_is_from ? 'C' : 'X', ui->sx, ui->sy);
1499 return dupstr(buf);
1500 }
1501
1502 if (ui->drag_is_from) {
1503 if (!isvalidmove(state, 0, ui->sx, ui->sy, x, y)) return "";
1504 sprintf(buf, "L%d,%d-%d,%d", ui->sx, ui->sy, x, y);
1505 } else {
1506 if (!isvalidmove(state, 0, x, y, ui->sx, ui->sy)) return "";
1507 sprintf(buf, "L%d,%d-%d,%d", x, y, ui->sx, ui->sy);
1508 }
1509 return dupstr(buf);
1510 } /* else if (button == 'H' || button == 'h')
1511 return dupstr("H"); */
1512 else if ((button == 'x' || button == 'X') && ui->cshow) {
1513 int si = ui->cy*w + ui->cx;
1514 if (state->prev[si] == -1 && state->next[si] == -1)
1515 return "";
1516 sprintf(buf, "%c%d,%d",
1517 (button == 'x') ? 'C' : 'X', ui->cx, ui->cy);
1518 return dupstr(buf);
1519 }
1520
1521 return NULL;
1522}
1523
1524static void unlink_cell(game_state *state, int si)
1525{
1526 debug(("Unlinking (%d,%d).", si%state->w, si/state->w));
1527 if (state->prev[si] != -1) {
1528 debug((" ... removing prev link from (%d,%d).",
1529 state->prev[si]%state->w, state->prev[si]/state->w));
1530 state->next[state->prev[si]] = -1;
1531 state->prev[si] = -1;
1532 }
1533 if (state->next[si] != -1) {
1534 debug((" ... removing next link to (%d,%d).",
1535 state->next[si]%state->w, state->next[si]/state->w));
1536 state->prev[state->next[si]] = -1;
1537 state->next[si] = -1;
1538 }
1539}
1540
1541static game_state *execute_move(game_state *state, char *move)
1542{
1543 game_state *ret = NULL;
1544 int sx, sy, ex, ey, si, ei, w = state->w;
1545 char c;
1546
1547 debug(("move: %s", move));
1548
1549 if (move[0] == 'S') {
1550 game_params p;
1551 game_state *tmp;
1552 char *valid;
1553 int i;
1554
1555 p.w = state->w; p.h = state->h;
1556 valid = validate_desc(&p, move+1);
1557 if (valid) {
1558 debug(("execute_move: move not valid: %s", valid));
1559 return NULL;
1560 }
1561 ret = dup_game(state);
1562 tmp = new_game(NULL, &p, move+1);
1563 for (i = 0; i < state->n; i++) {
1564 ret->prev[i] = tmp->prev[i];
1565 ret->next[i] = tmp->next[i];
1566 }
1567 free_game(tmp);
1568 ret->used_solve = 1;
1569 } else if (sscanf(move, "L%d,%d-%d,%d", &sx, &sy, &ex, &ey) == 4) {
1570 if (!isvalidmove(state, 0, sx, sy, ex, ey)) return NULL;
1571
1572 ret = dup_game(state);
1573
1574 si = sy*w+sx; ei = ey*w+ex;
1575 makelink(ret, si, ei);
1576 } else if (sscanf(move, "%c%d,%d", &c, &sx, &sy) == 3) {
1577 if (c != 'C' && c != 'X') return NULL;
1578 if (!INGRID(state, sx, sy)) return NULL;
1579 si = sy*w+sx;
1580 if (state->prev[si] == -1 && state->next[si] == -1)
1581 return NULL;
1582
1583 ret = dup_game(state);
1584
1585 if (c == 'C') {
1586 /* Unlink the single cell we dragged from the board. */
1587 unlink_cell(ret, si);
1588 } else {
1589 int i, set, sset = state->nums[si] / (state->n+1);
1590 for (i = 0; i < state->n; i++) {
1591 /* Unlink all cells in the same set as the one we dragged
1592 * from the board. */
1593
1594 if (state->nums[i] == 0) continue;
1595 set = state->nums[i] / (state->n+1);
1596 if (set != sset) continue;
1597
1598 unlink_cell(ret, i);
1599 }
1600 }
1601 } else if (strcmp(move, "H") == 0) {
1602 ret = dup_game(state);
1603 solve_state(ret);
1604 }
1605 if (ret) {
1606 update_numbers(ret);
1607 if (check_completion(ret, 1)) ret->completed = 1;
1608 }
1609
1610 return ret;
1611}
1612
1613/* ----------------------------------------------------------------------
1614 * Drawing routines.
1615 */
1616
1617static void game_compute_size(game_params *params, int tilesize,
1618 int *x, int *y)
1619{
1620 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1621 struct { int tilesize, order; } ads, *ds = &ads;
1622 ads.tilesize = tilesize;
1623
1624 *x = TILE_SIZE * params->w + 2 * BORDER;
1625 *y = TILE_SIZE * params->h + 2 * BORDER;
1626}
1627
1628static void game_set_size(drawing *dr, game_drawstate *ds,
1629 game_params *params, int tilesize)
1630{
1631 ds->tilesize = tilesize;
1632 assert(TILE_SIZE > 0);
1633
1634 assert(!ds->dragb);
1635 ds->dragb = blitter_new(dr, BLITTER_SIZE, BLITTER_SIZE);
1636}
1637
1638/* Colours chosen from the webby palette to work as a background to black text,
1639 * W then some plausible approximation to pastelly ROYGBIV; we then interpolate
1640 * between consecutive pairs to give another 8 (and then the drawing routine
1641 * will reuse backgrounds). */
1642static const unsigned long bgcols[8] = {
1643 0xffffff, /* white */
1644 0xffa07a, /* lightsalmon */
1645 0x98fb98, /* green */
1646 0x7fffd4, /* aquamarine */
1647 0x9370db, /* medium purple */
1648 0xffa500, /* orange */
1649 0x87cefa, /* lightskyblue */
1650 0xffff00, /* yellow */
1651};
1652
1653static float *game_colours(frontend *fe, int *ncolours)
1654{
1655 float *ret = snewn(3 * NCOLOURS, float);
1656 int c, i;
1657
1658 game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
1659
1660 for (i = 0; i < 3; i++) {
1661 ret[COL_NUMBER * 3 + i] = 0.0F;
1662 ret[COL_ARROW * 3 + i] = 0.0F;
1663 ret[COL_CURSOR * 3 + i] = ret[COL_BACKGROUND * 3 + i] / 2.0F;
1664 ret[COL_GRID * 3 + i] = ret[COL_BACKGROUND * 3 + i] / 1.3F;
1665 }
1666 ret[COL_NUMBER_SET * 3 + 0] = 0.0F;
1667 ret[COL_NUMBER_SET * 3 + 1] = 0.0F;
1668 ret[COL_NUMBER_SET * 3 + 2] = 0.9F;
1669
1670 ret[COL_ERROR * 3 + 0] = 1.0F;
1671 ret[COL_ERROR * 3 + 1] = 0.0F;
1672 ret[COL_ERROR * 3 + 2] = 0.0F;
1673
1674 ret[COL_DRAG_ORIGIN * 3 + 0] = 0.2F;
1675 ret[COL_DRAG_ORIGIN * 3 + 1] = 1.0F;
1676 ret[COL_DRAG_ORIGIN * 3 + 2] = 0.2F;
1677
1678 for (c = 0; c < 8; c++) {
1679 ret[(COL_B0 + c) * 3 + 0] = (float)((bgcols[c] & 0xff0000) >> 16) / 256.0F;
1680 ret[(COL_B0 + c) * 3 + 1] = (float)((bgcols[c] & 0xff00) >> 8) / 256.0F;
1681 ret[(COL_B0 + c) * 3 + 2] = (float)((bgcols[c] & 0xff)) / 256.0F;
1682 }
1683 for (c = 0; c < 8; c++) {
1684 for (i = 0; i < 3; i++) {
1685 ret[(COL_B0 + 8 + c) * 3 + i] =
1686 (ret[(COL_B0 + c) * 3 + i] + ret[(COL_B0 + c + 1) * 3 + i]) / 2.0F;
1687 }
1688 }
1689
1690#define average(r,a,b,w) do { \
1691 for (i = 0; i < 3; i++) \
1692 ret[(r)*3+i] = ret[(a)*3+i] + w * (ret[(b)*3+i] - ret[(a)*3+i]); \
1693} while (0)
1694 average(COL_ARROW_BG_DIM, COL_BACKGROUND, COL_ARROW, 0.1F);
1695 average(COL_NUMBER_SET_MID, COL_B0, COL_NUMBER_SET, 0.3F);
1696 for (c = 0; c < NBACKGROUNDS; c++) {
1697 /* I assume here that COL_ARROW and COL_NUMBER are the same.
1698 * Otherwise I'd need two sets of COL_M*. */
1699 average(COL_M0 + c, COL_B0 + c, COL_NUMBER, 0.3F);
1700 average(COL_D0 + c, COL_B0 + c, COL_NUMBER, 0.1F);
1701 average(COL_X0 + c, COL_BACKGROUND, COL_B0 + c, 0.5F);
1702 }
1703
1704 *ncolours = NCOLOURS;
1705 return ret;
1706}
1707
1708static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
1709{
1710 struct game_drawstate *ds = snew(struct game_drawstate);
1711 int i;
1712
1713 ds->tilesize = ds->started = ds->solved = 0;
1714 ds->w = state->w;
1715 ds->h = state->h;
1716 ds->n = state->n;
1717
1718 ds->nums = snewn(state->n, int);
1719 ds->dirp = snewn(state->n, int);
1720 ds->f = snewn(state->n, unsigned int);
1721 for (i = 0; i < state->n; i++) {
1722 ds->nums[i] = 0;
1723 ds->dirp[i] = -1;
1724 ds->f[i] = 0;
1725 }
1726
1727 ds->angle_offset = 0.0F;
1728
1729 ds->dragging = ds->dx = ds->dy = 0;
1730 ds->dragb = NULL;
1731
1732 return ds;
1733}
1734
1735static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1736{
1737 sfree(ds->nums);
1738 sfree(ds->dirp);
1739 sfree(ds->f);
1740 if (ds->dragb) blitter_free(dr, ds->dragb);
1741
1742 sfree(ds);
1743}
1744
1745/* cx, cy are top-left corner. sz is the 'radius' of the arrow.
1746 * ang is in radians, clockwise from 0 == straight up. */
1747static void draw_arrow(drawing *dr, int cx, int cy, int sz, double ang,
1748 int cfill, int cout)
1749{
1750 int coords[14];
1751 int xdx, ydx, xdy, ydy, xdx3, xdy3;
1752 double s = sin(ang), c = cos(ang);
1753
1754 xdx3 = (int)(sz * (c/3 + 1) + 0.5) - sz;
1755 xdy3 = (int)(sz * (s/3 + 1) + 0.5) - sz;
1756 xdx = (int)(sz * (c + 1) + 0.5) - sz;
1757 xdy = (int)(sz * (s + 1) + 0.5) - sz;
1758 ydx = -xdy;
1759 ydy = xdx;
1760
1761
1762 coords[2*0 + 0] = cx - ydx;
1763 coords[2*0 + 1] = cy - ydy;
1764 coords[2*1 + 0] = cx + xdx;
1765 coords[2*1 + 1] = cy + xdy;
1766 coords[2*2 + 0] = cx + xdx3;
1767 coords[2*2 + 1] = cy + xdy3;
1768 coords[2*3 + 0] = cx + xdx3 + ydx;
1769 coords[2*3 + 1] = cy + xdy3 + ydy;
1770 coords[2*4 + 0] = cx - xdx3 + ydx;
1771 coords[2*4 + 1] = cy - xdy3 + ydy;
1772 coords[2*5 + 0] = cx - xdx3;
1773 coords[2*5 + 1] = cy - xdy3;
1774 coords[2*6 + 0] = cx - xdx;
1775 coords[2*6 + 1] = cy - xdy;
1776
1777 draw_polygon(dr, coords, 7, cfill, cout);
1778}
1779
1780static void draw_arrow_dir(drawing *dr, int cx, int cy, int sz, int dir,
1781 int cfill, int cout, double angle_offset)
1782{
1783 double ang = 2.0 * PI * (double)dir / 8.0 + angle_offset;
1784 draw_arrow(dr, cx, cy, sz, ang, cfill, cout);
1785}
1786
1787/* cx, cy are centre coordinates.. */
1788static void draw_star(drawing *dr, int cx, int cy, int rad, int npoints,
1789 int cfill, int cout, double angle_offset)
1790{
1791 int *coords, n;
1792 double a, r;
1793
1794 assert(npoints > 0);
1795
1796 coords = snewn(npoints * 2 * 2, int);
1797
1798 for (n = 0; n < npoints * 2; n++) {
1799 a = 2.0 * PI * ((double)n / ((double)npoints * 2.0)) + angle_offset;
1800 r = (n % 2) ? (double)rad/2.0 : (double)rad;
1801
1802 /* We're rotating the point at (0, -r) by a degrees */
1803 coords[2*n+0] = cx + (int)( r * sin(a));
1804 coords[2*n+1] = cy + (int)(-r * cos(a));
1805 }
1806 draw_polygon(dr, coords, npoints*2, cfill, cout);
1807 sfree(coords);
1808}
1809
1810static int num2col(game_drawstate *ds, int num)
1811{
1812 int set = num / (ds->n+1);
1813
33c2bb47 1814 if (num <= 0) return COL_B0;
4cbcbfca 1815 return COL_B0 + (set % 16);
1816}
1817
1818#define ARROW_HALFSZ (7 * TILE_SIZE / 32)
1819
1820#define F_CUR 0x001 /* Cursor on this tile. */
1821#define F_DRAG_SRC 0x002 /* Tile is source of a drag. */
1822#define F_ERROR 0x004 /* Tile marked in error. */
1823#define F_IMMUTABLE 0x008 /* Tile (number) is immutable. */
1824#define F_ARROW_POINT 0x010 /* Tile points to other tile */
1825#define F_ARROW_INPOINT 0x020 /* Other tile points in here. */
1826#define F_DIM 0x040 /* Tile is dim */
1827
1828static void tile_redraw(drawing *dr, game_drawstate *ds, int tx, int ty,
1829 int dir, int dirp, int num, unsigned int f,
1830 double angle_offset, int print_ink)
1831{
1832 int cb = TILE_SIZE / 16, textsz;
1833 char buf[20];
1834 int arrowcol, sarrowcol, setcol, textcol;
33c2bb47 1835 int acx, acy, asz, empty = 0;
1836
1837 if (num == 0 && !(f & F_ARROW_POINT) && !(f & F_ARROW_INPOINT)) {
1838 empty = 1;
1839 /*
1840 * We don't display text in empty cells: typically these are
1841 * signified by num=0. However, in some cases a cell could
1842 * have had the number 0 assigned to it if the user made an
1843 * error (e.g. tried to connect a chain of length 5 to the
1844 * immutable number 4) so we _do_ display the 0 if the cell
1845 * has a link in or a link out.
1846 */
1847 }
4cbcbfca 1848
1849 /* Calculate colours. */
1850
1851 if (print_ink >= 0) {
1852 /*
1853 * We're printing, so just do everything in black.
1854 */
1855 arrowcol = textcol = print_ink;
1856 setcol = sarrowcol = -1; /* placate optimiser */
1857 } else {
1858
33c2bb47 1859 setcol = empty ? COL_BACKGROUND : num2col(ds, num);
4cbcbfca 1860
1861#define dim(fg,bg) ( \
1862 (bg)==COL_BACKGROUND ? COL_ARROW_BG_DIM : \
1863 (bg) + COL_D0 - COL_B0 \
1864 )
1865
1866#define mid(fg,bg) ( \
1867 (fg)==COL_NUMBER_SET ? COL_NUMBER_SET_MID : \
1868 (bg) + COL_M0 - COL_B0 \
1869 )
1870
1871#define dimbg(bg) ( \
1872 (bg)==COL_BACKGROUND ? COL_BACKGROUND : \
1873 (bg) + COL_X0 - COL_B0 \
1874 )
1875
1876 if (f & F_DRAG_SRC) arrowcol = COL_DRAG_ORIGIN;
1877 else if (f & F_DIM) arrowcol = dim(COL_ARROW, setcol);
1878 else if (f & F_ARROW_POINT) arrowcol = mid(COL_ARROW, setcol);
1879 else arrowcol = COL_ARROW;
1880
51990f54 1881 if ((f & F_ERROR) && !(f & F_IMMUTABLE)) textcol = COL_ERROR;
4cbcbfca 1882 else {
1883 if (f & F_IMMUTABLE) textcol = COL_NUMBER_SET;
1884 else textcol = COL_NUMBER;
1885
1886 if (f & F_DIM) textcol = dim(textcol, setcol);
1887 else if (((f & F_ARROW_POINT) || num==ds->n) &&
1888 ((f & F_ARROW_INPOINT) || num==1))
1889 textcol = mid(textcol, setcol);
1890 }
1891
1892 if (f & F_DIM) sarrowcol = dim(COL_ARROW, setcol);
1893 else sarrowcol = COL_ARROW;
1894 }
1895
1896 /* Clear tile background */
1897
1898 if (print_ink < 0) {
1899 draw_rect(dr, tx, ty, TILE_SIZE, TILE_SIZE,
1900 (f & F_DIM) ? dimbg(setcol) : setcol);
1901 }
1902
1903 /* Draw large (outwards-pointing) arrow. */
1904
1905 asz = ARROW_HALFSZ; /* 'radius' of arrow/star. */
1906 acx = tx+TILE_SIZE/2+asz; /* centre x */
1907 acy = ty+TILE_SIZE/2+asz; /* centre y */
1908
1909 if (num == ds->n && (f & F_IMMUTABLE))
1910 draw_star(dr, acx, acy, asz, 5, arrowcol, arrowcol, angle_offset);
1911 else
1912 draw_arrow_dir(dr, acx, acy, asz, dir, arrowcol, arrowcol, angle_offset);
1913 if (print_ink < 0 && (f & F_CUR))
1914 draw_rect_corners(dr, acx, acy, asz+1, COL_CURSOR);
1915
1916 /* Draw dot iff this tile requires a predecessor and doesn't have one. */
1917
1918 if (print_ink < 0) {
1919 acx = tx+TILE_SIZE/2-asz;
1920 acy = ty+TILE_SIZE/2+asz;
1921
1922 if (!(f & F_ARROW_INPOINT) && num != 1) {
1923 draw_circle(dr, acx, acy, asz / 4, sarrowcol, sarrowcol);
1924 }
1925 }
1926
1927 /* Draw text (number or set). */
1928
33c2bb47 1929 if (!empty) {
1930 int set = (num <= 0) ? 0 : num / (ds->n+1);
1931
1932 if (set == 0 || num <= 0) {
1933 sprintf(buf, "%d", num);
4cbcbfca 1934 } else {
33c2bb47 1935 int n = num % (ds->n+1);
1936
4cbcbfca 1937 if (n == 0)
1938 sprintf(buf, "%c", (int)(set+'a'-1));
1939 else
1940 sprintf(buf, "%c+%d", (int)(set+'a'-1), n);
1941 }
1942 textsz = min(2*asz, (TILE_SIZE - 2 * cb) / (int)strlen(buf));
1943 draw_text(dr, tx + cb, ty + TILE_SIZE/4, FONT_VARIABLE, textsz,
1944 ALIGN_VCENTRE | ALIGN_HLEFT, textcol, buf);
1945 }
1946
1947 if (print_ink < 0) {
1948 draw_rect_outline(dr, tx, ty, TILE_SIZE, TILE_SIZE, COL_GRID);
1949 draw_update(dr, tx, ty, TILE_SIZE, TILE_SIZE);
1950 }
1951}
1952
1953static void draw_drag_indicator(drawing *dr, game_drawstate *ds,
1954 game_state *state, game_ui *ui, int validdrag)
1955{
1956 int dir, w = ds->w, acol = COL_ARROW;
1957 int fx = FROMCOORD(ui->dx), fy = FROMCOORD(ui->dy);
1958 double ang;
1959
1960 if (validdrag) {
1961 /* If we could move here, lock the arrow to the appropriate direction. */
1962 dir = ui->drag_is_from ? state->dirs[ui->sy*w+ui->sx] : state->dirs[fy*w+fx];
1963
1964 ang = (2.0 * PI * dir) / 8.0; /* similar to calculation in draw_arrow_dir. */
1965 } else {
1966 /* Draw an arrow pointing away from/towards the origin cell. */
1967 int ox = COORD(ui->sx) + TILE_SIZE/2, oy = COORD(ui->sy) + TILE_SIZE/2;
1968 double tana, offset;
1969 double xdiff = fabs(ox - ui->dx), ydiff = fabs(oy - ui->dy);
1970
1971 if (xdiff == 0) {
1972 ang = (oy > ui->dy) ? 0.0F : PI;
1973 } else if (ydiff == 0) {
1974 ang = (ox > ui->dx) ? 3.0F*PI/2.0F : PI/2.0F;
1975 } else {
1976 if (ui->dx > ox && ui->dy < oy) {
1977 tana = xdiff / ydiff;
1978 offset = 0.0F;
1979 } else if (ui->dx > ox && ui->dy > oy) {
1980 tana = ydiff / xdiff;
1981 offset = PI/2.0F;
1982 } else if (ui->dx < ox && ui->dy > oy) {
1983 tana = xdiff / ydiff;
1984 offset = PI;
1985 } else {
1986 tana = ydiff / xdiff;
1987 offset = 3.0F * PI / 2.0F;
1988 }
1989 ang = atan(tana) + offset;
1990 }
1991
1992 if (!ui->drag_is_from) ang += PI; /* point to origin, not away from. */
1993
1994 }
1995 draw_arrow(dr, ui->dx, ui->dy, ARROW_HALFSZ, ang, acol, acol);
1996}
1997
1998static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
1999 game_state *state, int dir, game_ui *ui,
2000 float animtime, float flashtime)
2001{
2002 int x, y, i, w = ds->w, dirp, force = 0;
2003 unsigned int f;
2004 double angle_offset = 0.0;
2005 game_state *postdrop = NULL;
2006
2007 if (flashtime > 0.0F)
2008 angle_offset = 2.0 * PI * (flashtime / FLASH_SPIN);
2009 if (angle_offset != ds->angle_offset) {
2010 ds->angle_offset = angle_offset;
2011 force = 1;
2012 }
2013
2014 if (ds->dragging) {
2015 assert(ds->dragb);
2016 blitter_load(dr, ds->dragb, ds->dx, ds->dy);
2017 draw_update(dr, ds->dx, ds->dy, BLITTER_SIZE, BLITTER_SIZE);
2018 ds->dragging = FALSE;
2019 }
2020
2021 /* If an in-progress drag would make a valid move if finished, we
2022 * reflect that move in the board display. We let interpret_move do
2023 * most of the heavy lifting for us: we have to copy the game_ui so
2024 * as not to stomp on the real UI's drag state. */
2025 if (ui->dragging) {
2026 game_ui uicopy = *ui;
2027 char *movestr = interpret_move(state, &uicopy, ds, ui->dx, ui->dy, LEFT_RELEASE);
2028
2029 if (movestr != NULL && strcmp(movestr, "") != 0) {
2030 postdrop = execute_move(state, movestr);
2031 sfree(movestr);
2032
2033 state = postdrop;
2034 }
2035 }
2036
2037 if (!ds->started) {
2038 int aw = TILE_SIZE * state->w;
2039 int ah = TILE_SIZE * state->h;
2040 draw_rect(dr, 0, 0, aw + 2 * BORDER, ah + 2 * BORDER, COL_BACKGROUND);
2041 draw_rect_outline(dr, BORDER - 1, BORDER - 1, aw + 2, ah + 2, COL_GRID);
2042 draw_update(dr, 0, 0, aw + 2 * BORDER, ah + 2 * BORDER);
2043 }
2044 for (x = 0; x < state->w; x++) {
2045 for (y = 0; y < state->h; y++) {
2046 i = y*w + x;
2047 f = 0;
2048 dirp = -1;
2049
2050 if (ui->cshow && x == ui->cx && y == ui->cy)
2051 f |= F_CUR;
2052
2053 if (ui->dragging) {
2054 if (x == ui->sx && y == ui->sy)
2055 f |= F_DRAG_SRC;
2056 else if (ui->drag_is_from) {
2057 if (!ispointing(state, ui->sx, ui->sy, x, y))
2058 f |= F_DIM;
2059 } else {
2060 if (!ispointing(state, x, y, ui->sx, ui->sy))
2061 f |= F_DIM;
2062 }
2063 }
2064
2065 if (state->impossible ||
2066 state->nums[i] < 0 || state->flags[i] & FLAG_ERROR)
2067 f |= F_ERROR;
2068 if (state->flags[i] & FLAG_IMMUTABLE)
2069 f |= F_IMMUTABLE;
2070
2071 if (state->next[i] != -1)
2072 f |= F_ARROW_POINT;
2073
2074 if (state->prev[i] != -1) {
2075 /* Currently the direction here is from our square _back_
2076 * to its previous. We could change this to give the opposite
2077 * sense to the direction. */
2078 f |= F_ARROW_INPOINT;
2079 dirp = whichdir(x, y, state->prev[i]%w, state->prev[i]/w);
2080 }
2081
2082 if (state->nums[i] != ds->nums[i] ||
2083 f != ds->f[i] || dirp != ds->dirp[i] ||
2084 force || !ds->started) {
2085 tile_redraw(dr, ds,
2086 BORDER + x * TILE_SIZE,
2087 BORDER + y * TILE_SIZE,
2088 state->dirs[i], dirp, state->nums[i], f,
2089 angle_offset, -1);
2090 ds->nums[i] = state->nums[i];
2091 ds->f[i] = f;
2092 ds->dirp[i] = dirp;
2093 }
2094 }
2095 }
2096 if (ui->dragging) {
2097 ds->dragging = TRUE;
2098 ds->dx = ui->dx - BLITTER_SIZE/2;
2099 ds->dy = ui->dy - BLITTER_SIZE/2;
2100 blitter_save(dr, ds->dragb, ds->dx, ds->dy);
2101
2102 draw_drag_indicator(dr, ds, state, ui, postdrop ? 1 : 0);
2103 }
2104 if (postdrop) free_game(postdrop);
2105 if (!ds->started) ds->started = TRUE;
2106}
2107
2108static float game_anim_length(game_state *oldstate, game_state *newstate,
2109 int dir, game_ui *ui)
2110{
2111 return 0.0F;
2112}
2113
2114static float game_flash_length(game_state *oldstate, game_state *newstate,
2115 int dir, game_ui *ui)
2116{
2117 if (!oldstate->completed &&
2118 newstate->completed && !newstate->used_solve)
2119 return FLASH_SPIN;
2120 else
2121 return 0.0F;
2122}
2123
2124static int game_timing_state(game_state *state, game_ui *ui)
2125{
2126 return TRUE;
2127}
2128
2129static void game_print_size(game_params *params, float *x, float *y)
2130{
2131 int pw, ph;
2132
2133 game_compute_size(params, 1300, &pw, &ph);
2134 *x = pw / 100.0F;
2135 *y = ph / 100.0F;
2136}
2137
2138static void game_print(drawing *dr, game_state *state, int tilesize)
2139{
2140 int ink = print_mono_colour(dr, 0);
2141 int x, y;
2142
2143 /* Fake up just enough of a drawstate */
2144 game_drawstate ads, *ds = &ads;
2145 ds->tilesize = tilesize;
2146 ds->n = state->n;
2147
2148 /*
2149 * Border and grid.
2150 */
2151 print_line_width(dr, TILE_SIZE / 40);
2152 for (x = 1; x < state->w; x++)
2153 draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(state->h), ink);
2154 for (y = 1; y < state->h; y++)
2155 draw_line(dr, COORD(0), COORD(y), COORD(state->w), COORD(y), ink);
2156 print_line_width(dr, 2*TILE_SIZE / 40);
2157 draw_rect_outline(dr, COORD(0), COORD(0), TILE_SIZE*state->w,
2158 TILE_SIZE*state->h, ink);
2159
2160 /*
2161 * Arrows and numbers.
2162 */
2163 print_line_width(dr, 0);
2164 for (y = 0; y < state->h; y++)
2165 for (x = 0; x < state->w; x++)
2166 tile_redraw(dr, ds, COORD(x), COORD(y), state->dirs[y*state->w+x],
2167 0, state->nums[y*state->w+x], 0, 0.0, ink);
2168}
2169
2170#ifdef COMBINED
2171#define thegame signpost
2172#endif
2173
2174const struct game thegame = {
2175 "Signpost", "games.signpost", "signpost",
2176 default_params,
2177 game_fetch_preset,
2178 decode_params,
2179 encode_params,
2180 free_params,
2181 dup_params,
2182 TRUE, game_configure, custom_params,
2183 validate_params,
2184 new_game_desc,
2185 validate_desc,
2186 new_game,
2187 dup_game,
2188 free_game,
2189 TRUE, solve_game,
2190 TRUE, game_can_format_as_text_now, game_text_format,
2191 new_ui,
2192 free_ui,
2193 encode_ui,
2194 decode_ui,
2195 game_changed_state,
2196 interpret_move,
2197 execute_move,
2198 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2199 game_colours,
2200 game_new_drawstate,
2201 game_free_drawstate,
2202 game_redraw,
2203 game_anim_length,
2204 game_flash_length,
2205 TRUE, FALSE, game_print_size, game_print,
2206 FALSE, /* wants_statusbar */
2207 FALSE, game_timing_state,
2208 REQUIRE_RBUTTON | REQUIRE_NUMPAD, /* flags */
2209};
2210
2211#ifdef STANDALONE_SOLVER
2212
2213#include <time.h>
2214#include <stdarg.h>
2215
2216const char *quis = NULL;
2217int verbose = 0;
2218
2219void usage(FILE *out) {
2220 fprintf(out, "usage: %s [--stdin] [--soak] [--seed SEED] <params>|<game id>\n", quis);
2221}
2222
2223static void cycle_seed(char **seedstr, random_state *rs)
2224{
2225 char newseed[16];
2226 int j;
2227
2228 newseed[15] = '\0';
2229 newseed[0] = '1' + (char)random_upto(rs, 9);
2230 for (j = 1; j < 15; j++)
2231 newseed[j] = '0' + (char)random_upto(rs, 10);
2232 sfree(*seedstr);
2233 *seedstr = dupstr(newseed);
2234}
2235
2236static void start_soak(game_params *p, char *seedstr)
2237{
2238 time_t tt_start, tt_now, tt_last;
2239 char *desc, *aux;
2240 random_state *rs;
2241 long n = 0, nnums = 0, i;
2242 game_state *state;
2243
2244 tt_start = tt_now = time(NULL);
2245 printf("Soak-generating a %dx%d grid.\n", p->w, p->h);
2246
2247 while (1) {
2248 rs = random_new(seedstr, strlen(seedstr));
2249 desc = thegame.new_desc(p, rs, &aux, 0);
2250
2251 state = thegame.new_game(NULL, p, desc);
2252 for (i = 0; i < state->n; i++) {
2253 if (state->flags[i] & FLAG_IMMUTABLE)
2254 nnums++;
2255 }
2256 thegame.free_game(state);
2257
2258 sfree(desc);
2259 cycle_seed(&seedstr, rs);
2260 random_free(rs);
2261
2262 n++;
2263 tt_last = time(NULL);
2264 if (tt_last > tt_now) {
2265 tt_now = tt_last;
2266 printf("%ld total, %3.1f/s, %3.1f nums/grid (%3.1f%%).\n",
2267 n,
2268 (double)n / ((double)tt_now - tt_start),
2269 (double)nnums / (double)n,
2270 ((double)nnums * 100.0) / ((double)n * (double)p->w * (double)p->h) );
2271 }
2272 }
2273}
2274
2275static void process_desc(char *id)
2276{
2277 char *desc, *err, *solvestr;
2278 game_params *p;
2279 game_state *s;
2280
2281 printf("%s\n ", id);
2282
2283 desc = strchr(id, ':');
2284 if (!desc) {
2285 fprintf(stderr, "%s: expecting game description.", quis);
2286 exit(1);
2287 }
2288
2289 *desc++ = '\0';
2290
2291 p = thegame.default_params();
2292 thegame.decode_params(p, id);
2293 err = thegame.validate_params(p, 1);
2294 if (err) {
2295 fprintf(stderr, "%s: %s", quis, err);
2296 thegame.free_params(p);
2297 return;
2298 }
2299
2300 err = thegame.validate_desc(p, desc);
2301 if (err) {
2302 fprintf(stderr, "%s: %s\nDescription: %s\n", quis, err, desc);
2303 thegame.free_params(p);
2304 return;
2305 }
2306
2307 s = thegame.new_game(NULL, p, desc);
2308
2309 solvestr = thegame.solve(s, s, NULL, &err);
2310 if (!solvestr)
2311 fprintf(stderr, "%s\n", err);
2312 else
2313 printf("Puzzle is soluble.\n");
2314
2315 thegame.free_game(s);
2316 thegame.free_params(p);
2317}
2318
2319int main(int argc, const char *argv[])
2320{
2321 char *id = NULL, *desc, *err, *aux = NULL;
2322 int soak = 0, verbose = 0, stdin_desc = 0, n = 1, i;
2323 char *seedstr = NULL, newseed[16];
2324
2325 setvbuf(stdout, NULL, _IONBF, 0);
2326
2327 quis = argv[0];
2328 while (--argc > 0) {
2329 char *p = (char*)(*++argv);
2330 if (!strcmp(p, "-v") || !strcmp(p, "--verbose"))
2331 verbose = 1;
2332 else if (!strcmp(p, "--stdin"))
2333 stdin_desc = 1;
2334 else if (!strcmp(p, "-e") || !strcmp(p, "--seed")) {
2335 seedstr = dupstr(*++argv);
2336 argc--;
2337 } else if (!strcmp(p, "-n") || !strcmp(p, "--number")) {
2338 n = atoi(*++argv);
2339 argc--;
2340 } else if (!strcmp(p, "-s") || !strcmp(p, "--soak")) {
2341 soak = 1;
2342 } else if (*p == '-') {
2343 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2344 usage(stderr);
2345 exit(1);
2346 } else {
2347 id = p;
2348 }
2349 }
2350
2351 sprintf(newseed, "%lu", time(NULL));
2352 seedstr = dupstr(newseed);
2353
2354 if (id || !stdin_desc) {
2355 if (id && strchr(id, ':')) {
2356 /* Parameters and description passed on cmd-line:
2357 * try and solve it. */
2358 process_desc(id);
2359 } else {
2360 /* No description passed on cmd-line: decode parameters
2361 * (with optional seed too) */
2362
2363 game_params *p = thegame.default_params();
2364
2365 if (id) {
2366 char *cmdseed = strchr(id, '#');
2367 if (cmdseed) {
2368 *cmdseed++ = '\0';
2369 sfree(seedstr);
2370 seedstr = dupstr(cmdseed);
2371 }
2372
2373 thegame.decode_params(p, id);
2374 }
2375
2376 err = thegame.validate_params(p, 1);
2377 if (err) {
2378 fprintf(stderr, "%s: %s", quis, err);
2379 thegame.free_params(p);
2380 exit(1);
2381 }
2382
2383 /* We have a set of valid parameters; either soak with it
2384 * or generate a single game description and print to stdout. */
2385 if (soak)
2386 start_soak(p, seedstr);
2387 else {
2388 char *pstring = thegame.encode_params(p, 0);
2389
2390 for (i = 0; i < n; i++) {
2391 random_state *rs = random_new(seedstr, strlen(seedstr));
2392
2393 if (verbose) printf("%s#%s\n", pstring, seedstr);
2394 desc = thegame.new_desc(p, rs, &aux, 0);
2395 printf("%s:%s\n", pstring, desc);
2396 sfree(desc);
2397
2398 cycle_seed(&seedstr, rs);
2399
2400 random_free(rs);
2401 }
2402
2403 sfree(pstring);
2404 }
2405 thegame.free_params(p);
2406 }
2407 }
2408
2409 if (stdin_desc) {
2410 char buf[4096];
2411
2412 while (fgets(buf, sizeof(buf), stdin)) {
2413 buf[strcspn(buf, "\r\n")] = '\0';
2414 process_desc(buf);
2415 }
2416 }
2417 sfree(seedstr);
2418
2419 return 0;
2420}
2421
2422#endif
2423
2424
2425/* vim: set shiftwidth=4 tabstop=8: */