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