chiark / gitweb /
61bd3c0d72b270d41aeb834958aa45fcd2a2575e
[sgt-puzzles.git] / signpost.c
1 /*
2  * signpost.c: implementation of the janko game 'arrow path'
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
28 enum {
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
40 struct game_params {
41     int w, h;
42     int force_corner_start;
43 };
44
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" };
47
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 };
50
51 #define DIR_OPPOSITE(d) ((d+4)%8)
52
53 struct 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
71 static 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
89 static 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
95 static int ispointing(const game_state *state, int fromx, int fromy,
96                       int tox, int toy)
97 {
98     int w = state->w, dir = state->dirs[fromy*w+fromx];
99
100     /* (by convention) squares do not point to themselves. */
101     if (fromx == tox && fromy == toy) return 0;
102
103     /* the final number points to nothing. */
104     if (state->nums[fromy*w + fromx] == state->n) return 0;
105
106     while (1) {
107         if (!INGRID(state, fromx, fromy)) return 0;
108         if (fromx == tox && fromy == toy) return 1;
109         fromx += dxs[dir]; fromy += dys[dir];
110     }
111     return 0; /* not reached */
112 }
113
114 static int ispointingi(game_state *state, int fromi, int toi)
115 {
116     int w = state->w;
117     return ispointing(state, fromi%w, fromi/w, toi%w, toi/w);
118 }
119
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)
124 {
125     int n, gap, i = y*state->w+x, sz;
126
127     assert(d != 0);
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 */
134
135     if (gap == 0) {
136         /* no gap, so the only allowable move is that that directly
137          * links the two numbers. */
138         n = state->nums[i];
139         return (n == num+d) ? 0 : 1;
140     }
141     if (state->prev[i] == -1 && state->next[i] == -1)
142         return 1; /* single unconnected square, always OK */
143
144     sz = dsf_size(state->dsf, i);
145     return (sz > gap) ? 0 : 1;
146 }
147
148 static int isvalidmove(const game_state *state, int clever,
149                        int fromx, int fromy, int tox, int toy)
150 {
151     int w = state->w, from = fromy*w+fromx, to = toy*w+tox;
152     int nfrom, nto;
153
154     if (!INGRID(state, fromx, fromy) || !INGRID(state, tox, toy))
155         return 0;
156
157     /* can only move where we point */
158     if (!ispointing(state, fromx, fromy, tox, toy))
159         return 0;
160
161     nfrom = state->nums[from]; nto = state->nums[to];
162
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)))
166         return 0;
167
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))
171         return 0;
172
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)) {
176         if (nfrom != nto-1)
177             return 0;
178     } else if (clever && ISREALNUM(state, nfrom)) {
179         if (!move_couldfit(state, nfrom, +1, tox, toy))
180             return 0;
181     } else if (clever && ISREALNUM(state, nto)) {
182         if (!move_couldfit(state, nto, -1, fromx, fromy))
183             return 0;
184     }
185
186     return 1;
187 }
188
189 static void makelink(game_state *state, int from, int to)
190 {
191     if (state->next[from] != -1)
192         state->prev[state->next[from]] = -1;
193     state->next[from] = to;
194
195     if (state->prev[to] != -1)
196         state->next[state->prev[to]] = -1;
197     state->prev[to] = from;
198 }
199
200 static int game_can_format_as_text_now(const game_params *params)
201 {
202     if (params->w * params->h >= 100) return 0;
203     return 1;
204 }
205
206 static char *game_text_format(const game_state *state)
207 {
208     int len = state->h * 2 * (4*state->w + 1) + state->h + 2;
209     int x, y, i, num, n, set;
210     char *ret, *p;
211
212     p = ret = snewn(len, char);
213
214     for (y = 0; y < state->h; y++) {
215         for (x = 0; x < state->h; x++) {
216             i = y*state->w+x;
217             *p++ = dirstrings[state->dirs[i]][0];
218             *p++ = dirstrings[state->dirs[i]][1];
219             *p++ = (state->flags[i] & FLAG_IMMUTABLE) ? 'I' : ' ';
220             *p++ = ' ';
221         }
222         *p++ = '\n';
223         for (x = 0; x < state->h; x++) {
224             i = y*state->w+x;
225             num = state->nums[i];
226             if (num == 0) {
227                 *p++ = ' ';
228                 *p++ = ' ';
229                 *p++ = ' ';
230             } else {
231                 n = num % (state->n+1);
232                 set = num / (state->n+1);
233
234                 assert(n <= 99); /* two digits only! */
235
236                 if (set != 0)
237                     *p++ = set+'a'-1;
238
239                 *p++ = (n >= 10) ? ('0' + (n/10)) : ' ';
240                 *p++ = '0' + (n%10);
241
242                 if (set == 0)
243                     *p++ = ' ';
244             }
245             *p++ = ' ';
246         }
247         *p++ = '\n';
248         *p++ = '\n';
249     }
250     *p++ = '\0';
251
252     return ret;
253 }
254
255 static void debug_state(const char *desc, game_state *state)
256 {
257 #ifdef DEBUGGING
258     char *dbg;
259     if (state->n >= 100) {
260         debug(("[ no game_text_format for this size ]"));
261         return;
262     }
263     dbg = game_text_format(state);
264     debug(("%s\n%s", desc, dbg));
265     sfree(dbg);
266 #endif
267 }
268
269
270 static void strip_nums(game_state *state) {
271     int i;
272     for (i = 0; i < state->n; i++) {
273         if (!(state->flags[i] & FLAG_IMMUTABLE))
274             state->nums[i] = 0;
275     }
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);
280 }
281
282 static int check_nums(game_state *orig, game_state *copy, int only_immutable)
283 {
284     int i, ret = 1;
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]));
293             ret = 0;
294         }
295     }
296     return ret;
297 }
298
299 /* --- Game parameter/presets functions --- */
300
301 static game_params *default_params(void)
302 {
303     game_params *ret = snew(game_params);
304     ret->w = ret->h = 4;
305     ret->force_corner_start = 1;
306
307     return ret;
308 }
309
310 static const struct game_params signpost_presets[] = {
311   { 4, 4, 1 },
312   { 4, 4, 0 },
313   { 5, 5, 1 },
314   { 5, 5, 0 },
315   { 6, 6, 1 },
316   { 7, 7, 1 }
317 };
318
319 static int game_fetch_preset(int i, char **name, game_params **params)
320 {
321     game_params *ret;
322     char buf[80];
323
324     if (i < 0 || i >= lenof(signpost_presets))
325         return FALSE;
326
327     ret = default_params();
328     *ret = signpost_presets[i];
329     *params = ret;
330
331     sprintf(buf, "%dx%d%s", ret->w, ret->h,
332             ret->force_corner_start ? "" : ", free ends");
333     *name = dupstr(buf);
334
335     return TRUE;
336 }
337
338 static void free_params(game_params *params)
339 {
340     sfree(params);
341 }
342
343 static game_params *dup_params(const game_params *params)
344 {
345     game_params *ret = snew(game_params);
346     *ret = *params;                    /* structure copy */
347     return ret;
348 }
349
350 static void decode_params(game_params *ret, char const *string)
351 {
352     ret->w = ret->h = atoi(string);
353     while (*string && isdigit((unsigned char)*string)) string++;
354     if (*string == 'x') {
355         string++;
356         ret->h = atoi(string);
357         while (*string && isdigit((unsigned char)*string)) string++;
358     }
359     ret->force_corner_start = 0;
360     if (*string == 'c') {
361         string++;
362         ret->force_corner_start = 1;
363     }
364
365 }
366
367 static char *encode_params(const game_params *params, int full)
368 {
369     char data[256];
370
371     if (full)
372         sprintf(data, "%dx%d%s", params->w, params->h,
373                 params->force_corner_start ? "c" : "");
374     else
375         sprintf(data, "%dx%d", params->w, params->h);
376
377     return dupstr(data);
378 }
379
380 static config_item *game_configure(const game_params *params)
381 {
382     config_item *ret;
383     char buf[80];
384
385     ret = snewn(4, config_item);
386
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);
391
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);
396
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;
400
401     ret[3].name = NULL;
402     ret[3].type = C_END;
403
404     return ret;
405 }
406
407 static game_params *custom_params(const config_item *cfg)
408 {
409     game_params *ret = snew(game_params);
410
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;
414
415     return ret;
416 }
417
418 static char *validate_params(const game_params *params, int full)
419 {
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";
426     return NULL;
427 }
428
429 /* --- Game description string generation and unpicking --- */
430
431 static void blank_game_into(game_state *state)
432 {
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));
439 }
440
441 static game_state *blank_game(int w, int h)
442 {
443     game_state *state = snew(game_state);
444
445     memset(state, 0, sizeof(game_state));
446     state->w = w;
447     state->h = h;
448     state->n = w*h;
449
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);
457
458     blank_game_into(state);
459
460     return state;
461 }
462
463 static void dup_game_to(game_state *to, const game_state *from)
464 {
465     to->completed = from->completed;
466     to->used_solve = from->used_solve;
467     to->impossible = from->impossible;
468
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));
472
473     memcpy(to->next, from->next, to->n*sizeof(int));
474     memcpy(to->prev, from->prev, to->n*sizeof(int));
475
476     memcpy(to->dsf, from->dsf, to->n*sizeof(int));
477     memcpy(to->numsi, from->numsi, (to->n+1)*sizeof(int));
478 }
479
480 static game_state *dup_game(const game_state *state)
481 {
482     game_state *ret = blank_game(state->w, state->h);
483     dup_game_to(ret, state);
484     return ret;
485 }
486
487 static void free_game(game_state *state)
488 {
489     sfree(state->dirs);
490     sfree(state->nums);
491     sfree(state->flags);
492     sfree(state->next);
493     sfree(state->prev);
494     sfree(state->dsf);
495     sfree(state->numsi);
496     sfree(state);
497 }
498
499 static void unpick_desc(const game_params *params, const char *desc,
500                         game_state **sout, char **mout)
501 {
502     game_state *state = blank_game(params->w, params->h);
503     char *msg = NULL, c;
504     int num = 0, i = 0;
505
506     while (*desc) {
507         if (i >= state->n) {
508             msg = "Game description longer than expected";
509             goto done;
510         }
511
512         c = *desc;
513         if (isdigit((unsigned char)c)) {
514             num = (num*10) + (int)(c-'0');
515             if (num > state->n) {
516                 msg = "Number too large";
517                 goto done;
518             }
519         } else if ((c-'a') >= 0 && (c-'a') < DIR_MAX) {
520             state->nums[i] = num;
521             state->flags[i] = num ? FLAG_IMMUTABLE : 0;
522             num = 0;
523
524             state->dirs[i] = c - 'a';
525             i++;
526         } else if (!*desc) {
527             msg = "Game description shorter than expected";
528             goto done;
529         } else {
530             msg = "Game description contains unexpected characters";
531             goto done;
532         }
533         desc++;
534     }
535     if (i < state->n) {
536         msg = "Game description shorter than expected";
537         goto done;
538     }
539
540 done:
541     if (msg) { /* sth went wrong. */
542         if (mout) *mout = msg;
543         free_game(state);
544     } else {
545         if (mout) *mout = NULL;
546         if (sout) *sout = state;
547         else free_game(state);
548     }
549 }
550
551 static char *generate_desc(game_state *state, int issolve)
552 {
553     char *ret, buf[80];
554     int retlen, i, k;
555
556     ret = NULL; retlen = 0;
557     if (issolve) {
558         ret = sresize(ret, 2, char);
559         ret[0] = 'S'; ret[1] = '\0';
560         retlen += 1;
561     }
562     for (i = 0; i < state->n; i++) {
563         if (state->nums[i])
564             k = sprintf(buf, "%d%c", state->nums[i], (int)(state->dirs[i]+'a'));
565         else
566             k = sprintf(buf, "%c", (int)(state->dirs[i]+'a'));
567         ret = sresize(ret, retlen + k + 1, char);
568         strcpy(ret + retlen, buf);
569         retlen += k;
570     }
571     return ret;
572 }
573
574 /* --- Game generation --- */
575
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)
580 {
581     int n = 0, a, x, y, sx, sy, dx, dy, newi;
582     int w = state->w, h = state->h;
583
584     sx = i % w; sy = i / w;
585
586     for (a = 0; a < DIR_MAX; a++) {
587         x = sx; y = sy;
588         dx = dxs[a]; dy = dys[a];
589         while (1) {
590             x += dx; y += dy;
591             if (x < 0 || y < 0 || x >= w || y >= h) break;
592
593             newi = y*w + x;
594             if (state->nums[newi] == 0) {
595                 ai[n] = newi;
596                 ad[n] = a;
597                 n++;
598             }
599         }
600     }
601     return n;
602 }
603
604 static int new_game_fill(game_state *state, random_state *rs,
605                          int headi, int taili)
606 {
607     int nfilled, an, ret = 0, j;
608     int *aidx, *adir;
609
610     aidx = snewn(state->n, int);
611     adir = snewn(state->n, int);
612
613     debug(("new_game_fill: headi=%d, taili=%d.", headi, taili));
614
615     memset(state->nums, 0, state->n*sizeof(int));
616
617     state->nums[headi] = 1;
618     state->nums[taili] = state->n;
619
620     state->dirs[taili] = 0;
621     nfilled = 2;
622     assert(state->n > 1);
623
624     while (nfilled < state->n) {
625         /* Try and expand _from_ headi; keep going if there's only one
626          * place to go to. */
627         an = cell_adj(state, headi, aidx, adir);
628         do {
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;
633             nfilled++;
634             headi = aidx[j];
635             an = cell_adj(state, headi, aidx, adir);
636         } while (an == 1);
637
638         if (nfilled == state->n) break;
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
662 done:
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
700 static int solve_state(game_state *state);
701
702 static 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. */
717 static 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         strip_nums(copy);
756         if (solve_state(copy) > 0) goto solved;
757         assert(check_nums(state, copy, 1));
758     }
759     ret = 0;
760     goto done;
761
762 solved:
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
767      * 1 and N. */
768     for (i = 0; i < state->n; i++) {
769         j = scratch[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);
776             strip_nums(copy);
777             if (solve_state(copy) > 0) {
778                 assert(check_nums(state, copy, 0));
779                 debug(("new_game_strip: OK, removing number"));
780             } else {
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;
785             }
786         }
787     }
788
789 done:
790     debug(("new_game_strip: %ssuccessful.", ret ? "" : "not "));
791     sfree(scratch);
792     free_game(copy);
793     return ret;
794 }
795
796 static char *new_game_desc(const game_params *params, random_state *rs,
797                            char **aux, int interactive)
798 {
799     game_state *state = blank_game(params->w, params->h);
800     char *ret;
801     int headi, taili;
802
803     /* this shouldn't happen (validate_params), but let's play it safe */
804     if (params->w == 1 && params->h == 1) return dupstr("1a");
805
806 generate:
807     blank_game_into(state);
808
809     /* keep trying until we fill successfully. */
810     do {
811         if (params->force_corner_start) {
812             headi = 0;
813             taili = state->n-1;
814         } else {
815             do {
816                 headi = random_upto(rs, state->n);
817                 taili = random_upto(rs, state->n);
818             } while (headi == taili);
819         }
820     } while (!new_game_fill(state, rs, headi, taili));
821
822     debug_state("Filled game:", state);
823
824     assert(state->nums[headi] <= state->n);
825     assert(state->nums[taili] <= state->n);
826
827     state->flags[headi] |= FLAG_IMMUTABLE;
828     state->flags[taili] |= FLAG_IMMUTABLE;
829
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)) {
833         goto generate;
834     }
835     strip_nums(state);
836     {
837         game_state *tosolve = dup_game(state);
838         assert(solve_state(tosolve) > 0);
839         free_game(tosolve);
840     }
841     ret = generate_desc(state, 0);
842     free_game(state);
843     return ret;
844 }
845
846 static char *validate_desc(const game_params *params, const char *desc)
847 {
848     char *ret = NULL;
849
850     unpick_desc(params, desc, NULL, &ret);
851     return ret;
852 }
853
854 /* --- Linked-list and numbers array --- */
855
856 /* Assuming numbers are always up-to-date, there are only four possibilities
857  * for regions changing after a single valid move:
858  *
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).
867  *
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
870  * previous move.
871  *
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.
875  */
876
877 #define COLOUR(a) ((a) / (state->n+1))
878 #define START(c) ((c) * (state->n+1))
879
880 struct head_meta {
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) */
885     const char *why;
886 };
887
888 static void head_number(game_state *state, int i, struct head_meta *head)
889 {
890     int off = 0, ss, j = i, c, n, sz;
891
892     /* Insist we really were passed the head of a chain. */
893     assert(state->prev[i] == -1 && state->next[i] != -1);
894
895     head->i = i;
896     head->sz = dsf_size(state->dsf, i);
897     head->why = NULL;
898
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;
902     while (j != -1) {
903         if (state->flags[j] & FLAG_IMMUTABLE) {
904             ss = state->nums[j] - off;
905             if (!head->preference) {
906                 head->start = ss;
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;
912             }
913         }
914         off++;
915         j = state->next[j];
916         assert(j != i); /* we have created a loop, obviously wrong */
917     }
918     if (head->preference) goto done;
919
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. */
931         head->start = 0;
932         head->preference = 0;
933         head->why = "lowest available colour group";
934     } else {
935         c = COLOUR(state->nums[i]);
936         n = 1;
937         sz = dsf_size(state->dsf, i);
938         j = i;
939         while (state->next[j] != -1) {
940             j = state->next[j];
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";
945                 goto done;
946             }
947             if (COLOUR(state->nums[j]) == c)
948                 n++;
949             else {
950                 int start_alternate = START(COLOUR(state->nums[j]));
951                 if (n < (sz - n)) {
952                     head->start = start_alternate;
953                     head->preference = 1;
954                     head->why = "joining two coloured regions, swapping to larger colour";
955                 } else {
956                     head->start = START(c);
957                     head->preference = 1;
958                     head->why = "joining two coloured regions, taking largest";
959                 }
960                 goto done;
961             }
962         }
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. */
965         if (c == 0) {
966             /* not convinced this shouldn't be an assertion failure here. */
967             head->start = 0;
968             head->preference = 0;
969         } else {
970             head->start = START(c);
971             head->preference = 1;
972         }
973         head->why = "got to end of coloured region";
974     }
975
976 done:
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));
982     else
983         debug(("Chain at (%d,%d) using next available colour: %s.",
984                head->i%state->w, head->i/state->w,
985                head->why));
986 }
987
988 #if 0
989 static void debug_numbers(game_state *state)
990 {
991     int i, w=state->w;
992
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,
997                i%w, i/w,
998                state->next[i]==-1 ? -1 : state->next[i]%w,
999                state->next[i]==-1 ? -1 : state->next[i]/w));
1000     }
1001     w = w+1;
1002 }
1003 #endif
1004
1005 static void connect_numbers(game_state *state)
1006 {
1007     int i, di, dni;
1008
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]);
1015             if (di == dni) {
1016                 debug(("connect_numbers: chain forms a loop."));
1017                 state->impossible = 1;
1018             }
1019             dsf_merge(state->dsf, di, dni);
1020         }
1021     }
1022 }
1023
1024 static int compare_heads(const void *a, const void *b)
1025 {
1026     struct head_meta *ha = (struct head_meta *)a;
1027     struct head_meta *hb = (struct head_meta *)b;
1028
1029     /* Heads with preferred colours first... */
1030     if (ha->preference && !hb->preference) return -1;
1031     if (hb->preference && !ha->preference) return 1;
1032
1033     /* ...then heads with low colours first... */
1034     if (ha->start < hb->start) return -1;
1035     if (ha->start > hb->start) return 1;
1036
1037     /* ... then large regions first... */
1038     if (ha->sz > hb->sz) return -1;
1039     if (ha->sz < hb->sz) return 1;
1040
1041     /* ... then position. */
1042     if (ha->i > hb->i) return -1;
1043     if (ha->i < hb->i) return 1;
1044
1045     return 0;
1046 }
1047
1048 static int lowest_start(game_state *state, struct head_meta *heads, int nheads)
1049 {
1050     int n, c;
1051
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)
1056                 goto used;
1057         }
1058         return c;
1059 used:
1060         ;
1061     }
1062     assert(!"No available colours!");
1063     return 0;
1064 }
1065
1066 static void update_numbers(game_state *state)
1067 {
1068     int i, j, n, nnum, nheads;
1069     struct head_meta *heads = snewn(state->n, struct head_meta);
1070
1071     for (n = 0; n < state->n; n++)
1072         state->numsi[n] = -1;
1073
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;
1079         }
1080         else if (state->prev[i] == -1 && state->next[i] == -1)
1081             state->nums[i] = 0;
1082     }
1083     connect_numbers(state);
1084
1085     /* Construct an array of the heads of all current regions, together
1086      * with their preferred colours. */
1087     nheads = 0;
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;
1092
1093         head_number(state, i, &heads[nheads++]);
1094     }
1095
1096     /* Sort that array:
1097      * - heads with preferred colours first, then
1098      * - heads with low colours first, then
1099      * - large regions first
1100      */
1101     qsort(heads, nheads, sizeof(struct head_meta), compare_heads);
1102
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' */
1111         }
1112         else if (!heads[n].preference) {
1113             assert(heads[n].start == 0);
1114             heads[n].start = START(lowest_start(state, heads, nheads));
1115         }
1116     }
1117
1118     debug(("Region colouring after duplicate removal:"));
1119
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)" : ""));
1126
1127         nnum = heads[n].start;
1128         j = heads[n].i;
1129         while (j != -1) {
1130             if (!(state->flags[j] & FLAG_IMMUTABLE)) {
1131                 if (nnum > 0 && nnum <= state->n)
1132                     state->numsi[nnum] = j;
1133                 state->nums[j] = nnum;
1134             }
1135             nnum++;
1136             j = state->next[j];
1137             assert(j != heads[n].i); /* loop?! */
1138         }
1139     }
1140     /*debug_numbers(state);*/
1141     sfree(heads);
1142 }
1143
1144 static int check_completion(game_state *state, int mark_errors)
1145 {
1146     int n, j, k, error = 0, complete;
1147
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). */
1153     if (mark_errors) {
1154         for (j = 0; j < state->n; j++)
1155             state->flags[j] &= ~FLAG_ERROR;
1156     }
1157
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]) {
1163                     if (mark_errors) {
1164                         state->flags[j] |= FLAG_ERROR;
1165                         state->flags[k] |= FLAG_ERROR;
1166                     }
1167                     error = 1;
1168                 }
1169             }
1170         }
1171     }
1172
1173     /* Search and mark numbers n not pointing to n+1; if any numbers
1174      * are missing we know we've not completed. */
1175     complete = 1;
1176     for (n = 1; n < state->n; n++) {
1177         if (state->numsi[n] == -1 || state->numsi[n+1] == -1)
1178             complete = 0;
1179         else if (!ispointingi(state, state->numsi[n], state->numsi[n+1])) {
1180             if (mark_errors) {
1181                 state->flags[state->numsi[n]] |= FLAG_ERROR;
1182                 state->flags[state->numsi[n+1]] |= FLAG_ERROR;
1183             }
1184             error = 1;
1185         } else {
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. */
1189             if (mark_errors)
1190                 makelink(state, state->numsi[n], state->numsi[n+1]);
1191         }
1192     }
1193
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))) {
1199             error = 1;
1200             if (mark_errors)
1201                 state->flags[n] |= FLAG_ERROR;
1202         }
1203     }
1204
1205     if (error) return 0;
1206     return complete;
1207 }
1208 static game_state *new_game(midend *me, const game_params *params,
1209                             const char *desc)
1210 {
1211     game_state *state = NULL;
1212
1213     unpick_desc(params, desc, &state, NULL);
1214     if (!state) assert(!"new_game failed to unpick");
1215
1216     update_numbers(state);
1217     check_completion(state, 1); /* update any auto-links */
1218
1219     return state;
1220 }
1221
1222 /* --- Solver --- */
1223
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)
1227 {
1228     int i, j, sx, sy, x, y, d, poss, w=state->w, nlinks = 0;
1229
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. */
1234
1235     memset(from, -1, state->n*sizeof(int));
1236
1237     /* poss is 'can I link to anything' with the same meanings. */
1238
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. */
1242
1243         d = state->dirs[i];
1244         poss = -1;
1245         sx = x = i%w; sy = y = i/w;
1246         while (1) {
1247             x += dxs[d]; y += dys[d];
1248             if (!INGRID(state, x, y)) break;
1249             if (!isvalidmove(state, 1, sx, sy, x, y)) continue;
1250
1251             /* can't link to somewhere with a back-link we would have to
1252              * break (the solver just doesn't work like this). */
1253             j = y*w+x;
1254             if (state->prev[j] != -1) continue;
1255
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."));
1260                 poss = j;
1261                 from[j] = i;
1262                 break;
1263             }
1264
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;
1268
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;
1272         }
1273         if (poss == -2) {
1274             /*debug(("Solver: (%d,%d) has multiple possible next squares.", sx, sy));*/
1275             ;
1276         } else if (poss == -1) {
1277             debug(("Solver: nowhere possible for (%d,%d) to link to.", sx, sy));
1278             copy->impossible = 1;
1279             return -1;
1280         } else {
1281             debug(("Solver: linking (%d,%d) to only possible next (%d,%d).",
1282                    sx, sy, poss%w, poss/w));
1283             makelink(copy, i, poss);
1284             nlinks++;
1285         }
1286     }
1287
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. */
1291
1292         x = i%w; y = i/w;
1293         if (from[i] == -1) {
1294             debug(("Solver: nowhere possible to link to (%d,%d)", x, y));
1295             copy->impossible = 1;
1296             return -1;
1297         } else if (from[i] == -2) {
1298             /*debug(("Solver: (%d,%d) has multiple possible prev squares.", x, y));*/
1299             ;
1300         } else {
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);
1304             nlinks++;
1305         }
1306     }
1307
1308     return nlinks;
1309 }
1310
1311 /* Returns 1 if we managed to solve it, 0 otherwise. */
1312 static int solve_state(game_state *state)
1313 {
1314     game_state *copy = dup_game(state);
1315     int *scratch = snewn(state->n, int), ret;
1316
1317     debug_state("Before solver: ", state);
1318
1319     while (1) {
1320         update_numbers(state);
1321
1322         if (solve_single(state, copy, scratch)) {
1323             dup_game_to(state, copy);
1324             if (state->impossible) break; else continue;
1325         }
1326         break;
1327     }
1328     free_game(copy);
1329     sfree(scratch);
1330
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);
1336     return ret;
1337 }
1338
1339 static char *solve_game(const game_state *state, const game_state *currstate,
1340                         const char *aux, char **error)
1341 {
1342     game_state *tosolve;
1343     char *ret = NULL;
1344     int result;
1345
1346     tosolve = dup_game(currstate);
1347     result = solve_state(tosolve);
1348     if (result > 0)
1349         ret = generate_desc(tosolve, 1);
1350     free_game(tosolve);
1351     if (ret) return ret;
1352
1353     tosolve = dup_game(state);
1354     result = solve_state(tosolve);
1355     if (result < 0)
1356         *error = "Puzzle is impossible.";
1357     else if (result == 0)
1358         *error = "Unable to solve puzzle.";
1359     else
1360         ret = generate_desc(tosolve, 1);
1361
1362     free_game(tosolve);
1363
1364     return ret;
1365 }
1366
1367 /* --- UI and move routines. --- */
1368
1369
1370 struct game_ui {
1371     int cx, cy, cshow;
1372
1373     int dragging, drag_is_from;
1374     int sx, sy;         /* grid coords of start cell */
1375     int dx, dy;         /* pixel coords of drag posn */
1376 };
1377
1378 static game_ui *new_ui(const game_state *state)
1379 {
1380     game_ui *ui = snew(game_ui);
1381
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. */
1384
1385     ui->cx = ui->cy = ui->cshow = 0;
1386
1387     ui->dragging = 0;
1388     ui->sx = ui->sy = ui->dx = ui->dy = 0;
1389
1390     return ui;
1391 }
1392
1393 static void free_ui(game_ui *ui)
1394 {
1395     sfree(ui);
1396 }
1397
1398 static char *encode_ui(const game_ui *ui)
1399 {
1400     return NULL;
1401 }
1402
1403 static void decode_ui(game_ui *ui, const char *encoding)
1404 {
1405 }
1406
1407 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1408                                const game_state *newstate)
1409 {
1410     if (!oldstate->completed && newstate->completed)
1411         ui->cshow = ui->dragging = 0;
1412 }
1413
1414 struct game_drawstate {
1415     int tilesize, started, solved;
1416     int w, h, n;
1417     int *nums, *dirp;
1418     unsigned int *f;
1419     double angle_offset;
1420
1421     int dragging, dx, dy;
1422     blitter *dragb;
1423 };
1424
1425 static char *interpret_move(const game_state *state, game_ui *ui,
1426                             const game_drawstate *ds,
1427                             int mx, int my, int button)
1428 {
1429     int x = FROMCOORD(mx), y = FROMCOORD(my), w = state->w;
1430     char buf[80];
1431
1432     if (IS_CURSOR_MOVE(button)) {
1433         move_cursor(button, &ui->cx, &ui->cy, state->w, state->h, 0);
1434         ui->cshow = 1;
1435         if (ui->dragging) {
1436             ui->dx = COORD(ui->cx) + TILE_SIZE/2;
1437             ui->dy = COORD(ui->cy) + TILE_SIZE/2;
1438         }
1439         return UI_UPDATE;
1440     } else if (IS_CURSOR_SELECT(button)) {
1441         if (!ui->cshow)
1442             ui->cshow = 1;
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))
1448                     return UI_UPDATE;
1449                 sprintf(buf, "L%d,%d-%d,%d", ui->sx, ui->sy, ui->cx, ui->cy);
1450             } else {
1451                 if (!isvalidmove(state, 0, ui->cx, ui->cy, ui->sx, ui->sy))
1452                     return UI_UPDATE;
1453                 sprintf(buf, "L%d,%d-%d,%d", ui->cx, ui->cy, ui->sx, ui->sy);
1454             }
1455             return dupstr(buf);
1456         } else {
1457             ui->dragging = TRUE;
1458             ui->sx = ui->cx;
1459             ui->sy = ui->cy;
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;
1463         }
1464         return UI_UPDATE;
1465     }
1466     if (IS_MOUSE_DOWN(button)) {
1467         if (ui->cshow) {
1468             ui->cshow = ui->dragging = 0;
1469         }
1470         assert(!ui->dragging);
1471         if (!INGRID(state, x, y)) return NULL;
1472
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))
1477                 return NULL;
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))
1482                 return NULL;
1483         }
1484
1485         ui->dragging = TRUE;
1486         ui->drag_is_from = (button == LEFT_BUTTON) ? 1 : 0;
1487         ui->sx = x;
1488         ui->sy = y;
1489         ui->dx = mx;
1490         ui->dy = my;
1491         ui->cshow = 0;
1492         return UI_UPDATE;
1493     } else if (IS_MOUSE_DRAG(button) && ui->dragging) {
1494         ui->dx = mx;
1495         ui->dy = my;
1496         return UI_UPDATE;
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 */
1500
1501         if (!INGRID(state, x, y)) {
1502             int si = ui->sy*w+ui->sx;
1503             if (state->prev[si] == -1 && state->next[si] == -1)
1504                 return UI_UPDATE;
1505             sprintf(buf, "%c%d,%d",
1506                     (int)(ui->drag_is_from ? 'C' : 'X'), ui->sx, ui->sy);
1507             return dupstr(buf);
1508         }
1509
1510         if (ui->drag_is_from) {
1511             if (!isvalidmove(state, 0, ui->sx, ui->sy, x, y))
1512                 return UI_UPDATE;
1513             sprintf(buf, "L%d,%d-%d,%d", ui->sx, ui->sy, x, y);
1514         } else {
1515             if (!isvalidmove(state, 0, x, y, ui->sx, ui->sy))
1516                 return UI_UPDATE;
1517             sprintf(buf, "L%d,%d-%d,%d", x, y, ui->sx, ui->sy);
1518         }
1519         return dupstr(buf);
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)
1525             return UI_UPDATE;
1526         sprintf(buf, "%c%d,%d",
1527                 (int)((button == 'x') ? 'C' : 'X'), ui->cx, ui->cy);
1528         return dupstr(buf);
1529     }
1530
1531     return NULL;
1532 }
1533
1534 static void unlink_cell(game_state *state, int si)
1535 {
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;
1542     }
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;
1548     }
1549 }
1550
1551 static game_state *execute_move(const game_state *state, const char *move)
1552 {
1553     game_state *ret = NULL;
1554     int sx, sy, ex, ey, si, ei, w = state->w;
1555     char c;
1556
1557     debug(("move: %s", move));
1558
1559     if (move[0] == 'S') {
1560         game_params p;
1561         game_state *tmp;
1562         char *valid;
1563         int i;
1564
1565         p.w = state->w; p.h = state->h;
1566         valid = validate_desc(&p, move+1);
1567         if (valid) {
1568             debug(("execute_move: move not valid: %s", valid));
1569             return NULL;
1570         }
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];
1576         }
1577         free_game(tmp);
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;
1581
1582         ret = dup_game(state);
1583
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) {
1587         int sset;
1588
1589         if (c != 'C' && c != 'X') return NULL;
1590         if (!INGRID(state, sx, sy)) return NULL;
1591         si = sy*w+sx;
1592         if (state->prev[si] == -1 && state->next[si] == -1)
1593             return NULL;
1594
1595         ret = dup_game(state);
1596
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);
1601         } else {
1602             int i, set;
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. */
1606
1607                 if (state->nums[i] == 0) continue;
1608                 set = state->nums[i] / (state->n+1);
1609                 if (set != sset) continue;
1610
1611                 unlink_cell(ret, i);
1612             }
1613         }
1614     } else if (strcmp(move, "H") == 0) {
1615         ret = dup_game(state);
1616         solve_state(ret);
1617     }
1618     if (ret) {
1619         update_numbers(ret);
1620         if (check_completion(ret, 1)) ret->completed = 1;
1621     }
1622
1623     return ret;
1624 }
1625
1626 /* ----------------------------------------------------------------------
1627  * Drawing routines.
1628  */
1629
1630 static void game_compute_size(const game_params *params, int tilesize,
1631                               int *x, int *y)
1632 {
1633     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1634     struct { int tilesize, order; } ads, *ds = &ads;
1635     ads.tilesize = tilesize;
1636
1637     *x = TILE_SIZE * params->w + 2 * BORDER;
1638     *y = TILE_SIZE * params->h + 2 * BORDER;
1639 }
1640
1641 static void game_set_size(drawing *dr, game_drawstate *ds,
1642                           const game_params *params, int tilesize)
1643 {
1644     ds->tilesize = tilesize;
1645     assert(TILE_SIZE > 0);
1646
1647     assert(!ds->dragb);
1648     ds->dragb = blitter_new(dr, BLITTER_SIZE, BLITTER_SIZE);
1649 }
1650
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 */
1664 };
1665
1666 static float *game_colours(frontend *fe, int *ncolours)
1667 {
1668     float *ret = snewn(3 * NCOLOURS, float);
1669     int c, i;
1670
1671     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
1672
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;
1678     }
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;
1682
1683     ret[COL_ERROR * 3 + 0] = 1.0F;
1684     ret[COL_ERROR * 3 + 1] = 0.0F;
1685     ret[COL_ERROR * 3 + 2] = 0.0F;
1686
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;
1690
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;
1695     }
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;
1700         }
1701     }
1702
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]); \
1706 } while (0)
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);
1715     }
1716
1717     *ncolours = NCOLOURS;
1718     return ret;
1719 }
1720
1721 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1722 {
1723     struct game_drawstate *ds = snew(struct game_drawstate);
1724     int i;
1725
1726     ds->tilesize = ds->started = ds->solved = 0;
1727     ds->w = state->w;
1728     ds->h = state->h;
1729     ds->n = state->n;
1730
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++) {
1735         ds->nums[i] = 0;
1736         ds->dirp[i] = -1;
1737         ds->f[i] = 0;
1738     }
1739
1740     ds->angle_offset = 0.0F;
1741
1742     ds->dragging = ds->dx = ds->dy = 0;
1743     ds->dragb = NULL;
1744
1745     return ds;
1746 }
1747
1748 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1749 {
1750     sfree(ds->nums);
1751     sfree(ds->dirp);
1752     sfree(ds->f);
1753     if (ds->dragb) blitter_free(dr, ds->dragb);
1754
1755     sfree(ds);
1756 }
1757
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)
1762 {
1763     int coords[14];
1764     int xdx, ydx, xdy, ydy, xdx3, xdy3;
1765     double s = sin(ang), c = cos(ang);
1766
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;
1771     ydx = -xdy;
1772     ydy = xdx;
1773
1774
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;
1789
1790     draw_polygon(dr, coords, 7, cfill, cout);
1791 }
1792
1793 static void draw_arrow_dir(drawing *dr, int cx, int cy, int sz, int dir,
1794                            int cfill, int cout, double angle_offset)
1795 {
1796     double ang = 2.0 * PI * (double)dir / 8.0 + angle_offset;
1797     draw_arrow(dr, cx, cy, sz, ang, cfill, cout);
1798 }
1799
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)
1803 {
1804     int *coords, n;
1805     double a, r;
1806
1807     assert(npoints > 0);
1808
1809     coords = snewn(npoints * 2 * 2, int);
1810
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;
1814
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));
1818     }
1819     draw_polygon(dr, coords, npoints*2, cfill, cout);
1820     sfree(coords);
1821 }
1822
1823 static int num2col(game_drawstate *ds, int num)
1824 {
1825     int set = num / (ds->n+1);
1826
1827     if (num <= 0 || set == 0) return COL_B0;
1828     return COL_B0 + 1 + ((set-1) % 15);
1829 }
1830
1831 #define ARROW_HALFSZ (7 * TILE_SIZE / 32)
1832
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 */
1840
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)
1844 {
1845     int cb = TILE_SIZE / 16, textsz;
1846     char buf[20];
1847     int arrowcol, sarrowcol, setcol, textcol;
1848     int acx, acy, asz, empty = 0;
1849
1850     if (num == 0 && !(f & F_ARROW_POINT) && !(f & F_ARROW_INPOINT)) {
1851         empty = 1;
1852         /*
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.
1859          */
1860     }
1861
1862     /* Calculate colours. */
1863
1864     if (print_ink >= 0) {
1865         /*
1866          * We're printing, so just do everything in black.
1867          */
1868         arrowcol = textcol = print_ink;
1869         setcol = sarrowcol = -1;       /* placate optimiser */
1870     } else {
1871
1872         setcol = empty ? COL_BACKGROUND : num2col(ds, num);
1873
1874 #define dim(fg,bg) ( \
1875       (bg)==COL_BACKGROUND ? COL_ARROW_BG_DIM : \
1876       (bg) + COL_D0 - COL_B0 \
1877     )
1878
1879 #define mid(fg,bg) ( \
1880       (fg)==COL_NUMBER_SET ? COL_NUMBER_SET_MID : \
1881       (bg) + COL_M0 - COL_B0 \
1882     )
1883
1884 #define dimbg(bg) ( \
1885       (bg)==COL_BACKGROUND ? COL_BACKGROUND : \
1886       (bg) + COL_X0 - COL_B0 \
1887     )
1888
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;
1893
1894         if ((f & F_ERROR) && !(f & F_IMMUTABLE)) textcol = COL_ERROR;
1895         else {
1896             if (f & F_IMMUTABLE) textcol = COL_NUMBER_SET;
1897             else textcol = COL_NUMBER;
1898
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);
1903         }
1904
1905         if (f & F_DIM) sarrowcol = dim(COL_ARROW, setcol);
1906         else sarrowcol = COL_ARROW;
1907     }
1908
1909     /* Clear tile background */
1910
1911     if (print_ink < 0) {
1912         draw_rect(dr, tx, ty, TILE_SIZE, TILE_SIZE,
1913                   (f & F_DIM) ? dimbg(setcol) : setcol);
1914     }
1915
1916     /* Draw large (outwards-pointing) arrow. */
1917
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 */
1921
1922     if (num == ds->n && (f & F_IMMUTABLE))
1923         draw_star(dr, acx, acy, asz, 5, arrowcol, arrowcol, angle_offset);
1924     else
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);
1928
1929     /* Draw dot iff this tile requires a predecessor and doesn't have one. */
1930
1931     if (print_ink < 0) {
1932         acx = tx+TILE_SIZE/2-asz;
1933         acy = ty+TILE_SIZE/2+asz;
1934
1935         if (!(f & F_ARROW_INPOINT) && num != 1) {
1936             draw_circle(dr, acx, acy, asz / 4, sarrowcol, sarrowcol);
1937         }
1938     }
1939
1940     /* Draw text (number or set). */
1941
1942     if (!empty) {
1943         int set = (num <= 0) ? 0 : num / (ds->n+1);
1944
1945         char *p = buf;
1946         if (set == 0 || num <= 0) {
1947             sprintf(buf, "%d", num);
1948         } else {
1949             int n = num % (ds->n+1);
1950             p += sizeof(buf) - 1;
1951
1952             if (n != 0) {
1953                 sprintf(buf, "+%d", n);  /* Just to get the length... */
1954                 p -= strlen(buf);
1955                 sprintf(p, "+%d", n);
1956             } else {
1957                 *p = '\0';
1958             }
1959             do {
1960                 set--;
1961                 p--;
1962                 *p = (char)((set % 26)+'a');
1963                 set /= 26;
1964             } while (set);
1965         }
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);
1969     }
1970
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);
1974     }
1975 }
1976
1977 static void draw_drag_indicator(drawing *dr, game_drawstate *ds,
1978                                 const game_state *state, const game_ui *ui,
1979                                 int validdrag)
1980 {
1981     int dir, w = ds->w, acol = COL_ARROW;
1982     int fx = FROMCOORD(ui->dx), fy = FROMCOORD(ui->dy);
1983     double ang;
1984
1985     if (validdrag) {
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];
1988
1989         ang = (2.0 * PI * dir) / 8.0; /* similar to calculation in draw_arrow_dir. */
1990     } else {
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);
1995
1996         if (xdiff == 0) {
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;
2000         } else {
2001             if (ui->dx > ox && ui->dy < oy) {
2002                 tana = xdiff / ydiff;
2003                 offset = 0.0F;
2004             } else if (ui->dx > ox && ui->dy > oy) {
2005                 tana = ydiff / xdiff;
2006                 offset = PI/2.0F;
2007             } else if (ui->dx < ox && ui->dy > oy) {
2008                 tana = xdiff / ydiff;
2009                 offset = PI;
2010             } else {
2011                 tana = ydiff / xdiff;
2012                 offset = 3.0F * PI / 2.0F;
2013             }
2014             ang = atan(tana) + offset;
2015         }
2016
2017         if (!ui->drag_is_from) ang += PI; /* point to origin, not away from. */
2018
2019     }
2020     draw_arrow(dr, ui->dx, ui->dy, ARROW_HALFSZ, ang, acol, acol);
2021 }
2022
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)
2027 {
2028     int x, y, i, w = ds->w, dirp, force = 0;
2029     unsigned int f;
2030     double angle_offset = 0.0;
2031     game_state *postdrop = NULL;
2032
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;
2037         force = 1;
2038     }
2039
2040     if (ds->dragging) {
2041         assert(ds->dragb);
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;
2045     }
2046
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. */
2051     if (ui->dragging) {
2052         game_ui uicopy = *ui;
2053         char *movestr = interpret_move(state, &uicopy, ds, ui->dx, ui->dy, LEFT_RELEASE);
2054
2055         if (movestr != NULL && strcmp(movestr, "") != 0) {
2056             postdrop = execute_move(state, movestr);
2057             sfree(movestr);
2058
2059             state = postdrop;
2060         }
2061     }
2062
2063     if (!ds->started) {
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);
2069     }
2070     for (x = 0; x < state->w; x++) {
2071         for (y = 0; y < state->h; y++) {
2072             i = y*w + x;
2073             f = 0;
2074             dirp = -1;
2075
2076             if (ui->cshow && x == ui->cx && y == ui->cy)
2077                 f |= F_CUR;
2078
2079             if (ui->dragging) {
2080                 if (x == ui->sx && y == ui->sy)
2081                     f |= F_DRAG_SRC;
2082                 else if (ui->drag_is_from) {
2083                     if (!ispointing(state, ui->sx, ui->sy, x, y))
2084                         f |= F_DIM;
2085                 } else {
2086                     if (!ispointing(state, x, y, ui->sx, ui->sy))
2087                         f |= F_DIM;
2088                 }
2089             }
2090
2091             if (state->impossible ||
2092                 state->nums[i] < 0 || state->flags[i] & FLAG_ERROR)
2093                 f |= F_ERROR;
2094             if (state->flags[i] & FLAG_IMMUTABLE)
2095                 f |= F_IMMUTABLE;
2096
2097             if (state->next[i] != -1)
2098                 f |= F_ARROW_POINT;
2099
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);
2106             }
2107
2108             if (state->nums[i] != ds->nums[i] ||
2109                 f != ds->f[i] || dirp != ds->dirp[i] ||
2110                 force || !ds->started) {
2111                 int sign;
2112                 {
2113                     /*
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 :-)
2122                      */
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'));
2127                     }
2128                     if (gear_mode)
2129                         sign = 1 - 2 * ((x ^ y) & 1);
2130                     else
2131                         sign = 1;
2132                 }
2133                 tile_redraw(dr, ds,
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];
2139                 ds->f[i] = f;
2140                 ds->dirp[i] = dirp;
2141             }
2142         }
2143     }
2144     if (ui->dragging) {
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);
2149
2150         draw_drag_indicator(dr, ds, state, ui, postdrop ? 1 : 0);
2151     }
2152     if (postdrop) free_game(postdrop);
2153     if (!ds->started) ds->started = TRUE;
2154 }
2155
2156 static float game_anim_length(const game_state *oldstate,
2157                               const game_state *newstate, int dir, game_ui *ui)
2158 {
2159     return 0.0F;
2160 }
2161
2162 static float game_flash_length(const game_state *oldstate,
2163                                const game_state *newstate, int dir, game_ui *ui)
2164 {
2165     if (!oldstate->completed &&
2166         newstate->completed && !newstate->used_solve)
2167         return FLASH_SPIN;
2168     else
2169         return 0.0F;
2170 }
2171
2172 static int game_status(const game_state *state)
2173 {
2174     return state->completed ? +1 : 0;
2175 }
2176
2177 static int game_timing_state(const game_state *state, game_ui *ui)
2178 {
2179     return TRUE;
2180 }
2181
2182 static void game_print_size(const game_params *params, float *x, float *y)
2183 {
2184     int pw, ph;
2185
2186     game_compute_size(params, 1300, &pw, &ph);
2187     *x = pw / 100.0F;
2188     *y = ph / 100.0F;
2189 }
2190
2191 static void game_print(drawing *dr, const game_state *state, int tilesize)
2192 {
2193     int ink = print_mono_colour(dr, 0);
2194     int x, y;
2195
2196     /* Fake up just enough of a drawstate */
2197     game_drawstate ads, *ds = &ads;
2198     ds->tilesize = tilesize;
2199     ds->n = state->n;
2200
2201     /*
2202      * Border and grid.
2203      */
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);
2212
2213     /*
2214      * Arrows and numbers.
2215      */
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);
2221 }
2222
2223 #ifdef COMBINED
2224 #define thegame signpost
2225 #endif
2226
2227 const struct game thegame = {
2228     "Signpost", "games.signpost", "signpost",
2229     default_params,
2230     game_fetch_preset, NULL,
2231     decode_params,
2232     encode_params,
2233     free_params,
2234     dup_params,
2235     TRUE, game_configure, custom_params,
2236     validate_params,
2237     new_game_desc,
2238     validate_desc,
2239     new_game,
2240     dup_game,
2241     free_game,
2242     TRUE, solve_game,
2243     TRUE, game_can_format_as_text_now, game_text_format,
2244     new_ui,
2245     free_ui,
2246     encode_ui,
2247     decode_ui,
2248     game_changed_state,
2249     interpret_move,
2250     execute_move,
2251     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2252     game_colours,
2253     game_new_drawstate,
2254     game_free_drawstate,
2255     game_redraw,
2256     game_anim_length,
2257     game_flash_length,
2258     game_status,
2259     TRUE, FALSE, game_print_size, game_print,
2260     FALSE,                             /* wants_statusbar */
2261     FALSE, game_timing_state,
2262     REQUIRE_RBUTTON,                   /* flags */
2263 };
2264
2265 #ifdef STANDALONE_SOLVER
2266
2267 #include <time.h>
2268 #include <stdarg.h>
2269
2270 const char *quis = NULL;
2271 int verbose = 0;
2272
2273 void usage(FILE *out) {
2274     fprintf(out, "usage: %s [--stdin] [--soak] [--seed SEED] <params>|<game id>\n", quis);
2275 }
2276
2277 static void cycle_seed(char **seedstr, random_state *rs)
2278 {
2279     char newseed[16];
2280     int j;
2281
2282     newseed[15] = '\0';
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);
2286     sfree(*seedstr);
2287     *seedstr = dupstr(newseed);
2288 }
2289
2290 static void start_soak(game_params *p, char *seedstr)
2291 {
2292     time_t tt_start, tt_now, tt_last;
2293     char *desc, *aux;
2294     random_state *rs;
2295     long n = 0, nnums = 0, i;
2296     game_state *state;
2297
2298     tt_start = tt_now = time(NULL);
2299     printf("Soak-generating a %dx%d grid.\n", p->w, p->h);
2300
2301     while (1) {
2302        rs = random_new(seedstr, strlen(seedstr));
2303        desc = thegame.new_desc(p, rs, &aux, 0);
2304
2305        state = thegame.new_game(NULL, p, desc);
2306        for (i = 0; i < state->n; i++) {
2307            if (state->flags[i] & FLAG_IMMUTABLE)
2308                nnums++;
2309        }
2310        thegame.free_game(state);
2311
2312        sfree(desc);
2313        cycle_seed(&seedstr, rs);
2314        random_free(rs);
2315
2316        n++;
2317        tt_last = time(NULL);
2318        if (tt_last > tt_now) {
2319            tt_now = tt_last;
2320            printf("%ld total, %3.1f/s, %3.1f nums/grid (%3.1f%%).\n",
2321                   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) );
2325        }
2326     }
2327 }
2328
2329 static void process_desc(char *id)
2330 {
2331     char *desc, *err, *solvestr;
2332     game_params *p;
2333     game_state *s;
2334
2335     printf("%s\n  ", id);
2336
2337     desc = strchr(id, ':');
2338     if (!desc) {
2339         fprintf(stderr, "%s: expecting game description.", quis);
2340         exit(1);
2341     }
2342
2343     *desc++ = '\0';
2344
2345     p = thegame.default_params();
2346     thegame.decode_params(p, id);
2347     err = thegame.validate_params(p, 1);
2348     if (err) {
2349         fprintf(stderr, "%s: %s", quis, err);
2350         thegame.free_params(p);
2351         return;
2352     }
2353
2354     err = thegame.validate_desc(p, desc);
2355     if (err) {
2356         fprintf(stderr, "%s: %s\nDescription: %s\n", quis, err, desc);
2357         thegame.free_params(p);
2358         return;
2359     }
2360
2361     s = thegame.new_game(NULL, p, desc);
2362
2363     solvestr = thegame.solve(s, s, NULL, &err);
2364     if (!solvestr)
2365         fprintf(stderr, "%s\n", err);
2366     else
2367         printf("Puzzle is soluble.\n");
2368
2369     thegame.free_game(s);
2370     thegame.free_params(p);
2371 }
2372
2373 int main(int argc, const char *argv[])
2374 {
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];
2378
2379     setvbuf(stdout, NULL, _IONBF, 0);
2380
2381     quis = argv[0];
2382     while (--argc > 0) {
2383         char *p = (char*)(*++argv);
2384         if (!strcmp(p, "-v") || !strcmp(p, "--verbose"))
2385             verbose = 1;
2386         else if (!strcmp(p, "--stdin"))
2387             stdin_desc = 1;
2388         else if (!strcmp(p, "-e") || !strcmp(p, "--seed")) {
2389             seedstr = dupstr(*++argv);
2390             argc--;
2391         } else if (!strcmp(p, "-n") || !strcmp(p, "--number")) {
2392             n = atoi(*++argv);
2393             argc--;
2394         } else if (!strcmp(p, "-s") || !strcmp(p, "--soak")) {
2395             soak = 1;
2396         } else if (*p == '-') {
2397             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2398             usage(stderr);
2399             exit(1);
2400         } else {
2401             id = p;
2402         }
2403     }
2404
2405     sprintf(newseed, "%lu", (unsigned long) time(NULL));
2406     seedstr = dupstr(newseed);
2407
2408     if (id || !stdin_desc) {
2409         if (id && strchr(id, ':')) {
2410             /* Parameters and description passed on cmd-line:
2411              * try and solve it. */
2412             process_desc(id);
2413         } else {
2414             /* No description passed on cmd-line: decode parameters
2415              * (with optional seed too) */
2416
2417             game_params *p = thegame.default_params();
2418
2419             if (id) {
2420                 char *cmdseed = strchr(id, '#');
2421                 if (cmdseed) {
2422                     *cmdseed++ = '\0';
2423                     sfree(seedstr);
2424                     seedstr = dupstr(cmdseed);
2425                 }
2426
2427                 thegame.decode_params(p, id);
2428             }
2429
2430             err = thegame.validate_params(p, 1);
2431             if (err) {
2432                 fprintf(stderr, "%s: %s", quis, err);
2433                 thegame.free_params(p);
2434                 exit(1);
2435             }
2436
2437             /* We have a set of valid parameters; either soak with it
2438              * or generate a single game description and print to stdout. */
2439             if (soak)
2440                 start_soak(p, seedstr);
2441             else {
2442                 char *pstring = thegame.encode_params(p, 0);
2443
2444                 for (i = 0; i < n; i++) {
2445                     random_state *rs = random_new(seedstr, strlen(seedstr));
2446
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);
2450                     sfree(desc);
2451
2452                     cycle_seed(&seedstr, rs);
2453
2454                     random_free(rs);
2455                 }
2456
2457                 sfree(pstring);
2458             }
2459             thegame.free_params(p);
2460         }
2461     }
2462
2463     if (stdin_desc) {
2464         char buf[4096];
2465
2466         while (fgets(buf, sizeof(buf), stdin)) {
2467             buf[strcspn(buf, "\r\n")] = '\0';
2468             process_desc(buf);
2469         }
2470     }
2471     sfree(seedstr);
2472
2473     return 0;
2474 }
2475
2476 #endif
2477
2478
2479 /* vim: set shiftwidth=4 tabstop=8: */