Keyboard control patch for Twiddle, from James H.
[sgt-puzzles/ydirson.git] / bridges.c
blob18296817e8177daf854bff7a65994d031f4d8311
1 /*
2 * bridges.c: Implementation of the Nikoli game 'Bridges'.
4 * Things still to do:
6 * * write a recursive solver?
7 */
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <assert.h>
13 #include <ctype.h>
14 #include <math.h>
16 #include "puzzles.h"
18 /* Turn this on for hints about which lines are considered possibilities. */
19 #undef DRAW_HINTS
20 #undef DRAW_GRID
21 #undef DRAW_DSF
23 /* --- structures for params, state, etc. --- */
25 #define MAX_BRIDGES 4
27 #define PREFERRED_TILE_SIZE 24
28 #define TILE_SIZE (ds->tilesize)
29 #define BORDER (TILE_SIZE / 2)
31 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
32 #define FROMCOORD(x) ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
34 #define FLASH_TIME 0.50F
36 enum {
37 COL_BACKGROUND,
38 COL_FOREGROUND,
39 COL_HIGHLIGHT, COL_LOWLIGHT,
40 COL_SELECTED, COL_MARK,
41 COL_HINT, COL_GRID,
42 COL_WARNING,
43 NCOLOURS
46 struct game_params {
47 int w, h, maxb;
48 int islands, expansion; /* %age of island squares, %age chance of expansion */
49 int allowloops, difficulty;
52 /* general flags used by all structs */
53 #define G_ISLAND 0x0001
54 #define G_LINEV 0x0002 /* contains a vert. line */
55 #define G_LINEH 0x0004 /* contains a horiz. line (mutex with LINEV) */
56 #define G_LINE (G_LINEV|G_LINEH)
57 #define G_MARKV 0x0008
58 #define G_MARKH 0x0010
59 #define G_MARK (G_MARKV|G_MARKH)
60 #define G_NOLINEV 0x0020
61 #define G_NOLINEH 0x0040
62 #define G_NOLINE (G_NOLINEV|G_NOLINEH)
64 /* flags used by the drawstate */
65 #define G_ISSEL 0x0080
66 #define G_REDRAW 0x0100
67 #define G_FLASH 0x0200
68 #define G_WARN 0x0400
70 /* flags used by the solver etc. */
71 #define G_SWEEP 0x0800
73 #define G_FLAGSH (G_LINEH|G_MARKH|G_NOLINEH)
74 #define G_FLAGSV (G_LINEV|G_MARKV|G_NOLINEV)
76 typedef unsigned int grid_type; /* change me later if we invent > 16 bits of flags. */
78 struct solver_state {
79 int *dsf, *tmpdsf;
80 int refcount;
83 /* state->gridi is an optimisation; it stores the pointer to the island
84 * structs indexed by (x,y). It's not strictly necessary (we could use
85 * find234 instead), but Purify showed that board generation (mostly the solver)
86 * was spending 60% of its time in find234. */
88 struct surrounds { /* cloned from lightup.c */
89 struct { int x, y, dx, dy, off; } points[4];
90 int npoints, nislands;
93 struct island {
94 game_state *state;
95 int x, y, count;
96 struct surrounds adj;
99 struct game_state {
100 int w, h, completed, solved, allowloops, maxb;
101 grid_type *grid, *scratch;
102 struct island *islands;
103 int n_islands, n_islands_alloc;
104 game_params params; /* used by the aux solver. */
105 #define N_WH_ARRAYS 5
106 char *wha, *possv, *possh, *lines, *maxv, *maxh;
107 struct island **gridi;
108 struct solver_state *solver; /* refcounted */
111 #define GRIDSZ(s) ((s)->w * (s)->h * sizeof(grid_type))
113 #define INGRID(s,x,y) ((x) >= 0 && (x) < (s)->w && (y) >= 0 && (y) < (s)->h)
115 #define DINDEX(x,y) ((y)*state->w + (x))
117 #define INDEX(s,g,x,y) ((s)->g[(y)*((s)->w) + (x)])
118 #define IDX(s,g,i) ((s)->g[(i)])
119 #define GRID(s,x,y) INDEX(s,grid,x,y)
120 #define SCRATCH(s,x,y) INDEX(s,scratch,x,y)
121 #define POSSIBLES(s,dx,x,y) ((dx) ? (INDEX(s,possh,x,y)) : (INDEX(s,possv,x,y)))
122 #define MAXIMUM(s,dx,x,y) ((dx) ? (INDEX(s,maxh,x,y)) : (INDEX(s,maxv,x,y)))
124 #define GRIDCOUNT(s,x,y,f) ((GRID(s,x,y) & (f)) ? (INDEX(s,lines,x,y)) : 0)
126 #define WITHIN2(x,min,max) (((x) < (min)) ? 0 : (((x) > (max)) ? 0 : 1))
127 #define WITHIN(x,min,max) ((min) > (max) ? \
128 WITHIN2(x,max,min) : WITHIN2(x,min,max))
130 /* --- island struct and tree support functions --- */
132 #define ISLAND_ORTH(is,j,f,df) \
133 (is->f + (is->adj.points[(j)].off*is->adj.points[(j)].df))
135 #define ISLAND_ORTHX(is,j) ISLAND_ORTH(is,j,x,dx)
136 #define ISLAND_ORTHY(is,j) ISLAND_ORTH(is,j,y,dy)
138 static void fixup_islands_for_realloc(game_state *state)
140 int i;
142 for (i = 0; i < state->w*state->h; i++) state->gridi[i] = NULL;
143 for (i = 0; i < state->n_islands; i++) {
144 struct island *is = &state->islands[i];
145 is->state = state;
146 INDEX(state, gridi, is->x, is->y) = is;
150 static int game_can_format_as_text_now(game_params *params)
152 return TRUE;
155 static char *game_text_format(game_state *state)
157 int x, y, len, nl;
158 char *ret, *p;
159 struct island *is;
160 grid_type grid;
162 len = (state->h) * (state->w+1) + 1;
163 ret = snewn(len, char);
164 p = ret;
166 for (y = 0; y < state->h; y++) {
167 for (x = 0; x < state->w; x++) {
168 grid = GRID(state,x,y);
169 nl = INDEX(state,lines,x,y);
170 is = INDEX(state, gridi, x, y);
171 if (is) {
172 *p++ = '0' + is->count;
173 } else if (grid & G_LINEV) {
174 *p++ = (nl > 1) ? '"' : (nl == 1) ? '|' : '!'; /* gaah, want a double-bar. */
175 } else if (grid & G_LINEH) {
176 *p++ = (nl > 1) ? '=' : (nl == 1) ? '-' : '~';
177 } else {
178 *p++ = '.';
181 *p++ = '\n';
183 *p++ = '\0';
185 assert(p - ret == len);
186 return ret;
189 static void debug_state(game_state *state)
191 char *textversion = game_text_format(state);
192 debug(("%s", textversion));
193 sfree(textversion);
196 /*static void debug_possibles(game_state *state)
198 int x, y;
199 debug(("possh followed by possv\n"));
200 for (y = 0; y < state->h; y++) {
201 for (x = 0; x < state->w; x++) {
202 debug(("%d", POSSIBLES(state, 1, x, y)));
204 debug((" "));
205 for (x = 0; x < state->w; x++) {
206 debug(("%d", POSSIBLES(state, 0, x, y)));
208 debug(("\n"));
210 debug(("\n"));
211 for (y = 0; y < state->h; y++) {
212 for (x = 0; x < state->w; x++) {
213 debug(("%d", MAXIMUM(state, 1, x, y)));
215 debug((" "));
216 for (x = 0; x < state->w; x++) {
217 debug(("%d", MAXIMUM(state, 0, x, y)));
219 debug(("\n"));
221 debug(("\n"));
224 static void island_set_surrounds(struct island *is)
226 assert(INGRID(is->state,is->x,is->y));
227 is->adj.npoints = is->adj.nislands = 0;
228 #define ADDPOINT(cond,ddx,ddy) do {\
229 if (cond) { \
230 is->adj.points[is->adj.npoints].x = is->x+(ddx); \
231 is->adj.points[is->adj.npoints].y = is->y+(ddy); \
232 is->adj.points[is->adj.npoints].dx = (ddx); \
233 is->adj.points[is->adj.npoints].dy = (ddy); \
234 is->adj.points[is->adj.npoints].off = 0; \
235 is->adj.npoints++; \
236 } } while(0)
237 ADDPOINT(is->x > 0, -1, 0);
238 ADDPOINT(is->x < (is->state->w-1), +1, 0);
239 ADDPOINT(is->y > 0, 0, -1);
240 ADDPOINT(is->y < (is->state->h-1), 0, +1);
243 static void island_find_orthogonal(struct island *is)
245 /* fills in the rest of the 'surrounds' structure, assuming
246 * all other islands are now in place. */
247 int i, x, y, dx, dy, off;
249 is->adj.nislands = 0;
250 for (i = 0; i < is->adj.npoints; i++) {
251 dx = is->adj.points[i].dx;
252 dy = is->adj.points[i].dy;
253 x = is->x + dx;
254 y = is->y + dy;
255 off = 1;
256 is->adj.points[i].off = 0;
257 while (INGRID(is->state, x, y)) {
258 if (GRID(is->state, x, y) & G_ISLAND) {
259 is->adj.points[i].off = off;
260 is->adj.nislands++;
261 /*debug(("island (%d,%d) has orth is. %d*(%d,%d) away at (%d,%d).\n",
262 is->x, is->y, off, dx, dy,
263 ISLAND_ORTHX(is,i), ISLAND_ORTHY(is,i)));*/
264 goto foundisland;
266 off++; x += dx; y += dy;
268 foundisland:
273 static int island_hasbridge(struct island *is, int direction)
275 int x = is->adj.points[direction].x;
276 int y = is->adj.points[direction].y;
277 grid_type gline = is->adj.points[direction].dx ? G_LINEH : G_LINEV;
279 if (GRID(is->state, x, y) & gline) return 1;
280 return 0;
283 static struct island *island_find_connection(struct island *is, int adjpt)
285 struct island *is_r;
287 assert(adjpt < is->adj.npoints);
288 if (!is->adj.points[adjpt].off) return NULL;
289 if (!island_hasbridge(is, adjpt)) return NULL;
291 is_r = INDEX(is->state, gridi,
292 ISLAND_ORTHX(is, adjpt), ISLAND_ORTHY(is, adjpt));
293 assert(is_r);
295 return is_r;
298 static struct island *island_add(game_state *state, int x, int y, int count)
300 struct island *is;
301 int realloced = 0;
303 assert(!(GRID(state,x,y) & G_ISLAND));
304 GRID(state,x,y) |= G_ISLAND;
306 state->n_islands++;
307 if (state->n_islands > state->n_islands_alloc) {
308 state->n_islands_alloc = state->n_islands * 2;
309 state->islands =
310 sresize(state->islands, state->n_islands_alloc, struct island);
311 realloced = 1;
313 is = &state->islands[state->n_islands-1];
315 memset(is, 0, sizeof(struct island));
316 is->state = state;
317 is->x = x;
318 is->y = y;
319 is->count = count;
320 island_set_surrounds(is);
322 if (realloced)
323 fixup_islands_for_realloc(state);
324 else
325 INDEX(state, gridi, x, y) = is;
327 return is;
331 /* n = -1 means 'flip NOLINE flags [and set line to 0].' */
332 static void island_join(struct island *i1, struct island *i2, int n, int is_max)
334 game_state *state = i1->state;
335 int s, e, x, y;
337 assert(i1->state == i2->state);
338 assert(n >= -1 && n <= i1->state->maxb);
340 if (i1->x == i2->x) {
341 x = i1->x;
342 if (i1->y < i2->y) {
343 s = i1->y+1; e = i2->y-1;
344 } else {
345 s = i2->y+1; e = i1->y-1;
347 for (y = s; y <= e; y++) {
348 if (is_max) {
349 INDEX(state,maxv,x,y) = n;
350 } else {
351 if (n < 0) {
352 GRID(state,x,y) ^= G_NOLINEV;
353 } else if (n == 0) {
354 GRID(state,x,y) &= ~G_LINEV;
355 } else {
356 GRID(state,x,y) |= G_LINEV;
357 INDEX(state,lines,x,y) = n;
361 } else if (i1->y == i2->y) {
362 y = i1->y;
363 if (i1->x < i2->x) {
364 s = i1->x+1; e = i2->x-1;
365 } else {
366 s = i2->x+1; e = i1->x-1;
368 for (x = s; x <= e; x++) {
369 if (is_max) {
370 INDEX(state,maxh,x,y) = n;
371 } else {
372 if (n < 0) {
373 GRID(state,x,y) ^= G_NOLINEH;
374 } else if (n == 0) {
375 GRID(state,x,y) &= ~G_LINEH;
376 } else {
377 GRID(state,x,y) |= G_LINEH;
378 INDEX(state,lines,x,y) = n;
382 } else {
383 assert(!"island_join: islands not orthogonal.");
387 /* Counts the number of bridges currently attached to the island. */
388 static int island_countbridges(struct island *is)
390 int i, c = 0;
392 for (i = 0; i < is->adj.npoints; i++) {
393 c += GRIDCOUNT(is->state,
394 is->adj.points[i].x, is->adj.points[i].y,
395 is->adj.points[i].dx ? G_LINEH : G_LINEV);
397 /*debug(("island count for (%d,%d) is %d.\n", is->x, is->y, c));*/
398 return c;
401 static int island_adjspace(struct island *is, int marks, int missing,
402 int direction)
404 int x, y, poss, curr, dx;
405 grid_type gline, mline;
407 x = is->adj.points[direction].x;
408 y = is->adj.points[direction].y;
409 dx = is->adj.points[direction].dx;
410 gline = dx ? G_LINEH : G_LINEV;
412 if (marks) {
413 mline = dx ? G_MARKH : G_MARKV;
414 if (GRID(is->state,x,y) & mline) return 0;
416 poss = POSSIBLES(is->state, dx, x, y);
417 poss = min(poss, missing);
419 curr = GRIDCOUNT(is->state, x, y, gline);
420 poss = min(poss, MAXIMUM(is->state, dx, x, y) - curr);
422 return poss;
425 /* Counts the number of bridge spaces left around the island;
426 * expects the possibles to be up-to-date. */
427 static int island_countspaces(struct island *is, int marks)
429 int i, c = 0, missing;
431 missing = is->count - island_countbridges(is);
432 if (missing < 0) return 0;
434 for (i = 0; i < is->adj.npoints; i++) {
435 c += island_adjspace(is, marks, missing, i);
437 return c;
440 static int island_isadj(struct island *is, int direction)
442 int x, y;
443 grid_type gline, mline;
445 x = is->adj.points[direction].x;
446 y = is->adj.points[direction].y;
448 mline = is->adj.points[direction].dx ? G_MARKH : G_MARKV;
449 gline = is->adj.points[direction].dx ? G_LINEH : G_LINEV;
450 if (GRID(is->state, x, y) & mline) {
451 /* If we're marked (i.e. the thing to attach to is complete)
452 * only count an adjacency if we're already attached. */
453 return GRIDCOUNT(is->state, x, y, gline);
454 } else {
455 /* If we're unmarked, count possible adjacency iff it's
456 * flagged as POSSIBLE. */
457 return POSSIBLES(is->state, is->adj.points[direction].dx, x, y);
459 return 0;
462 /* Counts the no. of possible adjacent islands (including islands
463 * we're already connected to). */
464 static int island_countadj(struct island *is)
466 int i, nadj = 0;
468 for (i = 0; i < is->adj.npoints; i++) {
469 if (island_isadj(is, i)) nadj++;
471 return nadj;
474 static void island_togglemark(struct island *is)
476 int i, j, x, y, o;
477 struct island *is_loop;
479 /* mark the island... */
480 GRID(is->state, is->x, is->y) ^= G_MARK;
482 /* ...remove all marks on non-island squares... */
483 for (x = 0; x < is->state->w; x++) {
484 for (y = 0; y < is->state->h; y++) {
485 if (!(GRID(is->state, x, y) & G_ISLAND))
486 GRID(is->state, x, y) &= ~G_MARK;
490 /* ...and add marks to squares around marked islands. */
491 for (i = 0; i < is->state->n_islands; i++) {
492 is_loop = &is->state->islands[i];
493 if (!(GRID(is_loop->state, is_loop->x, is_loop->y) & G_MARK))
494 continue;
496 for (j = 0; j < is_loop->adj.npoints; j++) {
497 /* if this direction takes us to another island, mark all
498 * squares between the two islands. */
499 if (!is_loop->adj.points[j].off) continue;
500 assert(is_loop->adj.points[j].off > 1);
501 for (o = 1; o < is_loop->adj.points[j].off; o++) {
502 GRID(is_loop->state,
503 is_loop->x + is_loop->adj.points[j].dx*o,
504 is_loop->y + is_loop->adj.points[j].dy*o) |=
505 is_loop->adj.points[j].dy ? G_MARKV : G_MARKH;
511 static int island_impossible(struct island *is, int strict)
513 int curr = island_countbridges(is), nspc = is->count - curr, nsurrspc;
514 int i, poss;
515 grid_type v;
516 struct island *is_orth;
518 if (nspc < 0) {
519 debug(("island at (%d,%d) impossible because full.\n", is->x, is->y));
520 return 1; /* too many bridges */
521 } else if ((curr + island_countspaces(is, 0)) < is->count) {
522 debug(("island at (%d,%d) impossible because not enough spaces.\n", is->x, is->y));
523 return 1; /* impossible to create enough bridges */
524 } else if (strict && curr < is->count) {
525 debug(("island at (%d,%d) impossible because locked.\n", is->x, is->y));
526 return 1; /* not enough bridges and island is locked */
529 /* Count spaces in surrounding islands. */
530 nsurrspc = 0;
531 for (i = 0; i < is->adj.npoints; i++) {
532 int ifree, dx = is->adj.points[i].dx;
534 if (!is->adj.points[i].off) continue;
535 v = GRID(is->state, is->adj.points[i].x, is->adj.points[i].y);
536 poss = POSSIBLES(is->state, dx,
537 is->adj.points[i].x, is->adj.points[i].y);
538 if (poss == 0) continue;
539 is_orth = INDEX(is->state, gridi,
540 ISLAND_ORTHX(is,i), ISLAND_ORTHY(is,i));
541 assert(is_orth);
543 ifree = is_orth->count - island_countbridges(is_orth);
544 if (ifree > 0)
545 nsurrspc += min(ifree, MAXIMUM(is->state, dx,
546 is->adj.points[i].x, is->adj.points[i].y));
548 if (nsurrspc < nspc) {
549 debug(("island at (%d,%d) impossible: surr. islands %d spc, need %d.\n",
550 is->x, is->y, nsurrspc, nspc));
551 return 1; /* not enough spaces around surrounding islands to fill this one. */
554 return 0;
557 /* --- Game parameter functions --- */
559 #define DEFAULT_PRESET 0
561 const struct game_params bridges_presets[] = {
562 { 7, 7, 2, 30, 10, 1, 0 },
563 { 7, 7, 2, 30, 10, 1, 1 },
564 { 7, 7, 2, 30, 10, 1, 2 },
565 { 10, 10, 2, 30, 10, 1, 0 },
566 { 10, 10, 2, 30, 10, 1, 1 },
567 { 10, 10, 2, 30, 10, 1, 2 },
568 { 15, 15, 2, 30, 10, 1, 0 },
569 { 15, 15, 2, 30, 10, 1, 1 },
570 { 15, 15, 2, 30, 10, 1, 2 },
573 static game_params *default_params(void)
575 game_params *ret = snew(game_params);
576 *ret = bridges_presets[DEFAULT_PRESET];
578 return ret;
581 static int game_fetch_preset(int i, char **name, game_params **params)
583 game_params *ret;
584 char buf[80];
586 if (i < 0 || i >= lenof(bridges_presets))
587 return FALSE;
589 ret = default_params();
590 *ret = bridges_presets[i];
591 *params = ret;
593 sprintf(buf, "%dx%d %s", ret->w, ret->h,
594 ret->difficulty == 0 ? "easy" :
595 ret->difficulty == 1 ? "medium" : "hard");
596 *name = dupstr(buf);
598 return TRUE;
601 static void free_params(game_params *params)
603 sfree(params);
606 static game_params *dup_params(game_params *params)
608 game_params *ret = snew(game_params);
609 *ret = *params; /* structure copy */
610 return ret;
613 #define EATNUM(x) do { \
614 (x) = atoi(string); \
615 while (*string && isdigit((unsigned char)*string)) string++; \
616 } while(0)
618 static void decode_params(game_params *params, char const *string)
620 EATNUM(params->w);
621 params->h = params->w;
622 if (*string == 'x') {
623 string++;
624 EATNUM(params->h);
626 if (*string == 'i') {
627 string++;
628 EATNUM(params->islands);
630 if (*string == 'e') {
631 string++;
632 EATNUM(params->expansion);
634 if (*string == 'm') {
635 string++;
636 EATNUM(params->maxb);
638 params->allowloops = 1;
639 if (*string == 'L') {
640 string++;
641 params->allowloops = 0;
643 if (*string == 'd') {
644 string++;
645 EATNUM(params->difficulty);
649 static char *encode_params(game_params *params, int full)
651 char buf[80];
653 if (full) {
654 sprintf(buf, "%dx%di%de%dm%d%sd%d",
655 params->w, params->h, params->islands, params->expansion,
656 params->maxb, params->allowloops ? "" : "L",
657 params->difficulty);
658 } else {
659 sprintf(buf, "%dx%dm%d%s", params->w, params->h,
660 params->maxb, params->allowloops ? "" : "L");
662 return dupstr(buf);
665 static config_item *game_configure(game_params *params)
667 config_item *ret;
668 char buf[80];
670 ret = snewn(8, config_item);
672 ret[0].name = "Width";
673 ret[0].type = C_STRING;
674 sprintf(buf, "%d", params->w);
675 ret[0].sval = dupstr(buf);
676 ret[0].ival = 0;
678 ret[1].name = "Height";
679 ret[1].type = C_STRING;
680 sprintf(buf, "%d", params->h);
681 ret[1].sval = dupstr(buf);
682 ret[1].ival = 0;
684 ret[2].name = "Difficulty";
685 ret[2].type = C_CHOICES;
686 ret[2].sval = ":Easy:Medium:Hard";
687 ret[2].ival = params->difficulty;
689 ret[3].name = "Allow loops";
690 ret[3].type = C_BOOLEAN;
691 ret[3].sval = NULL;
692 ret[3].ival = params->allowloops;
694 ret[4].name = "Max. bridges per direction";
695 ret[4].type = C_CHOICES;
696 ret[4].sval = ":1:2:3:4"; /* keep up-to-date with MAX_BRIDGES */
697 ret[4].ival = params->maxb - 1;
699 ret[5].name = "%age of island squares";
700 ret[5].type = C_CHOICES;
701 ret[5].sval = ":5%:10%:15%:20%:25%:30%";
702 ret[5].ival = (params->islands / 5)-1;
704 ret[6].name = "Expansion factor (%age)";
705 ret[6].type = C_CHOICES;
706 ret[6].sval = ":0%:10%:20%:30%:40%:50%:60%:70%:80%:90%:100%";
707 ret[6].ival = params->expansion / 10;
709 ret[7].name = NULL;
710 ret[7].type = C_END;
711 ret[7].sval = NULL;
712 ret[7].ival = 0;
714 return ret;
717 static game_params *custom_params(config_item *cfg)
719 game_params *ret = snew(game_params);
721 ret->w = atoi(cfg[0].sval);
722 ret->h = atoi(cfg[1].sval);
723 ret->difficulty = cfg[2].ival;
724 ret->allowloops = cfg[3].ival;
725 ret->maxb = cfg[4].ival + 1;
726 ret->islands = (cfg[5].ival + 1) * 5;
727 ret->expansion = cfg[6].ival * 10;
729 return ret;
732 static char *validate_params(game_params *params, int full)
734 if (params->w < 3 || params->h < 3)
735 return "Width and height must be at least 3";
736 if (params->maxb < 1 || params->maxb > MAX_BRIDGES)
737 return "Too many bridges.";
738 if (full) {
739 if (params->islands <= 0 || params->islands > 30)
740 return "%age of island squares must be between 1% and 30%";
741 if (params->expansion < 0 || params->expansion > 100)
742 return "Expansion factor must be between 0 and 100";
744 return NULL;
747 /* --- Game encoding and differences --- */
749 static char *encode_game(game_state *state)
751 char *ret, *p;
752 int wh = state->w*state->h, run, x, y;
753 struct island *is;
755 ret = snewn(wh + 1, char);
756 p = ret;
757 run = 0;
758 for (y = 0; y < state->h; y++) {
759 for (x = 0; x < state->w; x++) {
760 is = INDEX(state, gridi, x, y);
761 if (is) {
762 if (run) {
763 *p++ = ('a'-1) + run;
764 run = 0;
766 if (is->count < 10)
767 *p++ = '0' + is->count;
768 else
769 *p++ = 'A' + (is->count - 10);
770 } else {
771 if (run == 26) {
772 *p++ = ('a'-1) + run;
773 run = 0;
775 run++;
779 if (run) {
780 *p++ = ('a'-1) + run;
781 run = 0;
783 *p = '\0';
784 assert(p - ret <= wh);
786 return ret;
789 static char *game_state_diff(game_state *src, game_state *dest)
791 int movesize = 256, movelen = 0;
792 char *move = snewn(movesize, char), buf[80];
793 int i, d, x, y, len;
794 grid_type gline, nline;
795 struct island *is_s, *is_d, *is_orth;
797 #define APPEND do { \
798 if (movelen + len >= movesize) { \
799 movesize = movelen + len + 256; \
800 move = sresize(move, movesize, char); \
802 strcpy(move + movelen, buf); \
803 movelen += len; \
804 } while(0)
806 move[movelen++] = 'S';
807 move[movelen] = '\0';
809 assert(src->n_islands == dest->n_islands);
811 for (i = 0; i < src->n_islands; i++) {
812 is_s = &src->islands[i];
813 is_d = &dest->islands[i];
814 assert(is_s->x == is_d->x);
815 assert(is_s->y == is_d->y);
816 assert(is_s->adj.npoints == is_d->adj.npoints); /* more paranoia */
818 for (d = 0; d < is_s->adj.npoints; d++) {
819 if (is_s->adj.points[d].dx == -1 ||
820 is_s->adj.points[d].dy == -1) continue;
822 x = is_s->adj.points[d].x;
823 y = is_s->adj.points[d].y;
824 gline = is_s->adj.points[d].dx ? G_LINEH : G_LINEV;
825 nline = is_s->adj.points[d].dx ? G_NOLINEH : G_NOLINEV;
826 is_orth = INDEX(dest, gridi,
827 ISLAND_ORTHX(is_d, d), ISLAND_ORTHY(is_d, d));
829 if (GRIDCOUNT(src, x, y, gline) != GRIDCOUNT(dest, x, y, gline)) {
830 assert(is_orth);
831 len = sprintf(buf, ";L%d,%d,%d,%d,%d",
832 is_s->x, is_s->y, is_orth->x, is_orth->y,
833 GRIDCOUNT(dest, x, y, gline));
834 APPEND;
836 if ((GRID(src,x,y) & nline) != (GRID(dest, x, y) & nline)) {
837 assert(is_orth);
838 len = sprintf(buf, ";N%d,%d,%d,%d",
839 is_s->x, is_s->y, is_orth->x, is_orth->y);
840 APPEND;
843 if ((GRID(src, is_s->x, is_s->y) & G_MARK) !=
844 (GRID(dest, is_d->x, is_d->y) & G_MARK)) {
845 len = sprintf(buf, ";M%d,%d", is_s->x, is_s->y);
846 APPEND;
849 return move;
852 /* --- Game setup and solving utilities --- */
854 /* This function is optimised; a Quantify showed that lots of grid-generation time
855 * (>50%) was spent in here. Hence the IDX() stuff. */
857 static void map_update_possibles(game_state *state)
859 int x, y, s, e, bl, i, np, maxb, w = state->w, idx;
860 struct island *is_s = NULL, *is_f = NULL;
862 /* Run down vertical stripes [un]setting possv... */
863 for (x = 0; x < state->w; x++) {
864 idx = x;
865 s = e = -1;
866 bl = 0;
867 /* Unset possible flags until we find an island. */
868 for (y = 0; y < state->h; y++) {
869 is_s = IDX(state, gridi, idx);
870 if (is_s) break;
872 IDX(state, possv, idx) = 0;
873 idx += w;
875 for (; y < state->h; y++) {
876 is_f = IDX(state, gridi, idx);
877 if (is_f) {
878 assert(is_s);
879 maxb = IDX(state, maxv, idx);
880 np = min(maxb, min(is_s->count, is_f->count));
882 if (s != -1) {
883 for (i = s; i <= e; i++) {
884 INDEX(state, possv, x, i) = bl ? 0 : np;
887 s = y+1;
888 bl = 0;
889 is_s = is_f;
890 } else {
891 e = y;
892 if (IDX(state,grid,idx) & (G_LINEH|G_NOLINEV)) bl = 1;
894 idx += w;
896 if (s != -1) {
897 for (i = s; i <= e; i++)
898 INDEX(state, possv, x, i) = 0;
902 /* ...and now do horizontal stripes [un]setting possh. */
903 /* can we lose this clone'n'hack? */
904 for (y = 0; y < state->h; y++) {
905 idx = y*w;
906 s = e = -1;
907 bl = 0;
908 for (x = 0; x < state->w; x++) {
909 is_s = IDX(state, gridi, idx);
910 if (is_s) break;
912 IDX(state, possh, idx) = 0;
913 idx += 1;
915 for (; x < state->w; x++) {
916 is_f = IDX(state, gridi, idx);
917 if (is_f) {
918 assert(is_s);
919 maxb = IDX(state, maxh, idx);
920 np = min(maxb, min(is_s->count, is_f->count));
922 if (s != -1) {
923 for (i = s; i <= e; i++) {
924 INDEX(state, possh, i, y) = bl ? 0 : np;
927 s = x+1;
928 bl = 0;
929 is_s = is_f;
930 } else {
931 e = x;
932 if (IDX(state,grid,idx) & (G_LINEV|G_NOLINEH)) bl = 1;
934 idx += 1;
936 if (s != -1) {
937 for (i = s; i <= e; i++)
938 INDEX(state, possh, i, y) = 0;
943 static void map_count(game_state *state)
945 int i, n, ax, ay;
946 grid_type flag, grid;
947 struct island *is;
949 for (i = 0; i < state->n_islands; i++) {
950 is = &state->islands[i];
951 is->count = 0;
952 for (n = 0; n < is->adj.npoints; n++) {
953 ax = is->adj.points[n].x;
954 ay = is->adj.points[n].y;
955 flag = (ax == is->x) ? G_LINEV : G_LINEH;
956 grid = GRID(state,ax,ay);
957 if (grid & flag) {
958 is->count += INDEX(state,lines,ax,ay);
964 static void map_find_orthogonal(game_state *state)
966 int i;
968 for (i = 0; i < state->n_islands; i++) {
969 island_find_orthogonal(&state->islands[i]);
973 static int grid_degree(game_state *state, int x, int y, int *nx_r, int *ny_r)
975 grid_type grid = SCRATCH(state, x, y), gline = grid & G_LINE;
976 struct island *is;
977 int x1, y1, x2, y2, c = 0, i, nx, ny;
979 nx = ny = -1; /* placate optimiser */
980 is = INDEX(state, gridi, x, y);
981 if (is) {
982 for (i = 0; i < is->adj.npoints; i++) {
983 gline = is->adj.points[i].dx ? G_LINEH : G_LINEV;
984 if (SCRATCH(state,
985 is->adj.points[i].x,
986 is->adj.points[i].y) & gline) {
987 nx = is->adj.points[i].x;
988 ny = is->adj.points[i].y;
989 c++;
992 } else if (gline) {
993 if (gline & G_LINEV) {
994 x1 = x2 = x;
995 y1 = y-1; y2 = y+1;
996 } else {
997 x1 = x-1; x2 = x+1;
998 y1 = y2 = y;
1000 /* Non-island squares with edges in should never be pointing off the
1001 * edge of the grid. */
1002 assert(INGRID(state, x1, y1));
1003 assert(INGRID(state, x2, y2));
1004 if (SCRATCH(state, x1, y1) & (gline | G_ISLAND)) {
1005 nx = x1; ny = y1; c++;
1007 if (SCRATCH(state, x2, y2) & (gline | G_ISLAND)) {
1008 nx = x2; ny = y2; c++;
1011 if (c == 1) {
1012 assert(nx != -1 && ny != -1); /* paranoia */
1013 *nx_r = nx; *ny_r = ny;
1015 return c;
1018 static int map_hasloops(game_state *state, int mark)
1020 int x, y, ox, oy, nx = 0, ny = 0, loop = 0;
1022 memcpy(state->scratch, state->grid, GRIDSZ(state));
1024 /* This algorithm is actually broken; if there are two loops connected
1025 * by bridges this will also highlight bridges. The correct algorithm
1026 * uses a dsf and a two-pass edge-detection algorithm (see check_correct
1027 * in slant.c); this is BALGE for now, especially since disallow-loops
1028 * is not the default for this puzzle. If we want to fix this later then
1029 * copy the alg in slant.c to the empty statement in map_group. */
1031 /* Remove all 1-degree edges. */
1032 for (y = 0; y < state->h; y++) {
1033 for (x = 0; x < state->w; x++) {
1034 ox = x; oy = y;
1035 while (grid_degree(state, ox, oy, &nx, &ny) == 1) {
1036 /*debug(("hasloops: removing 1-degree at (%d,%d).\n", ox, oy));*/
1037 SCRATCH(state, ox, oy) &= ~(G_LINE|G_ISLAND);
1038 ox = nx; oy = ny;
1042 /* Mark any remaining edges as G_WARN, if required. */
1043 for (x = 0; x < state->w; x++) {
1044 for (y = 0; y < state->h; y++) {
1045 if (GRID(state,x,y) & G_ISLAND) continue;
1047 if (SCRATCH(state, x, y) & G_LINE) {
1048 if (mark) {
1049 /*debug(("hasloops: marking loop square at (%d,%d).\n",
1050 x, y));*/
1051 GRID(state,x,y) |= G_WARN;
1052 loop = 1;
1053 } else
1054 return 1; /* short-cut as soon as we find one */
1055 } else {
1056 if (mark)
1057 GRID(state,x,y) &= ~G_WARN;
1061 return loop;
1064 static void map_group(game_state *state)
1066 int i, wh = state->w*state->h, d1, d2;
1067 int x, y, x2, y2;
1068 int *dsf = state->solver->dsf;
1069 struct island *is, *is_join;
1071 /* Initialise dsf. */
1072 dsf_init(dsf, wh);
1074 /* For each island, find connected islands right or down
1075 * and merge the dsf for the island squares as well as the
1076 * bridge squares. */
1077 for (x = 0; x < state->w; x++) {
1078 for (y = 0; y < state->h; y++) {
1079 GRID(state,x,y) &= ~(G_SWEEP|G_WARN); /* for group_full. */
1081 is = INDEX(state, gridi, x, y);
1082 if (!is) continue;
1083 d1 = DINDEX(x,y);
1084 for (i = 0; i < is->adj.npoints; i++) {
1085 /* only want right/down */
1086 if (is->adj.points[i].dx == -1 ||
1087 is->adj.points[i].dy == -1) continue;
1089 is_join = island_find_connection(is, i);
1090 if (!is_join) continue;
1092 d2 = DINDEX(is_join->x, is_join->y);
1093 if (dsf_canonify(dsf,d1) == dsf_canonify(dsf,d2)) {
1094 ; /* we have a loop. See comment in map_hasloops. */
1095 /* However, we still want to merge all squares joining
1096 * this side-that-makes-a-loop. */
1098 /* merge all squares between island 1 and island 2. */
1099 for (x2 = x; x2 <= is_join->x; x2++) {
1100 for (y2 = y; y2 <= is_join->y; y2++) {
1101 d2 = DINDEX(x2,y2);
1102 if (d1 != d2) dsf_merge(dsf,d1,d2);
1110 static int map_group_check(game_state *state, int canon, int warn,
1111 int *nislands_r)
1113 int *dsf = state->solver->dsf, nislands = 0;
1114 int x, y, i, allfull = 1;
1115 struct island *is;
1117 for (i = 0; i < state->n_islands; i++) {
1118 is = &state->islands[i];
1119 if (dsf_canonify(dsf, DINDEX(is->x,is->y)) != canon) continue;
1121 GRID(state, is->x, is->y) |= G_SWEEP;
1122 nislands++;
1123 if (island_countbridges(is) != is->count)
1124 allfull = 0;
1126 if (warn && allfull && nislands != state->n_islands) {
1127 /* we're full and this island group isn't the whole set.
1128 * Mark all squares with this dsf canon as ERR. */
1129 for (x = 0; x < state->w; x++) {
1130 for (y = 0; y < state->h; y++) {
1131 if (dsf_canonify(dsf, DINDEX(x,y)) == canon) {
1132 GRID(state,x,y) |= G_WARN;
1138 if (nislands_r) *nislands_r = nislands;
1139 return allfull;
1142 static int map_group_full(game_state *state, int *ngroups_r)
1144 int *dsf = state->solver->dsf, ngroups = 0;
1145 int i, anyfull = 0;
1146 struct island *is;
1148 /* NB this assumes map_group (or sth else) has cleared G_SWEEP. */
1150 for (i = 0; i < state->n_islands; i++) {
1151 is = &state->islands[i];
1152 if (GRID(state,is->x,is->y) & G_SWEEP) continue;
1154 ngroups++;
1155 if (map_group_check(state, dsf_canonify(dsf, DINDEX(is->x,is->y)),
1156 1, NULL))
1157 anyfull = 1;
1160 *ngroups_r = ngroups;
1161 return anyfull;
1164 static int map_check(game_state *state)
1166 int ngroups;
1168 /* Check for loops, if necessary. */
1169 if (!state->allowloops) {
1170 if (map_hasloops(state, 1))
1171 return 0;
1174 /* Place islands into island groups and check for early
1175 * satisfied-groups. */
1176 map_group(state); /* clears WARN and SWEEP */
1177 if (map_group_full(state, &ngroups)) {
1178 if (ngroups == 1) return 1;
1180 return 0;
1183 static void map_clear(game_state *state)
1185 int x, y;
1187 for (x = 0; x < state->w; x++) {
1188 for (y = 0; y < state->h; y++) {
1189 /* clear most flags; might want to be slightly more careful here. */
1190 GRID(state,x,y) &= G_ISLAND;
1195 static void solve_join(struct island *is, int direction, int n, int is_max)
1197 struct island *is_orth;
1198 int d1, d2, *dsf = is->state->solver->dsf;
1199 game_state *state = is->state; /* for DINDEX */
1201 is_orth = INDEX(is->state, gridi,
1202 ISLAND_ORTHX(is, direction),
1203 ISLAND_ORTHY(is, direction));
1204 assert(is_orth);
1205 /*debug(("...joining (%d,%d) to (%d,%d) with %d bridge(s).\n",
1206 is->x, is->y, is_orth->x, is_orth->y, n));*/
1207 island_join(is, is_orth, n, is_max);
1209 if (n > 0 && !is_max) {
1210 d1 = DINDEX(is->x, is->y);
1211 d2 = DINDEX(is_orth->x, is_orth->y);
1212 if (dsf_canonify(dsf, d1) != dsf_canonify(dsf, d2))
1213 dsf_merge(dsf, d1, d2);
1217 static int solve_fillone(struct island *is)
1219 int i, nadded = 0;
1221 debug(("solve_fillone for island (%d,%d).\n", is->x, is->y));
1223 for (i = 0; i < is->adj.npoints; i++) {
1224 if (island_isadj(is, i)) {
1225 if (island_hasbridge(is, i)) {
1226 /* already attached; do nothing. */;
1227 } else {
1228 solve_join(is, i, 1, 0);
1229 nadded++;
1233 return nadded;
1236 static int solve_fill(struct island *is)
1238 /* for each unmarked adjacent, make sure we convert every possible bridge
1239 * to a real one, and then work out the possibles afresh. */
1240 int i, nnew, ncurr, nadded = 0, missing;
1242 debug(("solve_fill for island (%d,%d).\n", is->x, is->y));
1244 missing = is->count - island_countbridges(is);
1245 if (missing < 0) return 0;
1247 /* very like island_countspaces. */
1248 for (i = 0; i < is->adj.npoints; i++) {
1249 nnew = island_adjspace(is, 1, missing, i);
1250 if (nnew) {
1251 ncurr = GRIDCOUNT(is->state,
1252 is->adj.points[i].x, is->adj.points[i].y,
1253 is->adj.points[i].dx ? G_LINEH : G_LINEV);
1255 solve_join(is, i, nnew + ncurr, 0);
1256 nadded += nnew;
1259 return nadded;
1262 static int solve_island_stage1(struct island *is, int *didsth_r)
1264 int bridges = island_countbridges(is);
1265 int nspaces = island_countspaces(is, 1);
1266 int nadj = island_countadj(is);
1267 int didsth = 0;
1269 assert(didsth_r);
1271 /*debug(("island at (%d,%d) filled %d/%d (%d spc) nadj %d\n",
1272 is->x, is->y, bridges, is->count, nspaces, nadj));*/
1273 if (bridges > is->count) {
1274 /* We only ever add bridges when we're sure they fit, or that's
1275 * the only place they can go. If we've added bridges such that
1276 * another island has become wrong, the puzzle must not have had
1277 * a solution. */
1278 debug(("...island at (%d,%d) is overpopulated!\n", is->x, is->y));
1279 return 0;
1280 } else if (bridges == is->count) {
1281 /* This island is full. Make sure it's marked (and update
1282 * possibles if we did). */
1283 if (!(GRID(is->state, is->x, is->y) & G_MARK)) {
1284 debug(("...marking island (%d,%d) as full.\n", is->x, is->y));
1285 island_togglemark(is);
1286 didsth = 1;
1288 } else if (GRID(is->state, is->x, is->y) & G_MARK) {
1289 debug(("...island (%d,%d) is marked but unfinished!\n",
1290 is->x, is->y));
1291 return 0; /* island has been marked unfinished; no solution from here. */
1292 } else {
1293 /* This is the interesting bit; we try and fill in more information
1294 * about this island. */
1295 if (is->count == bridges + nspaces) {
1296 if (solve_fill(is) > 0) didsth = 1;
1297 } else if (is->count > ((nadj-1) * is->state->maxb)) {
1298 /* must have at least one bridge in each possible direction. */
1299 if (solve_fillone(is) > 0) didsth = 1;
1302 if (didsth) {
1303 map_update_possibles(is->state);
1304 *didsth_r = 1;
1306 return 1;
1309 /* returns non-zero if a new line here would cause a loop. */
1310 static int solve_island_checkloop(struct island *is, int direction)
1312 struct island *is_orth;
1313 int *dsf = is->state->solver->dsf, d1, d2;
1314 game_state *state = is->state;
1316 if (is->state->allowloops) return 0; /* don't care anyway */
1317 if (island_hasbridge(is, direction)) return 0; /* already has a bridge */
1318 if (island_isadj(is, direction) == 0) return 0; /* no adj island */
1320 is_orth = INDEX(is->state, gridi,
1321 ISLAND_ORTHX(is,direction),
1322 ISLAND_ORTHY(is,direction));
1323 if (!is_orth) return 0;
1325 d1 = DINDEX(is->x, is->y);
1326 d2 = DINDEX(is_orth->x, is_orth->y);
1327 if (dsf_canonify(dsf, d1) == dsf_canonify(dsf, d2)) {
1328 /* two islands are connected already; don't join them. */
1329 return 1;
1331 return 0;
1334 static int solve_island_stage2(struct island *is, int *didsth_r)
1336 int added = 0, removed = 0, navail = 0, nadj, i;
1338 assert(didsth_r);
1340 for (i = 0; i < is->adj.npoints; i++) {
1341 if (solve_island_checkloop(is, i)) {
1342 debug(("removing possible loop at (%d,%d) direction %d.\n",
1343 is->x, is->y, i));
1344 solve_join(is, i, -1, 0);
1345 map_update_possibles(is->state);
1346 removed = 1;
1347 } else {
1348 navail += island_isadj(is, i);
1349 /*debug(("stage2: navail for (%d,%d) direction (%d,%d) is %d.\n",
1350 is->x, is->y,
1351 is->adj.points[i].dx, is->adj.points[i].dy,
1352 island_isadj(is, i)));*/
1356 /*debug(("island at (%d,%d) navail %d: checking...\n", is->x, is->y, navail));*/
1358 for (i = 0; i < is->adj.npoints; i++) {
1359 if (!island_hasbridge(is, i)) {
1360 nadj = island_isadj(is, i);
1361 if (nadj > 0 && (navail - nadj) < is->count) {
1362 /* we couldn't now complete the island without at
1363 * least one bridge here; put it in. */
1364 /*debug(("nadj %d, navail %d, is->count %d.\n",
1365 nadj, navail, is->count));*/
1366 debug(("island at (%d,%d) direction (%d,%d) must have 1 bridge\n",
1367 is->x, is->y,
1368 is->adj.points[i].dx, is->adj.points[i].dy));
1369 solve_join(is, i, 1, 0);
1370 added = 1;
1371 /*debug_state(is->state);
1372 debug_possibles(is->state);*/
1376 if (added) map_update_possibles(is->state);
1377 if (added || removed) *didsth_r = 1;
1378 return 1;
1381 static int solve_island_subgroup(struct island *is, int direction, int n)
1383 struct island *is_join;
1384 int nislands, *dsf = is->state->solver->dsf;
1385 game_state *state = is->state;
1387 debug(("..checking subgroups.\n"));
1389 /* if is isn't full, return 0. */
1390 if (n < is->count) {
1391 debug(("...orig island (%d,%d) not full.\n", is->x, is->y));
1392 return 0;
1395 is_join = INDEX(state, gridi,
1396 ISLAND_ORTHX(is, direction),
1397 ISLAND_ORTHY(is, direction));
1398 assert(is_join);
1400 /* if is_join isn't full, return 0. */
1401 if (island_countbridges(is_join) < is_join->count) {
1402 debug(("...dest island (%d,%d) not full.\n", is_join->x, is_join->y));
1403 return 0;
1406 /* Check group membership for is->dsf; if it's full return 1. */
1407 if (map_group_check(state, dsf_canonify(dsf, DINDEX(is->x,is->y)),
1408 0, &nislands)) {
1409 if (nislands < state->n_islands) {
1410 /* we have a full subgroup that isn't the whole set.
1411 * This isn't allowed. */
1412 debug(("island at (%d,%d) makes full subgroup, disallowing.\n",
1413 is->x, is->y, n));
1414 return 1;
1415 } else {
1416 debug(("...has finished puzzle.\n"));
1419 return 0;
1422 static int solve_island_impossible(game_state *state)
1424 struct island *is;
1425 int i;
1427 /* If any islands are impossible, return 1. */
1428 for (i = 0; i < state->n_islands; i++) {
1429 is = &state->islands[i];
1430 if (island_impossible(is, 0)) {
1431 debug(("island at (%d,%d) has become impossible, disallowing.\n",
1432 is->x, is->y));
1433 return 1;
1436 return 0;
1439 /* Bear in mind that this function is really rather inefficient. */
1440 static int solve_island_stage3(struct island *is, int *didsth_r)
1442 int i, n, x, y, missing, spc, curr, maxb, didsth = 0;
1443 int wh = is->state->w * is->state->h;
1444 struct solver_state *ss = is->state->solver;
1446 assert(didsth_r);
1448 missing = is->count - island_countbridges(is);
1449 if (missing <= 0) return 1;
1451 for (i = 0; i < is->adj.npoints; i++) {
1452 /* We only do right- or down-pointing bridges. */
1453 if (is->adj.points[i].dx == -1 ||
1454 is->adj.points[i].dy == -1) continue;
1456 x = is->adj.points[i].x;
1457 y = is->adj.points[i].y;
1458 spc = island_adjspace(is, 1, missing, i);
1459 if (spc == 0) continue;
1461 curr = GRIDCOUNT(is->state, x, y,
1462 is->adj.points[i].dx ? G_LINEH : G_LINEV);
1463 debug(("island at (%d,%d) s3, trying %d - %d bridges.\n",
1464 is->x, is->y, curr+1, curr+spc));
1466 /* Now we know that this island could have more bridges,
1467 * to bring the total from curr+1 to curr+spc. */
1468 maxb = -1;
1469 /* We have to squirrel the dsf away and restore it afterwards;
1470 * it is additive only, and can't be removed from. */
1471 memcpy(ss->tmpdsf, ss->dsf, wh*sizeof(int));
1472 for (n = curr+1; n <= curr+spc; n++) {
1473 solve_join(is, i, n, 0);
1474 map_update_possibles(is->state);
1476 if (solve_island_subgroup(is, i, n) ||
1477 solve_island_impossible(is->state)) {
1478 maxb = n-1;
1479 debug(("island at (%d,%d) d(%d,%d) new max of %d bridges:\n",
1480 is->x, is->y,
1481 is->adj.points[i].dx, is->adj.points[i].dy,
1482 maxb));
1483 break;
1486 solve_join(is, i, curr, 0); /* put back to before. */
1487 memcpy(ss->dsf, ss->tmpdsf, wh*sizeof(int));
1489 if (maxb != -1) {
1490 /*debug_state(is->state);*/
1491 if (maxb == 0) {
1492 debug(("...adding NOLINE.\n"));
1493 solve_join(is, i, -1, 0); /* we can't have any bridges here. */
1494 didsth = 1;
1495 } else {
1496 debug(("...setting maximum\n"));
1497 solve_join(is, i, maxb, 1);
1500 map_update_possibles(is->state);
1502 if (didsth) *didsth_r = didsth;
1503 return 1;
1506 #define CONTINUE_IF_FULL do { \
1507 if (GRID(state, is->x, is->y) & G_MARK) { \
1508 /* island full, don't try fixing it */ \
1509 continue; \
1510 } } while(0)
1512 static int solve_sub(game_state *state, int difficulty, int depth)
1514 struct island *is;
1515 int i, didsth;
1517 while (1) {
1518 didsth = 0;
1520 /* First island iteration: things we can work out by looking at
1521 * properties of the island as a whole. */
1522 for (i = 0; i < state->n_islands; i++) {
1523 is = &state->islands[i];
1524 if (!solve_island_stage1(is, &didsth)) return 0;
1526 if (didsth) continue;
1527 else if (difficulty < 1) break;
1529 /* Second island iteration: thing we can work out by looking at
1530 * properties of individual island connections. */
1531 for (i = 0; i < state->n_islands; i++) {
1532 is = &state->islands[i];
1533 CONTINUE_IF_FULL;
1534 if (!solve_island_stage2(is, &didsth)) return 0;
1536 if (didsth) continue;
1537 else if (difficulty < 2) break;
1539 /* Third island iteration: things we can only work out by looking
1540 * at groups of islands. */
1541 for (i = 0; i < state->n_islands; i++) {
1542 is = &state->islands[i];
1543 if (!solve_island_stage3(is, &didsth)) return 0;
1545 if (didsth) continue;
1546 else if (difficulty < 3) break;
1548 /* If we can be bothered, write a recursive solver to finish here. */
1549 break;
1551 if (map_check(state)) return 1; /* solved it */
1552 return 0;
1555 static void solve_for_hint(game_state *state)
1557 map_group(state);
1558 solve_sub(state, 10, 0);
1561 static int solve_from_scratch(game_state *state, int difficulty)
1563 map_clear(state);
1564 map_group(state);
1565 map_update_possibles(state);
1566 return solve_sub(state, difficulty, 0);
1569 /* --- New game functions --- */
1571 static game_state *new_state(game_params *params)
1573 game_state *ret = snew(game_state);
1574 int wh = params->w * params->h, i;
1576 ret->w = params->w;
1577 ret->h = params->h;
1578 ret->allowloops = params->allowloops;
1579 ret->maxb = params->maxb;
1580 ret->params = *params;
1582 ret->grid = snewn(wh, grid_type);
1583 memset(ret->grid, 0, GRIDSZ(ret));
1584 ret->scratch = snewn(wh, grid_type);
1585 memset(ret->scratch, 0, GRIDSZ(ret));
1587 ret->wha = snewn(wh*N_WH_ARRAYS, char);
1588 memset(ret->wha, 0, wh*N_WH_ARRAYS*sizeof(char));
1590 ret->possv = ret->wha;
1591 ret->possh = ret->wha + wh;
1592 ret->lines = ret->wha + wh*2;
1593 ret->maxv = ret->wha + wh*3;
1594 ret->maxh = ret->wha + wh*4;
1596 memset(ret->maxv, ret->maxb, wh*sizeof(char));
1597 memset(ret->maxh, ret->maxb, wh*sizeof(char));
1599 ret->islands = NULL;
1600 ret->n_islands = 0;
1601 ret->n_islands_alloc = 0;
1603 ret->gridi = snewn(wh, struct island *);
1604 for (i = 0; i < wh; i++) ret->gridi[i] = NULL;
1606 ret->solved = ret->completed = 0;
1608 ret->solver = snew(struct solver_state);
1609 ret->solver->dsf = snew_dsf(wh);
1610 ret->solver->tmpdsf = snewn(wh, int);
1612 ret->solver->refcount = 1;
1614 return ret;
1617 static game_state *dup_game(game_state *state)
1619 game_state *ret = snew(game_state);
1620 int wh = state->w*state->h;
1622 ret->w = state->w;
1623 ret->h = state->h;
1624 ret->allowloops = state->allowloops;
1625 ret->maxb = state->maxb;
1626 ret->params = state->params;
1628 ret->grid = snewn(wh, grid_type);
1629 memcpy(ret->grid, state->grid, GRIDSZ(ret));
1630 ret->scratch = snewn(wh, grid_type);
1631 memcpy(ret->scratch, state->scratch, GRIDSZ(ret));
1633 ret->wha = snewn(wh*N_WH_ARRAYS, char);
1634 memcpy(ret->wha, state->wha, wh*N_WH_ARRAYS*sizeof(char));
1636 ret->possv = ret->wha;
1637 ret->possh = ret->wha + wh;
1638 ret->lines = ret->wha + wh*2;
1639 ret->maxv = ret->wha + wh*3;
1640 ret->maxh = ret->wha + wh*4;
1642 ret->islands = snewn(state->n_islands, struct island);
1643 memcpy(ret->islands, state->islands, state->n_islands * sizeof(struct island));
1644 ret->n_islands = ret->n_islands_alloc = state->n_islands;
1646 ret->gridi = snewn(wh, struct island *);
1647 fixup_islands_for_realloc(ret);
1649 ret->solved = state->solved;
1650 ret->completed = state->completed;
1652 ret->solver = state->solver;
1653 ret->solver->refcount++;
1655 return ret;
1658 static void free_game(game_state *state)
1660 if (--state->solver->refcount <= 0) {
1661 sfree(state->solver->dsf);
1662 sfree(state->solver->tmpdsf);
1663 sfree(state->solver);
1666 sfree(state->islands);
1667 sfree(state->gridi);
1669 sfree(state->wha);
1671 sfree(state->scratch);
1672 sfree(state->grid);
1673 sfree(state);
1676 #define MAX_NEWISLAND_TRIES 50
1678 #define ORDER(a,b) do { if (a < b) { int tmp=a; int a=b; int b=tmp; } } while(0)
1680 static char *new_game_desc(game_params *params, random_state *rs,
1681 char **aux, int interactive)
1683 game_state *tobuild = NULL;
1684 int i, j, wh = params->w * params->h, x, y, dx, dy;
1685 int minx, miny, maxx, maxy, joinx, joiny, newx, newy, diffx, diffy;
1686 int ni_req = max((params->islands * wh) / 100, 2), ni_curr, ni_bad;
1687 struct island *is, *is2;
1688 char *ret;
1689 unsigned int echeck;
1691 /* pick a first island position randomly. */
1692 generate:
1693 if (tobuild) free_game(tobuild);
1694 tobuild = new_state(params);
1696 x = random_upto(rs, params->w);
1697 y = random_upto(rs, params->h);
1698 island_add(tobuild, x, y, 0);
1699 ni_curr = 1;
1700 ni_bad = 0;
1701 debug(("Created initial island at (%d,%d).\n", x, y));
1703 while (ni_curr < ni_req) {
1704 /* Pick a random island to try and extend from. */
1705 i = random_upto(rs, tobuild->n_islands);
1706 is = &tobuild->islands[i];
1708 /* Pick a random direction to extend in. */
1709 j = random_upto(rs, is->adj.npoints);
1710 dx = is->adj.points[j].x - is->x;
1711 dy = is->adj.points[j].y - is->y;
1713 /* Find out limits of where we could put a new island. */
1714 joinx = joiny = -1;
1715 minx = is->x + 2*dx; miny = is->y + 2*dy; /* closest is 2 units away. */
1716 x = is->x+dx; y = is->y+dy;
1717 if (GRID(tobuild,x,y) & (G_LINEV|G_LINEH)) {
1718 /* already a line next to the island, continue. */
1719 goto bad;
1721 while (1) {
1722 if (x < 0 || x >= params->w || y < 0 || y >= params->h) {
1723 /* got past the edge; put a possible at the island
1724 * and exit. */
1725 maxx = x-dx; maxy = y-dy;
1726 goto foundmax;
1728 if (GRID(tobuild,x,y) & G_ISLAND) {
1729 /* could join up to an existing island... */
1730 joinx = x; joiny = y;
1731 /* ... or make a new one 2 spaces away. */
1732 maxx = x - 2*dx; maxy = y - 2*dy;
1733 goto foundmax;
1734 } else if (GRID(tobuild,x,y) & (G_LINEV|G_LINEH)) {
1735 /* could make a new one 1 space away from the line. */
1736 maxx = x - dx; maxy = y - dy;
1737 goto foundmax;
1739 x += dx; y += dy;
1742 foundmax:
1743 debug(("Island at (%d,%d) with d(%d,%d) has new positions "
1744 "(%d,%d) -> (%d,%d), join (%d,%d).\n",
1745 is->x, is->y, dx, dy, minx, miny, maxx, maxy, joinx, joiny));
1746 /* Now we know where we could either put a new island
1747 * (between min and max), or (if loops are allowed) could join on
1748 * to an existing island (at join). */
1749 if (params->allowloops && joinx != -1 && joiny != -1) {
1750 if (random_upto(rs, 100) < (unsigned long)params->expansion) {
1751 is2 = INDEX(tobuild, gridi, joinx, joiny);
1752 debug(("Joining island at (%d,%d) to (%d,%d).\n",
1753 is->x, is->y, is2->x, is2->y));
1754 goto join;
1757 diffx = (maxx - minx) * dx;
1758 diffy = (maxy - miny) * dy;
1759 if (diffx < 0 || diffy < 0) goto bad;
1760 if (random_upto(rs,100) < (unsigned long)params->expansion) {
1761 newx = maxx; newy = maxy;
1762 debug(("Creating new island at (%d,%d) (expanded).\n", newx, newy));
1763 } else {
1764 newx = minx + random_upto(rs,diffx+1)*dx;
1765 newy = miny + random_upto(rs,diffy+1)*dy;
1766 debug(("Creating new island at (%d,%d).\n", newx, newy));
1768 /* check we're not next to island in the other orthogonal direction. */
1769 if ((INGRID(tobuild,newx+dy,newy+dx) && (GRID(tobuild,newx+dy,newy+dx) & G_ISLAND)) ||
1770 (INGRID(tobuild,newx-dy,newy-dx) && (GRID(tobuild,newx-dy,newy-dx) & G_ISLAND))) {
1771 debug(("New location is adjacent to island, skipping.\n"));
1772 goto bad;
1774 is2 = island_add(tobuild, newx, newy, 0);
1775 /* Must get is again at this point; the array might have
1776 * been realloced by island_add... */
1777 is = &tobuild->islands[i]; /* ...but order will not change. */
1779 ni_curr++; ni_bad = 0;
1780 join:
1781 island_join(is, is2, random_upto(rs, tobuild->maxb)+1, 0);
1782 debug_state(tobuild);
1783 continue;
1785 bad:
1786 ni_bad++;
1787 if (ni_bad > MAX_NEWISLAND_TRIES) {
1788 debug(("Unable to create any new islands after %d tries; "
1789 "created %d [%d%%] (instead of %d [%d%%] requested).\n",
1790 MAX_NEWISLAND_TRIES,
1791 ni_curr, ni_curr * 100 / wh,
1792 ni_req, ni_req * 100 / wh));
1793 goto generated;
1797 generated:
1798 if (ni_curr == 1) {
1799 debug(("Only generated one island (!), retrying.\n"));
1800 goto generate;
1802 /* Check we have at least one island on each extremity of the grid. */
1803 echeck = 0;
1804 for (x = 0; x < params->w; x++) {
1805 if (INDEX(tobuild, gridi, x, 0)) echeck |= 1;
1806 if (INDEX(tobuild, gridi, x, params->h-1)) echeck |= 2;
1808 for (y = 0; y < params->h; y++) {
1809 if (INDEX(tobuild, gridi, 0, y)) echeck |= 4;
1810 if (INDEX(tobuild, gridi, params->w-1, y)) echeck |= 8;
1812 if (echeck != 15) {
1813 debug(("Generated grid doesn't fill to sides, retrying.\n"));
1814 goto generate;
1817 map_count(tobuild);
1818 map_find_orthogonal(tobuild);
1820 if (params->difficulty > 0) {
1821 if (solve_from_scratch(tobuild, params->difficulty-1) > 0) {
1822 debug(("Grid is solvable at difficulty %d (too easy); retrying.\n",
1823 params->difficulty-1));
1824 goto generate;
1828 if (solve_from_scratch(tobuild, params->difficulty) == 0) {
1829 debug(("Grid not solvable at difficulty %d, (too hard); retrying.\n",
1830 params->difficulty));
1831 goto generate;
1834 /* ... tobuild is now solved. We rely on this making the diff for aux. */
1835 debug_state(tobuild);
1836 ret = encode_game(tobuild);
1838 game_state *clean = dup_game(tobuild);
1839 map_clear(clean);
1840 map_update_possibles(clean);
1841 *aux = game_state_diff(clean, tobuild);
1842 free_game(clean);
1844 free_game(tobuild);
1846 return ret;
1849 static char *validate_desc(game_params *params, char *desc)
1851 int i, wh = params->w * params->h;
1853 for (i = 0; i < wh; i++) {
1854 if (*desc >= '1' && *desc <= '9')
1855 /* OK */;
1856 else if (*desc >= 'a' && *desc <= 'z')
1857 i += *desc - 'a'; /* plus the i++ */
1858 else if (*desc >= 'A' && *desc <= 'G')
1859 /* OK */;
1860 else if (*desc == 'V' || *desc == 'W' ||
1861 *desc == 'X' || *desc == 'Y' ||
1862 *desc == 'H' || *desc == 'I' ||
1863 *desc == 'J' || *desc == 'K')
1864 /* OK */;
1865 else if (!*desc)
1866 return "Game description shorter than expected";
1867 else
1868 return "Game description containers unexpected character";
1869 desc++;
1871 if (*desc || i > wh)
1872 return "Game description longer than expected";
1874 return NULL;
1877 static game_state *new_game_sub(game_params *params, char *desc)
1879 game_state *state = new_state(params);
1880 int x, y, run = 0;
1882 debug(("new_game[_sub]: desc = '%s'.\n", desc));
1884 for (y = 0; y < params->h; y++) {
1885 for (x = 0; x < params->w; x++) {
1886 char c = '\0';
1888 if (run == 0) {
1889 c = *desc++;
1890 assert(c != 'S');
1891 if (c >= 'a' && c <= 'z')
1892 run = c - 'a' + 1;
1895 if (run > 0) {
1896 c = 'S';
1897 run--;
1900 switch (c) {
1901 case '1': case '2': case '3': case '4':
1902 case '5': case '6': case '7': case '8': case '9':
1903 island_add(state, x, y, (c - '0'));
1904 break;
1906 case 'A': case 'B': case 'C': case 'D':
1907 case 'E': case 'F': case 'G':
1908 island_add(state, x, y, (c - 'A') + 10);
1909 break;
1911 case 'S':
1912 /* empty square */
1913 break;
1915 default:
1916 assert(!"Malformed desc.");
1917 break;
1921 if (*desc) assert(!"Over-long desc.");
1923 map_find_orthogonal(state);
1924 map_update_possibles(state);
1926 return state;
1929 static game_state *new_game(midend *me, game_params *params, char *desc)
1931 return new_game_sub(params, desc);
1934 struct game_ui {
1935 int dragx_src, dragy_src; /* source; -1 means no drag */
1936 int dragx_dst, dragy_dst; /* src's closest orth island. */
1937 grid_type todraw;
1938 int dragging, drag_is_noline, nlines;
1941 static char *ui_cancel_drag(game_ui *ui)
1943 ui->dragx_src = ui->dragy_src = -1;
1944 ui->dragx_dst = ui->dragy_dst = -1;
1945 ui->dragging = 0;
1946 return "";
1949 static game_ui *new_ui(game_state *state)
1951 game_ui *ui = snew(game_ui);
1952 ui_cancel_drag(ui);
1953 return ui;
1956 static void free_ui(game_ui *ui)
1958 sfree(ui);
1961 static char *encode_ui(game_ui *ui)
1963 return NULL;
1966 static void decode_ui(game_ui *ui, char *encoding)
1970 static void game_changed_state(game_ui *ui, game_state *oldstate,
1971 game_state *newstate)
1975 struct game_drawstate {
1976 int tilesize;
1977 int w, h;
1978 grid_type *grid;
1979 int *lv, *lh;
1980 int started, dragging;
1983 static char *update_drag_dst(game_state *state, game_ui *ui, game_drawstate *ds,
1984 int nx, int ny)
1986 int ox, oy, dx, dy, i, currl, maxb;
1987 struct island *is;
1988 grid_type gtype, ntype, mtype, curr;
1990 if (ui->dragx_src == -1 || ui->dragy_src == -1) return NULL;
1992 ui->dragx_dst = -1;
1993 ui->dragy_dst = -1;
1995 /* work out which of the four directions we're closest to... */
1996 ox = COORD(ui->dragx_src) + TILE_SIZE/2;
1997 oy = COORD(ui->dragy_src) + TILE_SIZE/2;
1999 if (abs(nx-ox) < abs(ny-oy)) {
2000 dx = 0;
2001 dy = (ny-oy) < 0 ? -1 : 1;
2002 gtype = G_LINEV; ntype = G_NOLINEV; mtype = G_MARKV;
2003 maxb = INDEX(state, maxv, ui->dragx_src+dx, ui->dragy_src+dy);
2004 } else {
2005 dy = 0;
2006 dx = (nx-ox) < 0 ? -1 : 1;
2007 gtype = G_LINEH; ntype = G_NOLINEH; mtype = G_MARKH;
2008 maxb = INDEX(state, maxh, ui->dragx_src+dx, ui->dragy_src+dy);
2010 if (ui->drag_is_noline) {
2011 ui->todraw = ntype;
2012 } else {
2013 curr = GRID(state, ui->dragx_src+dx, ui->dragy_src+dy);
2014 currl = INDEX(state, lines, ui->dragx_src+dx, ui->dragy_src+dy);
2016 if (curr & gtype) {
2017 if (currl == maxb) {
2018 ui->todraw = 0;
2019 ui->nlines = 0;
2020 } else {
2021 ui->todraw = gtype;
2022 ui->nlines = currl + 1;
2024 } else {
2025 ui->todraw = gtype;
2026 ui->nlines = 1;
2030 /* ... and see if there's an island off in that direction. */
2031 is = INDEX(state, gridi, ui->dragx_src, ui->dragy_src);
2032 for (i = 0; i < is->adj.npoints; i++) {
2033 if (is->adj.points[i].off == 0) continue;
2034 curr = GRID(state, is->x+dx, is->y+dy);
2035 if (curr & mtype) continue; /* don't allow changes to marked lines. */
2036 if (ui->drag_is_noline) {
2037 if (curr & gtype) continue; /* no no-line where already a line */
2038 } else {
2039 if (POSSIBLES(state, dx, is->x+dx, is->y+dy) == 0) continue; /* no line if !possible. */
2040 if (curr & ntype) continue; /* can't have a bridge where there's a no-line. */
2043 if (is->adj.points[i].dx == dx &&
2044 is->adj.points[i].dy == dy) {
2045 ui->dragx_dst = ISLAND_ORTHX(is,i);
2046 ui->dragy_dst = ISLAND_ORTHY(is,i);
2049 /*debug(("update_drag src (%d,%d) d(%d,%d) dst (%d,%d)\n",
2050 ui->dragx_src, ui->dragy_src, dx, dy,
2051 ui->dragx_dst, ui->dragy_dst));*/
2052 return "";
2055 static char *finish_drag(game_state *state, game_ui *ui)
2057 char buf[80];
2059 if (ui->dragx_src == -1 || ui->dragy_src == -1)
2060 return NULL;
2061 if (ui->dragx_dst == -1 || ui->dragy_dst == -1)
2062 return ui_cancel_drag(ui);
2064 if (ui->drag_is_noline) {
2065 sprintf(buf, "N%d,%d,%d,%d",
2066 ui->dragx_src, ui->dragy_src,
2067 ui->dragx_dst, ui->dragy_dst);
2068 } else {
2069 sprintf(buf, "L%d,%d,%d,%d,%d",
2070 ui->dragx_src, ui->dragy_src,
2071 ui->dragx_dst, ui->dragy_dst, ui->nlines);
2074 ui_cancel_drag(ui);
2076 return dupstr(buf);
2079 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2080 int x, int y, int button)
2082 int gx = FROMCOORD(x), gy = FROMCOORD(y);
2083 char buf[80], *ret;
2084 grid_type ggrid = INGRID(state,gx,gy) ? GRID(state,gx,gy) : 0;
2086 if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
2087 if (!INGRID(state, gx, gy)) return NULL;
2088 if ((ggrid & G_ISLAND) && !(ggrid & G_MARK)) {
2089 ui->dragx_src = gx;
2090 ui->dragy_src = gy;
2091 return "";
2092 } else
2093 return ui_cancel_drag(ui);
2094 } else if (button == LEFT_DRAG || button == RIGHT_DRAG) {
2095 if (gx != ui->dragx_src || gy != ui->dragy_src) {
2096 ui->dragging = 1;
2097 ui->drag_is_noline = (button == RIGHT_DRAG) ? 1 : 0;
2098 return update_drag_dst(state, ui, ds, x, y);
2099 } else {
2100 /* cancel a drag when we go back to the starting point */
2101 ui->dragx_dst = -1;
2102 ui->dragy_dst = -1;
2103 return "";
2105 } else if (button == LEFT_RELEASE || button == RIGHT_RELEASE) {
2106 if (ui->dragging) {
2107 return finish_drag(state, ui);
2108 } else {
2109 ui_cancel_drag(ui);
2110 if (!INGRID(state, gx, gy)) return NULL;
2111 if (!(GRID(state, gx, gy) & G_ISLAND)) return NULL;
2112 sprintf(buf, "M%d,%d", gx, gy);
2113 return dupstr(buf);
2115 } else if (button == 'h' || button == 'H') {
2116 game_state *solved = dup_game(state);
2117 solve_for_hint(solved);
2118 ret = game_state_diff(state, solved);
2119 free_game(solved);
2120 return ret;
2123 return NULL;
2126 static game_state *execute_move(game_state *state, char *move)
2128 game_state *ret = dup_game(state);
2129 int x1, y1, x2, y2, nl, n;
2130 struct island *is1, *is2;
2131 char c;
2133 debug(("execute_move: %s\n", move));
2135 if (!*move) goto badmove;
2136 while (*move) {
2137 c = *move++;
2138 if (c == 'S') {
2139 ret->solved = TRUE;
2140 n = 0;
2141 } else if (c == 'L') {
2142 if (sscanf(move, "%d,%d,%d,%d,%d%n",
2143 &x1, &y1, &x2, &y2, &nl, &n) != 5)
2144 goto badmove;
2145 is1 = INDEX(ret, gridi, x1, y1);
2146 is2 = INDEX(ret, gridi, x2, y2);
2147 if (!is1 || !is2) goto badmove;
2148 if (nl < 0 || nl > state->maxb) goto badmove;
2149 island_join(is1, is2, nl, 0);
2150 } else if (c == 'N') {
2151 if (sscanf(move, "%d,%d,%d,%d%n",
2152 &x1, &y1, &x2, &y2, &n) != 4)
2153 goto badmove;
2154 is1 = INDEX(ret, gridi, x1, y1);
2155 is2 = INDEX(ret, gridi, x2, y2);
2156 if (!is1 || !is2) goto badmove;
2157 island_join(is1, is2, -1, 0);
2158 } else if (c == 'M') {
2159 if (sscanf(move, "%d,%d%n",
2160 &x1, &y1, &n) != 2)
2161 goto badmove;
2162 is1 = INDEX(ret, gridi, x1, y1);
2163 if (!is1) goto badmove;
2164 island_togglemark(is1);
2165 } else
2166 goto badmove;
2168 move += n;
2169 if (*move == ';')
2170 move++;
2171 else if (*move) goto badmove;
2174 map_update_possibles(ret);
2175 if (map_check(ret)) {
2176 debug(("Game completed.\n"));
2177 ret->completed = 1;
2179 return ret;
2181 badmove:
2182 debug(("%s: unrecognised move.\n", move));
2183 free_game(ret);
2184 return NULL;
2187 static char *solve_game(game_state *state, game_state *currstate,
2188 char *aux, char **error)
2190 char *ret;
2191 game_state *solved;
2193 if (aux) {
2194 debug(("solve_game: aux = %s\n", aux));
2195 solved = execute_move(state, aux);
2196 if (!solved) {
2197 *error = "Generated aux string is not a valid move (!).";
2198 return NULL;
2200 } else {
2201 solved = dup_game(state);
2202 /* solve with max strength... */
2203 if (solve_from_scratch(solved, 10) == 0) {
2204 free_game(solved);
2205 *error = "Game does not have a (non-recursive) solution.";
2206 return NULL;
2209 ret = game_state_diff(currstate, solved);
2210 free_game(solved);
2211 debug(("solve_game: ret = %s\n", ret));
2212 return ret;
2215 /* ----------------------------------------------------------------------
2216 * Drawing routines.
2219 static void game_compute_size(game_params *params, int tilesize,
2220 int *x, int *y)
2222 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2223 struct { int tilesize; } ads, *ds = &ads;
2224 ads.tilesize = tilesize;
2226 *x = TILE_SIZE * params->w + 2 * BORDER;
2227 *y = TILE_SIZE * params->h + 2 * BORDER;
2230 static void game_set_size(drawing *dr, game_drawstate *ds,
2231 game_params *params, int tilesize)
2233 ds->tilesize = tilesize;
2236 static float *game_colours(frontend *fe, int *ncolours)
2238 float *ret = snewn(3 * NCOLOURS, float);
2239 int i;
2241 game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
2243 for (i = 0; i < 3; i++) {
2244 ret[COL_FOREGROUND * 3 + i] = 0.0F;
2245 ret[COL_HINT * 3 + i] = ret[COL_LOWLIGHT * 3 + i];
2246 ret[COL_GRID * 3 + i] =
2247 (ret[COL_HINT * 3 + i] + ret[COL_BACKGROUND * 3 + i]) * 0.5F;
2248 ret[COL_MARK * 3 + i] = ret[COL_HIGHLIGHT * 3 + i];
2250 ret[COL_WARNING * 3 + 0] = 1.0F;
2251 ret[COL_WARNING * 3 + 1] = 0.25F;
2252 ret[COL_WARNING * 3 + 2] = 0.25F;
2254 ret[COL_SELECTED * 3 + 0] = 0.25F;
2255 ret[COL_SELECTED * 3 + 1] = 1.00F;
2256 ret[COL_SELECTED * 3 + 2] = 0.25F;
2258 *ncolours = NCOLOURS;
2259 return ret;
2262 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2264 struct game_drawstate *ds = snew(struct game_drawstate);
2265 int wh = state->w*state->h;
2267 ds->tilesize = 0;
2268 ds->w = state->w;
2269 ds->h = state->h;
2270 ds->started = 0;
2271 ds->grid = snewn(wh, grid_type);
2272 memset(ds->grid, -1, wh*sizeof(grid_type));
2273 ds->lv = snewn(wh, int);
2274 ds->lh = snewn(wh, int);
2275 memset(ds->lv, 0, wh*sizeof(int));
2276 memset(ds->lh, 0, wh*sizeof(int));
2278 return ds;
2281 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2283 sfree(ds->lv);
2284 sfree(ds->lh);
2285 sfree(ds->grid);
2286 sfree(ds);
2289 #define LINE_WIDTH (TILE_SIZE/8)
2290 #define TS8(x) (((x)*TILE_SIZE)/8)
2292 #define OFFSET(thing) ((TILE_SIZE/2) - ((thing)/2))
2294 static void lines_vert(drawing *dr, game_drawstate *ds,
2295 int ox, int oy, int lv, int col, grid_type v)
2297 int lw = LINE_WIDTH, gw = LINE_WIDTH, bw, i, loff;
2298 while ((bw = lw * lv + gw * (lv+1)) > TILE_SIZE)
2299 gw--;
2300 loff = OFFSET(bw);
2301 if (v & G_MARKV)
2302 draw_rect(dr, ox + loff, oy, bw, TILE_SIZE, COL_MARK);
2303 for (i = 0; i < lv; i++, loff += lw + gw)
2304 draw_rect(dr, ox + loff + gw, oy, lw, TILE_SIZE, col);
2307 static void lines_horiz(drawing *dr, game_drawstate *ds,
2308 int ox, int oy, int lh, int col, grid_type v)
2310 int lw = LINE_WIDTH, gw = LINE_WIDTH, bw, i, loff;
2311 while ((bw = lw * lh + gw * (lh+1)) > TILE_SIZE)
2312 gw--;
2313 loff = OFFSET(bw);
2314 if (v & G_MARKH)
2315 draw_rect(dr, ox, oy + loff, TILE_SIZE, bw, COL_MARK);
2316 for (i = 0; i < lh; i++, loff += lw + gw)
2317 draw_rect(dr, ox, oy + loff + gw, TILE_SIZE, lw, col);
2320 static void line_cross(drawing *dr, game_drawstate *ds,
2321 int ox, int oy, int col, grid_type v)
2323 int off = TS8(2);
2324 draw_line(dr, ox, oy, ox+off, oy+off, col);
2325 draw_line(dr, ox+off, oy, ox, oy+off, col);
2328 static void lines_lvlh(game_state *state, int x, int y, grid_type v,
2329 int *lv_r, int *lh_r)
2331 int lh = 0, lv = 0;
2333 if (v & G_LINEV) lv = INDEX(state,lines,x,y);
2334 if (v & G_LINEH) lh = INDEX(state,lines,x,y);
2336 #ifdef DRAW_HINTS
2337 if (INDEX(state, possv, x, y) && !lv) {
2338 lv = INDEX(state, possv, x, y);
2340 if (INDEX(state, possh, x, y) && !lh) {
2341 lh = INDEX(state, possh, x, y);
2343 #endif
2344 /*debug(("lvlh: (%d,%d) v 0x%x lv %d lh %d.\n", x, y, v, lv, lh));*/
2345 *lv_r = lv; *lh_r = lh;
2348 static void dsf_debug_draw(drawing *dr,
2349 game_state *state, game_drawstate *ds,
2350 int x, int y)
2352 #ifdef DRAW_DSF
2353 int ts = TILE_SIZE/2;
2354 int ox = COORD(x) + ts/2, oy = COORD(y) + ts/2;
2355 char str[10];
2357 sprintf(str, "%d", dsf_canonify(state->solver->dsf, DINDEX(x,y)));
2358 draw_text(dr, ox, oy, FONT_VARIABLE, ts,
2359 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_WARNING, str);
2360 #endif
2363 static void lines_redraw(drawing *dr,
2364 game_state *state, game_drawstate *ds, game_ui *ui,
2365 int x, int y, grid_type v, int lv, int lh)
2367 int ox = COORD(x), oy = COORD(y);
2368 int vcol = (v & G_FLASH) ? COL_HIGHLIGHT :
2369 (v & G_WARN) ? COL_WARNING : COL_FOREGROUND, hcol = vcol;
2370 grid_type todraw = v & G_NOLINE;
2372 if (v & G_ISSEL) {
2373 if (ui->todraw & G_FLAGSH) hcol = COL_SELECTED;
2374 if (ui->todraw & G_FLAGSV) vcol = COL_SELECTED;
2375 todraw |= ui->todraw;
2378 draw_rect(dr, ox, oy, TILE_SIZE, TILE_SIZE, COL_BACKGROUND);
2380 #ifdef DRAW_HINTS
2381 if (INDEX(state, possv, x, y) && !(v & G_LINEV))
2382 vcol = COL_HINT;
2383 if (INDEX(state, possh, x, y) && !(v & G_LINEH))
2384 hcol = COL_HINT;
2385 #endif
2386 #ifdef DRAW_GRID
2387 draw_rect_outline(dr, ox, oy, TILE_SIZE, TILE_SIZE, COL_GRID);
2388 #endif
2390 if (todraw & G_NOLINEV) {
2391 line_cross(dr, ds, ox + TS8(3), oy + TS8(1), vcol, todraw);
2392 line_cross(dr, ds, ox + TS8(3), oy + TS8(5), vcol, todraw);
2394 if (todraw & G_NOLINEH) {
2395 line_cross(dr, ds, ox + TS8(1), oy + TS8(3), hcol, todraw);
2396 line_cross(dr, ds, ox + TS8(5), oy + TS8(3), hcol, todraw);
2398 if (lv)
2399 lines_vert(dr, ds, ox, oy, lv, vcol, v);
2400 if (lh)
2401 lines_horiz(dr, ds, ox, oy, lh, hcol, v);
2403 dsf_debug_draw(dr, state, ds, x, y);
2404 draw_update(dr, ox, oy, TILE_SIZE, TILE_SIZE);
2407 #define ISLAND_RADIUS ((TILE_SIZE*12)/20)
2408 #define ISLAND_NUMSIZE(is) \
2409 (((is)->count < 10) ? (TILE_SIZE*7)/10 : (TILE_SIZE*5)/10)
2411 static void island_redraw(drawing *dr,
2412 game_state *state, game_drawstate *ds,
2413 struct island *is, grid_type v)
2415 /* These overlap the edges of their squares, which is why they're drawn later.
2416 * We know they can't overlap each other because they're not allowed within 2
2417 * squares of each other. */
2418 int half = TILE_SIZE/2;
2419 int ox = COORD(is->x) + half, oy = COORD(is->y) + half;
2420 int orad = ISLAND_RADIUS, irad = orad - LINE_WIDTH;
2421 int updatesz = orad*2+1;
2422 int tcol = (v & G_FLASH) ? COL_HIGHLIGHT :
2423 (v & G_WARN) ? COL_WARNING : COL_FOREGROUND;
2424 int col = (v & G_ISSEL) ? COL_SELECTED : tcol;
2425 int bg = (v & G_MARK) ? COL_MARK : COL_BACKGROUND;
2426 char str[10];
2428 #ifdef DRAW_GRID
2429 draw_rect_outline(dr, COORD(is->x), COORD(is->y),
2430 TILE_SIZE, TILE_SIZE, COL_GRID);
2431 #endif
2433 /* draw a thick circle */
2434 draw_circle(dr, ox, oy, orad, col, col);
2435 draw_circle(dr, ox, oy, irad, bg, bg);
2437 sprintf(str, "%d", is->count);
2438 draw_text(dr, ox, oy, FONT_VARIABLE, ISLAND_NUMSIZE(is),
2439 ALIGN_VCENTRE | ALIGN_HCENTRE, tcol, str);
2441 dsf_debug_draw(dr, state, ds, is->x, is->y);
2442 draw_update(dr, ox - orad, oy - orad, updatesz, updatesz);
2445 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2446 game_state *state, int dir, game_ui *ui,
2447 float animtime, float flashtime)
2449 int x, y, force = 0, i, j, redraw, lv, lh;
2450 grid_type v, dsv, flash = 0;
2451 struct island *is, *is_drag_src = NULL, *is_drag_dst = NULL;
2453 if (flashtime) {
2454 int f = (int)(flashtime * 5 / FLASH_TIME);
2455 if (f == 1 || f == 3) flash = G_FLASH;
2458 /* Clear screen, if required. */
2459 if (!ds->started) {
2460 draw_rect(dr, 0, 0,
2461 TILE_SIZE * ds->w + 2 * BORDER,
2462 TILE_SIZE * ds->h + 2 * BORDER, COL_BACKGROUND);
2463 #ifdef DRAW_GRID
2464 draw_rect_outline(dr,
2465 COORD(0)-1, COORD(0)-1,
2466 TILE_SIZE * ds->w + 2, TILE_SIZE * ds->h + 2,
2467 COL_GRID);
2468 #endif
2469 draw_update(dr, 0, 0,
2470 TILE_SIZE * ds->w + 2 * BORDER,
2471 TILE_SIZE * ds->h + 2 * BORDER);
2472 ds->started = 1;
2473 force = 1;
2476 if (ui->dragx_src != -1 && ui->dragy_src != -1) {
2477 ds->dragging = 1;
2478 is_drag_src = INDEX(state, gridi, ui->dragx_src, ui->dragy_src);
2479 assert(is_drag_src);
2480 if (ui->dragx_dst != -1 && ui->dragy_dst != -1) {
2481 is_drag_dst = INDEX(state, gridi, ui->dragx_dst, ui->dragy_dst);
2482 assert(is_drag_dst);
2484 } else
2485 ds->dragging = 0;
2487 /* Draw all lines (and hints, if we want), but *not* islands. */
2488 for (x = 0; x < ds->w; x++) {
2489 for (y = 0; y < ds->h; y++) {
2490 v = GRID(state, x, y) | flash;
2491 dsv = GRID(ds,x,y) & ~G_REDRAW;
2493 if (v & G_ISLAND) continue;
2495 if (is_drag_dst) {
2496 if (WITHIN(x,is_drag_src->x, is_drag_dst->x) &&
2497 WITHIN(y,is_drag_src->y, is_drag_dst->y))
2498 v |= G_ISSEL;
2500 lines_lvlh(state, x, y, v, &lv, &lh);
2502 if (v != dsv ||
2503 lv != INDEX(ds,lv,x,y) ||
2504 lh != INDEX(ds,lh,x,y) ||
2505 force) {
2506 GRID(ds, x, y) = v | G_REDRAW;
2507 INDEX(ds,lv,x,y) = lv;
2508 INDEX(ds,lh,x,y) = lh;
2509 lines_redraw(dr, state, ds, ui, x, y, v, lv, lh);
2510 } else
2511 GRID(ds,x,y) &= ~G_REDRAW;
2515 /* Draw islands. */
2516 for (i = 0; i < state->n_islands; i++) {
2517 is = &state->islands[i];
2518 v = GRID(state, is->x, is->y) | flash;
2520 redraw = 0;
2521 for (j = 0; j < is->adj.npoints; j++) {
2522 if (GRID(ds,is->adj.points[j].x,is->adj.points[j].y) & G_REDRAW) {
2523 redraw = 1;
2527 if (is_drag_src) {
2528 if (is == is_drag_src)
2529 v |= G_ISSEL;
2530 else if (is_drag_dst && is == is_drag_dst)
2531 v |= G_ISSEL;
2534 if (island_impossible(is, v & G_MARK)) v |= G_WARN;
2536 if ((v != GRID(ds, is->x, is->y)) || force || redraw) {
2537 GRID(ds,is->x,is->y) = v;
2538 island_redraw(dr, state, ds, is, v);
2543 static float game_anim_length(game_state *oldstate, game_state *newstate,
2544 int dir, game_ui *ui)
2546 return 0.0F;
2549 static float game_flash_length(game_state *oldstate, game_state *newstate,
2550 int dir, game_ui *ui)
2552 if (!oldstate->completed && newstate->completed &&
2553 !oldstate->solved && !newstate->solved)
2554 return FLASH_TIME;
2556 return 0.0F;
2559 static int game_timing_state(game_state *state, game_ui *ui)
2561 return TRUE;
2564 static void game_print_size(game_params *params, float *x, float *y)
2566 int pw, ph;
2568 /* 10mm squares by default. */
2569 game_compute_size(params, 1000, &pw, &ph);
2570 *x = pw / 100.0;
2571 *y = ph / 100.0;
2574 static void game_print(drawing *dr, game_state *state, int ts)
2576 int ink = print_mono_colour(dr, 0);
2577 int paper = print_mono_colour(dr, 1);
2578 int x, y, cx, cy, i, nl;
2579 int loff = ts/8;
2580 grid_type grid;
2582 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2583 game_drawstate ads, *ds = &ads;
2584 ads.tilesize = ts;
2586 /* I don't think this wants a border. */
2588 /* Bridges */
2589 print_line_width(dr, ts / 12);
2590 for (x = 0; x < state->w; x++) {
2591 for (y = 0; y < state->h; y++) {
2592 cx = COORD(x); cy = COORD(y);
2593 grid = GRID(state,x,y);
2594 nl = INDEX(state,lines,x,y);
2596 if (grid & G_ISLAND) continue;
2597 if (grid & G_LINEV) {
2598 if (nl > 1) {
2599 draw_line(dr, cx+ts/2-loff, cy, cx+ts/2-loff, cy+ts, ink);
2600 draw_line(dr, cx+ts/2+loff, cy, cx+ts/2+loff, cy+ts, ink);
2601 } else {
2602 draw_line(dr, cx+ts/2, cy, cx+ts/2, cy+ts, ink);
2605 if (grid & G_LINEH) {
2606 if (nl > 1) {
2607 draw_line(dr, cx, cy+ts/2-loff, cx+ts, cy+ts/2-loff, ink);
2608 draw_line(dr, cx, cy+ts/2+loff, cx+ts, cy+ts/2+loff, ink);
2609 } else {
2610 draw_line(dr, cx, cy+ts/2, cx+ts, cy+ts/2, ink);
2616 /* Islands */
2617 for (i = 0; i < state->n_islands; i++) {
2618 char str[10];
2619 struct island *is = &state->islands[i];
2620 grid = GRID(state, is->x, is->y);
2621 cx = COORD(is->x) + ts/2;
2622 cy = COORD(is->y) + ts/2;
2624 draw_circle(dr, cx, cy, ISLAND_RADIUS, paper, ink);
2626 sprintf(str, "%d", is->count);
2627 draw_text(dr, cx, cy, FONT_VARIABLE, ISLAND_NUMSIZE(is),
2628 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
2632 #ifdef COMBINED
2633 #define thegame bridges
2634 #endif
2636 const struct game thegame = {
2637 "Bridges", "games.bridges", "bridges",
2638 default_params,
2639 game_fetch_preset,
2640 decode_params,
2641 encode_params,
2642 free_params,
2643 dup_params,
2644 TRUE, game_configure, custom_params,
2645 validate_params,
2646 new_game_desc,
2647 validate_desc,
2648 new_game,
2649 dup_game,
2650 free_game,
2651 TRUE, solve_game,
2652 TRUE, game_can_format_as_text_now, game_text_format,
2653 new_ui,
2654 free_ui,
2655 encode_ui,
2656 decode_ui,
2657 game_changed_state,
2658 interpret_move,
2659 execute_move,
2660 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2661 game_colours,
2662 game_new_drawstate,
2663 game_free_drawstate,
2664 game_redraw,
2665 game_anim_length,
2666 game_flash_length,
2667 TRUE, FALSE, game_print_size, game_print,
2668 FALSE, /* wants_statusbar */
2669 FALSE, game_timing_state,
2670 REQUIRE_RBUTTON, /* flags */
2673 /* vim: set shiftwidth=4 tabstop=8: */