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