chiark / gitweb /
8f8ff7579c76bb3a18c5e5af6c33a40497c06565
[sgt-puzzles.git] / bridges.c
1 /*
2  * bridges.c: Implementation of the Nikoli game 'Bridges'.
3  *
4  * Things still to do:
5  *
6  * * write a recursive solver?
7  */
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <assert.h>
13 #include <ctype.h>
14 #include <math.h>
15
16 #include "puzzles.h"
17
18 /* Turn this on for hints about which lines are considered possibilities. */
19 #undef DRAW_GRID
20 #undef DRAW_DSF
21
22 /* --- structures for params, state, etc. --- */
23
24 #define MAX_BRIDGES     4
25
26 #define PREFERRED_TILE_SIZE 24
27 #define TILE_SIZE       (ds->tilesize)
28 #define BORDER          (TILE_SIZE / 2)
29
30 #define COORD(x)  ( (x) * TILE_SIZE + BORDER )
31 #define FROMCOORD(x)  ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
32
33 #define FLASH_TIME 0.50F
34
35 enum {
36     COL_BACKGROUND,
37     COL_FOREGROUND,
38     COL_HIGHLIGHT, COL_LOWLIGHT,
39     COL_SELECTED, COL_MARK,
40     COL_HINT, COL_GRID,
41     COL_WARNING,
42     COL_CURSOR,
43     NCOLOURS
44 };
45
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;
50 };
51
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)
63
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
69 #define G_CURSOR        0x0800
70
71 /* flags used by the solver etc. */
72 #define G_SWEEP         0x1000
73
74 #define G_FLAGSH        (G_LINEH|G_MARKH|G_NOLINEH)
75 #define G_FLAGSV        (G_LINEV|G_MARKV|G_NOLINEV)
76
77 typedef unsigned int grid_type; /* change me later if we invent > 16 bits of flags. */
78
79 struct solver_state {
80     int *dsf, *comptspaces;
81     int *tmpdsf, *tmpcompspaces;
82     int refcount;
83 };
84
85 /* state->gridi is an optimisation; it stores the pointer to the island
86  * structs indexed by (x,y). It's not strictly necessary (we could use
87  * find234 instead), but Purify showed that board generation (mostly the solver)
88  * was spending 60% of its time in find234. */
89
90 struct surrounds { /* cloned from lightup.c */
91     struct { int x, y, dx, dy, off; } points[4];
92     int npoints, nislands;
93 };
94
95 struct island {
96   game_state *state;
97   int x, y, count;
98   struct surrounds adj;
99 };
100
101 struct game_state {
102     int w, h, completed, solved, allowloops, maxb;
103     grid_type *grid, *scratch;
104     struct island *islands;
105     int n_islands, n_islands_alloc;
106     game_params params; /* used by the aux solver. */
107 #define N_WH_ARRAYS 5
108     char *wha, *possv, *possh, *lines, *maxv, *maxh;
109     struct island **gridi;
110     struct solver_state *solver; /* refcounted */
111 };
112
113 #define GRIDSZ(s) ((s)->w * (s)->h * sizeof(grid_type))
114
115 #define INGRID(s,x,y) ((x) >= 0 && (x) < (s)->w && (y) >= 0 && (y) < (s)->h)
116
117 #define DINDEX(x,y) ((y)*state->w + (x))
118
119 #define INDEX(s,g,x,y) ((s)->g[(y)*((s)->w) + (x)])
120 #define IDX(s,g,i) ((s)->g[(i)])
121 #define GRID(s,x,y) INDEX(s,grid,x,y)
122 #define SCRATCH(s,x,y) INDEX(s,scratch,x,y)
123 #define POSSIBLES(s,dx,x,y) ((dx) ? (INDEX(s,possh,x,y)) : (INDEX(s,possv,x,y)))
124 #define MAXIMUM(s,dx,x,y) ((dx) ? (INDEX(s,maxh,x,y)) : (INDEX(s,maxv,x,y)))
125
126 #define GRIDCOUNT(s,x,y,f) ((GRID(s,x,y) & (f)) ? (INDEX(s,lines,x,y)) : 0)
127
128 #define WITHIN2(x,min,max) (((x) < (min)) ? 0 : (((x) > (max)) ? 0 : 1))
129 #define WITHIN(x,min,max) ((min) > (max) ? \
130                            WITHIN2(x,max,min) : WITHIN2(x,min,max))
131
132 /* --- island struct and tree support functions --- */
133
134 #define ISLAND_ORTH(is,j,f,df) \
135     (is->f + (is->adj.points[(j)].off*is->adj.points[(j)].df))
136
137 #define ISLAND_ORTHX(is,j) ISLAND_ORTH(is,j,x,dx)
138 #define ISLAND_ORTHY(is,j) ISLAND_ORTH(is,j,y,dy)
139
140 static void fixup_islands_for_realloc(game_state *state)
141 {
142     int i;
143
144     for (i = 0; i < state->w*state->h; i++) state->gridi[i] = NULL;
145     for (i = 0; i < state->n_islands; i++) {
146         struct island *is = &state->islands[i];
147         is->state = state;
148         INDEX(state, gridi, is->x, is->y) = is;
149     }
150 }
151
152 static int game_can_format_as_text_now(game_params *params)
153 {
154     return TRUE;
155 }
156
157 static char *game_text_format(game_state *state)
158 {
159     int x, y, len, nl;
160     char *ret, *p;
161     struct island *is;
162     grid_type grid;
163
164     len = (state->h) * (state->w+1) + 1;
165     ret = snewn(len, char);
166     p = ret;
167
168     for (y = 0; y < state->h; y++) {
169         for (x = 0; x < state->w; x++) {
170             grid = GRID(state,x,y);
171             nl = INDEX(state,lines,x,y);
172             is = INDEX(state, gridi, x, y);
173             if (is) {
174                 *p++ = '0' + is->count;
175             } else if (grid & G_LINEV) {
176                 *p++ = (nl > 1) ? '"' : (nl == 1) ? '|' : '!'; /* gaah, want a double-bar. */
177             } else if (grid & G_LINEH) {
178                 *p++ = (nl > 1) ? '=' : (nl == 1) ? '-' : '~';
179             } else {
180                 *p++ = '.';
181             }
182         }
183         *p++ = '\n';
184     }
185     *p++ = '\0';
186
187     assert(p - ret == len);
188     return ret;
189 }
190
191 static void debug_state(game_state *state)
192 {
193     char *textversion = game_text_format(state);
194     debug(("%s", textversion));
195     sfree(textversion);
196 }
197
198 /*static void debug_possibles(game_state *state)
199 {
200     int x, y;
201     debug(("possh followed by possv\n"));
202     for (y = 0; y < state->h; y++) {
203         for (x = 0; x < state->w; x++) {
204             debug(("%d", POSSIBLES(state, 1, x, y)));
205         }
206         debug((" "));
207         for (x = 0; x < state->w; x++) {
208             debug(("%d", POSSIBLES(state, 0, x, y)));
209         }
210         debug(("\n"));
211     }
212     debug(("\n"));
213         for (y = 0; y < state->h; y++) {
214         for (x = 0; x < state->w; x++) {
215             debug(("%d", MAXIMUM(state, 1, x, y)));
216         }
217         debug((" "));
218         for (x = 0; x < state->w; x++) {
219             debug(("%d", MAXIMUM(state, 0, x, y)));
220         }
221         debug(("\n"));
222     }
223     debug(("\n"));
224 }*/
225
226 static void island_set_surrounds(struct island *is)
227 {
228     assert(INGRID(is->state,is->x,is->y));
229     is->adj.npoints = is->adj.nislands = 0;
230 #define ADDPOINT(cond,ddx,ddy) do {\
231     if (cond) { \
232         is->adj.points[is->adj.npoints].x = is->x+(ddx); \
233         is->adj.points[is->adj.npoints].y = is->y+(ddy); \
234         is->adj.points[is->adj.npoints].dx = (ddx); \
235         is->adj.points[is->adj.npoints].dy = (ddy); \
236         is->adj.points[is->adj.npoints].off = 0; \
237         is->adj.npoints++; \
238     } } while(0)
239     ADDPOINT(is->x > 0,                -1,  0);
240     ADDPOINT(is->x < (is->state->w-1), +1,  0);
241     ADDPOINT(is->y > 0,                 0, -1);
242     ADDPOINT(is->y < (is->state->h-1),  0, +1);
243 }
244
245 static void island_find_orthogonal(struct island *is)
246 {
247     /* fills in the rest of the 'surrounds' structure, assuming
248      * all other islands are now in place. */
249     int i, x, y, dx, dy, off;
250
251     is->adj.nislands = 0;
252     for (i = 0; i < is->adj.npoints; i++) {
253         dx = is->adj.points[i].dx;
254         dy = is->adj.points[i].dy;
255         x = is->x + dx;
256         y = is->y + dy;
257         off = 1;
258         is->adj.points[i].off = 0;
259         while (INGRID(is->state, x, y)) {
260             if (GRID(is->state, x, y) & G_ISLAND) {
261                 is->adj.points[i].off = off;
262                 is->adj.nislands++;
263                 /*debug(("island (%d,%d) has orth is. %d*(%d,%d) away at (%d,%d).\n",
264                        is->x, is->y, off, dx, dy,
265                        ISLAND_ORTHX(is,i), ISLAND_ORTHY(is,i)));*/
266                 goto foundisland;
267             }
268             off++; x += dx; y += dy;
269         }
270 foundisland:
271         ;
272     }
273 }
274
275 static int island_hasbridge(struct island *is, int direction)
276 {
277     int x = is->adj.points[direction].x;
278     int y = is->adj.points[direction].y;
279     grid_type gline = is->adj.points[direction].dx ? G_LINEH : G_LINEV;
280
281     if (GRID(is->state, x, y) & gline) return 1;
282     return 0;
283 }
284
285 static struct island *island_find_connection(struct island *is, int adjpt)
286 {
287     struct island *is_r;
288
289     assert(adjpt < is->adj.npoints);
290     if (!is->adj.points[adjpt].off) return NULL;
291     if (!island_hasbridge(is, adjpt)) return NULL;
292
293     is_r = INDEX(is->state, gridi,
294                  ISLAND_ORTHX(is, adjpt), ISLAND_ORTHY(is, adjpt));
295     assert(is_r);
296
297     return is_r;
298 }
299
300 static struct island *island_add(game_state *state, int x, int y, int count)
301 {
302     struct island *is;
303     int realloced = 0;
304
305     assert(!(GRID(state,x,y) & G_ISLAND));
306     GRID(state,x,y) |= G_ISLAND;
307
308     state->n_islands++;
309     if (state->n_islands > state->n_islands_alloc) {
310         state->n_islands_alloc = state->n_islands * 2;
311         state->islands =
312             sresize(state->islands, state->n_islands_alloc, struct island);
313         realloced = 1;
314     }
315     is = &state->islands[state->n_islands-1];
316
317     memset(is, 0, sizeof(struct island));
318     is->state = state;
319     is->x = x;
320     is->y = y;
321     is->count = count;
322     island_set_surrounds(is);
323
324     if (realloced)
325         fixup_islands_for_realloc(state);
326     else
327         INDEX(state, gridi, x, y) = is;
328
329     return is;
330 }
331
332
333 /* n = -1 means 'flip NOLINE flags [and set line to 0].' */
334 static void island_join(struct island *i1, struct island *i2, int n, int is_max)
335 {
336     game_state *state = i1->state;
337     int s, e, x, y;
338
339     assert(i1->state == i2->state);
340     assert(n >= -1 && n <= i1->state->maxb);
341
342     if (i1->x == i2->x) {
343         x = i1->x;
344         if (i1->y < i2->y) {
345             s = i1->y+1; e = i2->y-1;
346         } else {
347             s = i2->y+1; e = i1->y-1;
348         }
349         for (y = s; y <= e; y++) {
350             if (is_max) {
351                 INDEX(state,maxv,x,y) = n;
352             } else {
353                 if (n < 0) {
354                     GRID(state,x,y) ^= G_NOLINEV;
355                 } else if (n == 0) {
356                     GRID(state,x,y) &= ~G_LINEV;
357                 } else {
358                     GRID(state,x,y) |= G_LINEV;
359                     INDEX(state,lines,x,y) = n;
360                 }
361             }
362         }
363     } else if (i1->y == i2->y) {
364         y = i1->y;
365         if (i1->x < i2->x) {
366             s = i1->x+1; e = i2->x-1;
367         } else {
368             s = i2->x+1; e = i1->x-1;
369         }
370         for (x = s; x <= e; x++) {
371             if (is_max) {
372                 INDEX(state,maxh,x,y) = n;
373             } else {
374                 if (n < 0) {
375                     GRID(state,x,y) ^= G_NOLINEH;
376                 } else if (n == 0) {
377                     GRID(state,x,y) &= ~G_LINEH;
378                 } else {
379                     GRID(state,x,y) |= G_LINEH;
380                     INDEX(state,lines,x,y) = n;
381                 }
382             }
383         }
384     } else {
385         assert(!"island_join: islands not orthogonal.");
386     }
387 }
388
389 /* Counts the number of bridges currently attached to the island. */
390 static int island_countbridges(struct island *is)
391 {
392     int i, c = 0;
393
394     for (i = 0; i < is->adj.npoints; i++) {
395         c += GRIDCOUNT(is->state,
396                        is->adj.points[i].x, is->adj.points[i].y,
397                        is->adj.points[i].dx ? G_LINEH : G_LINEV);
398     }
399     /*debug(("island count for (%d,%d) is %d.\n", is->x, is->y, c));*/
400     return c;
401 }
402
403 static int island_adjspace(struct island *is, int marks, int missing,
404                            int direction)
405 {
406     int x, y, poss, curr, dx;
407     grid_type gline, mline;
408
409     x = is->adj.points[direction].x;
410     y = is->adj.points[direction].y;
411     dx = is->adj.points[direction].dx;
412     gline = dx ? G_LINEH : G_LINEV;
413
414     if (marks) {
415         mline = dx ? G_MARKH : G_MARKV;
416         if (GRID(is->state,x,y) & mline) return 0;
417     }
418     poss = POSSIBLES(is->state, dx, x, y);
419     poss = min(poss, missing);
420
421     curr = GRIDCOUNT(is->state, x, y, gline);
422     poss = min(poss, MAXIMUM(is->state, dx, x, y) - curr);
423
424     return poss;
425 }
426
427 /* Counts the number of bridge spaces left around the island;
428  * expects the possibles to be up-to-date. */
429 static int island_countspaces(struct island *is, int marks)
430 {
431     int i, c = 0, missing;
432
433     missing = is->count - island_countbridges(is);
434     if (missing < 0) return 0;
435
436     for (i = 0; i < is->adj.npoints; i++) {
437         c += island_adjspace(is, marks, missing, i);
438     }
439     return c;
440 }
441
442 static int island_isadj(struct island *is, int direction)
443 {
444     int x, y;
445     grid_type gline, mline;
446
447     x = is->adj.points[direction].x;
448     y = is->adj.points[direction].y;
449
450     mline = is->adj.points[direction].dx ? G_MARKH : G_MARKV;
451     gline = is->adj.points[direction].dx ? G_LINEH : G_LINEV;
452     if (GRID(is->state, x, y) & mline) {
453         /* If we're marked (i.e. the thing to attach to is complete)
454          * only count an adjacency if we're already attached. */
455         return GRIDCOUNT(is->state, x, y, gline);
456     } else {
457         /* If we're unmarked, count possible adjacency iff it's
458          * flagged as POSSIBLE. */
459         return POSSIBLES(is->state, is->adj.points[direction].dx, x, y);
460     }
461     return 0;
462 }
463
464 /* Counts the no. of possible adjacent islands (including islands
465  * we're already connected to). */
466 static int island_countadj(struct island *is)
467 {
468     int i, nadj = 0;
469
470     for (i = 0; i < is->adj.npoints; i++) {
471         if (island_isadj(is, i)) nadj++;
472     }
473     return nadj;
474 }
475
476 static void island_togglemark(struct island *is)
477 {
478     int i, j, x, y, o;
479     struct island *is_loop;
480
481     /* mark the island... */
482     GRID(is->state, is->x, is->y) ^= G_MARK;
483
484     /* ...remove all marks on non-island squares... */
485     for (x = 0; x < is->state->w; x++) {
486         for (y = 0; y < is->state->h; y++) {
487             if (!(GRID(is->state, x, y) & G_ISLAND))
488                 GRID(is->state, x, y) &= ~G_MARK;
489         }
490     }
491
492     /* ...and add marks to squares around marked islands. */
493     for (i = 0; i < is->state->n_islands; i++) {
494         is_loop = &is->state->islands[i];
495         if (!(GRID(is_loop->state, is_loop->x, is_loop->y) & G_MARK))
496             continue;
497
498         for (j = 0; j < is_loop->adj.npoints; j++) {
499             /* if this direction takes us to another island, mark all
500              * squares between the two islands. */
501             if (!is_loop->adj.points[j].off) continue;
502             assert(is_loop->adj.points[j].off > 1);
503             for (o = 1; o < is_loop->adj.points[j].off; o++) {
504                 GRID(is_loop->state,
505                      is_loop->x + is_loop->adj.points[j].dx*o,
506                      is_loop->y + is_loop->adj.points[j].dy*o) |=
507                     is_loop->adj.points[j].dy ? G_MARKV : G_MARKH;
508             }
509         }
510     }
511 }
512
513 static int island_impossible(struct island *is, int strict)
514 {
515     int curr = island_countbridges(is), nspc = is->count - curr, nsurrspc;
516     int i, poss;
517     struct island *is_orth;
518
519     if (nspc < 0) {
520         debug(("island at (%d,%d) impossible because full.\n", is->x, is->y));
521         return 1;        /* too many bridges */
522     } else if ((curr + island_countspaces(is, 0)) < is->count) {
523         debug(("island at (%d,%d) impossible because not enough spaces.\n", is->x, is->y));
524         return 1;        /* impossible to create enough bridges */
525     } else if (strict && curr < is->count) {
526         debug(("island at (%d,%d) impossible because locked.\n", is->x, is->y));
527         return 1;        /* not enough bridges and island is locked */
528     }
529
530     /* Count spaces in surrounding islands. */
531     nsurrspc = 0;
532     for (i = 0; i < is->adj.npoints; i++) {
533         int ifree, dx = is->adj.points[i].dx;
534
535         if (!is->adj.points[i].off) continue;
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);
542
543         ifree = is_orth->count - island_countbridges(is_orth);
544         if (ifree > 0) {
545             /*
546              * ifree is the number of bridges unfilled in the other
547              * island, which is clearly an upper bound on the number
548              * of extra bridges this island may run to it.
549              *
550              * Another upper bound is the number of bridges unfilled
551              * on the specific line between here and there. We must
552              * take the minimum of both.
553              */
554             int bmax = MAXIMUM(is->state, dx,
555                                is->adj.points[i].x, is->adj.points[i].y);
556             int bcurr = GRIDCOUNT(is->state,
557                                   is->adj.points[i].x, is->adj.points[i].y,
558                                   dx ? G_LINEH : G_LINEV);
559             assert(bcurr <= bmax);
560             nsurrspc += min(ifree, bmax - bcurr);
561         }
562     }
563     if (nsurrspc < nspc) {
564         debug(("island at (%d,%d) impossible: surr. islands %d spc, need %d.\n",
565                is->x, is->y, nsurrspc, nspc));
566         return 1;       /* not enough spaces around surrounding islands to fill this one. */
567     }
568
569     return 0;
570 }
571
572 /* --- Game parameter functions --- */
573
574 #define DEFAULT_PRESET 0
575
576 const struct game_params bridges_presets[] = {
577   { 7, 7, 2, 30, 10, 1, 0 },
578   { 7, 7, 2, 30, 10, 1, 1 },
579   { 7, 7, 2, 30, 10, 1, 2 },
580   { 10, 10, 2, 30, 10, 1, 0 },
581   { 10, 10, 2, 30, 10, 1, 1 },
582   { 10, 10, 2, 30, 10, 1, 2 },
583   { 15, 15, 2, 30, 10, 1, 0 },
584   { 15, 15, 2, 30, 10, 1, 1 },
585   { 15, 15, 2, 30, 10, 1, 2 },
586 };
587
588 static game_params *default_params(void)
589 {
590     game_params *ret = snew(game_params);
591     *ret = bridges_presets[DEFAULT_PRESET];
592
593     return ret;
594 }
595
596 static int game_fetch_preset(int i, char **name, game_params **params)
597 {
598     game_params *ret;
599     char buf[80];
600
601     if (i < 0 || i >= lenof(bridges_presets))
602         return FALSE;
603
604     ret = default_params();
605     *ret = bridges_presets[i];
606     *params = ret;
607
608     sprintf(buf, "%dx%d %s", ret->w, ret->h,
609             ret->difficulty == 0 ? "easy" :
610             ret->difficulty == 1 ? "medium" : "hard");
611     *name = dupstr(buf);
612
613     return TRUE;
614 }
615
616 static void free_params(game_params *params)
617 {
618     sfree(params);
619 }
620
621 static game_params *dup_params(game_params *params)
622 {
623     game_params *ret = snew(game_params);
624     *ret = *params;                    /* structure copy */
625     return ret;
626 }
627
628 #define EATNUM(x) do { \
629     (x) = atoi(string); \
630     while (*string && isdigit((unsigned char)*string)) string++; \
631 } while(0)
632
633 static void decode_params(game_params *params, char const *string)
634 {
635     EATNUM(params->w);
636     params->h = params->w;
637     if (*string == 'x') {
638         string++;
639         EATNUM(params->h);
640     }
641     if (*string == 'i') {
642         string++;
643         EATNUM(params->islands);
644     }
645     if (*string == 'e') {
646         string++;
647         EATNUM(params->expansion);
648     }
649     if (*string == 'm') {
650         string++;
651         EATNUM(params->maxb);
652     }
653     params->allowloops = 1;
654     if (*string == 'L') {
655         string++;
656         params->allowloops = 0;
657     }
658     if (*string == 'd') {
659         string++;
660         EATNUM(params->difficulty);
661     }
662 }
663
664 static char *encode_params(game_params *params, int full)
665 {
666     char buf[80];
667
668     if (full) {
669         sprintf(buf, "%dx%di%de%dm%d%sd%d",
670                 params->w, params->h, params->islands, params->expansion,
671                 params->maxb, params->allowloops ? "" : "L",
672                 params->difficulty);
673     } else {
674         sprintf(buf, "%dx%dm%d%s", params->w, params->h,
675                 params->maxb, params->allowloops ? "" : "L");
676     }
677     return dupstr(buf);
678 }
679
680 static config_item *game_configure(game_params *params)
681 {
682     config_item *ret;
683     char buf[80];
684
685     ret = snewn(8, config_item);
686
687     ret[0].name = "Width";
688     ret[0].type = C_STRING;
689     sprintf(buf, "%d", params->w);
690     ret[0].sval = dupstr(buf);
691     ret[0].ival = 0;
692
693     ret[1].name = "Height";
694     ret[1].type = C_STRING;
695     sprintf(buf, "%d", params->h);
696     ret[1].sval = dupstr(buf);
697     ret[1].ival = 0;
698
699     ret[2].name = "Difficulty";
700     ret[2].type = C_CHOICES;
701     ret[2].sval = ":Easy:Medium:Hard";
702     ret[2].ival = params->difficulty;
703
704     ret[3].name = "Allow loops";
705     ret[3].type = C_BOOLEAN;
706     ret[3].sval = NULL;
707     ret[3].ival = params->allowloops;
708
709     ret[4].name = "Max. bridges per direction";
710     ret[4].type = C_CHOICES;
711     ret[4].sval = ":1:2:3:4"; /* keep up-to-date with MAX_BRIDGES */
712     ret[4].ival = params->maxb - 1;
713
714     ret[5].name = "%age of island squares";
715     ret[5].type = C_CHOICES;
716     ret[5].sval = ":5%:10%:15%:20%:25%:30%";
717     ret[5].ival = (params->islands / 5)-1;
718
719     ret[6].name = "Expansion factor (%age)";
720     ret[6].type = C_CHOICES;
721     ret[6].sval = ":0%:10%:20%:30%:40%:50%:60%:70%:80%:90%:100%";
722     ret[6].ival = params->expansion / 10;
723
724     ret[7].name = NULL;
725     ret[7].type = C_END;
726     ret[7].sval = NULL;
727     ret[7].ival = 0;
728
729     return ret;
730 }
731
732 static game_params *custom_params(config_item *cfg)
733 {
734     game_params *ret = snew(game_params);
735
736     ret->w          = atoi(cfg[0].sval);
737     ret->h          = atoi(cfg[1].sval);
738     ret->difficulty = cfg[2].ival;
739     ret->allowloops = cfg[3].ival;
740     ret->maxb       = cfg[4].ival + 1;
741     ret->islands    = (cfg[5].ival + 1) * 5;
742     ret->expansion  = cfg[6].ival * 10;
743
744     return ret;
745 }
746
747 static char *validate_params(game_params *params, int full)
748 {
749     if (params->w < 3 || params->h < 3)
750         return "Width and height must be at least 3";
751     if (params->maxb < 1 || params->maxb > MAX_BRIDGES)
752         return "Too many bridges.";
753     if (full) {
754         if (params->islands <= 0 || params->islands > 30)
755             return "%age of island squares must be between 1% and 30%";
756         if (params->expansion < 0 || params->expansion > 100)
757             return "Expansion factor must be between 0 and 100";
758     }
759     return NULL;
760 }
761
762 /* --- Game encoding and differences --- */
763
764 static char *encode_game(game_state *state)
765 {
766     char *ret, *p;
767     int wh = state->w*state->h, run, x, y;
768     struct island *is;
769
770     ret = snewn(wh + 1, char);
771     p = ret;
772     run = 0;
773     for (y = 0; y < state->h; y++) {
774         for (x = 0; x < state->w; x++) {
775             is = INDEX(state, gridi, x, y);
776             if (is) {
777                 if (run) {
778                     *p++ = ('a'-1) + run;
779                     run = 0;
780                 }
781                 if (is->count < 10)
782                     *p++ = '0' + is->count;
783                 else
784                     *p++ = 'A' + (is->count - 10);
785             } else {
786                 if (run == 26) {
787                     *p++ = ('a'-1) + run;
788                     run = 0;
789                 }
790                 run++;
791             }
792         }
793     }
794     if (run) {
795         *p++ = ('a'-1) + run;
796         run = 0;
797     }
798     *p = '\0';
799     assert(p - ret <= wh);
800
801     return ret;
802 }
803
804 static char *game_state_diff(game_state *src, game_state *dest)
805 {
806     int movesize = 256, movelen = 0;
807     char *move = snewn(movesize, char), buf[80];
808     int i, d, x, y, len;
809     grid_type gline, nline;
810     struct island *is_s, *is_d, *is_orth;
811
812 #define APPEND do {                                     \
813     if (movelen + len >= movesize) {                    \
814         movesize = movelen + len + 256;                 \
815         move = sresize(move, movesize, char);           \
816     }                                                   \
817     strcpy(move + movelen, buf);                        \
818     movelen += len;                                     \
819 } while(0)
820
821     move[movelen++] = 'S';
822     move[movelen] = '\0';
823
824     assert(src->n_islands == dest->n_islands);
825
826     for (i = 0; i < src->n_islands; i++) {
827         is_s = &src->islands[i];
828         is_d = &dest->islands[i];
829         assert(is_s->x == is_d->x);
830         assert(is_s->y == is_d->y);
831         assert(is_s->adj.npoints == is_d->adj.npoints); /* more paranoia */
832
833         for (d = 0; d < is_s->adj.npoints; d++) {
834             if (is_s->adj.points[d].dx == -1 ||
835                 is_s->adj.points[d].dy == -1) continue;
836
837             x = is_s->adj.points[d].x;
838             y = is_s->adj.points[d].y;
839             gline = is_s->adj.points[d].dx ? G_LINEH : G_LINEV;
840             nline = is_s->adj.points[d].dx ? G_NOLINEH : G_NOLINEV;
841             is_orth = INDEX(dest, gridi,
842                             ISLAND_ORTHX(is_d, d), ISLAND_ORTHY(is_d, d));
843
844             if (GRIDCOUNT(src, x, y, gline) != GRIDCOUNT(dest, x, y, gline)) {
845                 assert(is_orth);
846                 len = sprintf(buf, ";L%d,%d,%d,%d,%d",
847                               is_s->x, is_s->y, is_orth->x, is_orth->y,
848                               GRIDCOUNT(dest, x, y, gline));
849                 APPEND;
850             }
851             if ((GRID(src,x,y) & nline) != (GRID(dest, x, y) & nline)) {
852                 assert(is_orth);
853                 len = sprintf(buf, ";N%d,%d,%d,%d",
854                               is_s->x, is_s->y, is_orth->x, is_orth->y);
855                 APPEND;
856             }
857         }
858         if ((GRID(src, is_s->x, is_s->y) & G_MARK) !=
859             (GRID(dest, is_d->x, is_d->y) & G_MARK)) {
860             len = sprintf(buf, ";M%d,%d", is_s->x, is_s->y);
861             APPEND;
862         }
863     }
864     return move;
865 }
866
867 /* --- Game setup and solving utilities --- */
868
869 /* This function is optimised; a Quantify showed that lots of grid-generation time
870  * (>50%) was spent in here. Hence the IDX() stuff. */
871
872 static void map_update_possibles(game_state *state)
873 {
874     int x, y, s, e, bl, i, np, maxb, w = state->w, idx;
875     struct island *is_s = NULL, *is_f = NULL;
876
877     /* Run down vertical stripes [un]setting possv... */
878     for (x = 0; x < state->w; x++) {
879         idx = x;
880         s = e = -1;
881         bl = 0;
882         /* Unset possible flags until we find an island. */
883         for (y = 0; y < state->h; y++) {
884             is_s = IDX(state, gridi, idx);
885             if (is_s) {
886                 maxb = is_s->count;
887                 break;
888             }
889
890             IDX(state, possv, idx) = 0;
891             idx += w;
892         }
893         for (; y < state->h; y++) {
894             maxb = min(maxb, IDX(state, maxv, idx));
895             is_f = IDX(state, gridi, idx);
896             if (is_f) {
897                 assert(is_s);
898                 np = min(maxb, is_f->count);
899
900                 if (s != -1) {
901                     for (i = s; i <= e; i++) {
902                         INDEX(state, possv, x, i) = bl ? 0 : np;
903                     }
904                 }
905                 s = y+1;
906                 bl = 0;
907                 is_s = is_f;
908                 maxb = is_s->count;
909             } else {
910                 e = y;
911                 if (IDX(state,grid,idx) & (G_LINEH|G_NOLINEV)) bl = 1;
912             }
913             idx += w;
914         }
915         if (s != -1) {
916             for (i = s; i <= e; i++)
917                 INDEX(state, possv, x, i) = 0;
918         }
919     }
920
921     /* ...and now do horizontal stripes [un]setting possh. */
922     /* can we lose this clone'n'hack? */
923     for (y = 0; y < state->h; y++) {
924         idx = y*w;
925         s = e = -1;
926         bl = 0;
927         for (x = 0; x < state->w; x++) {
928             is_s = IDX(state, gridi, idx);
929             if (is_s) {
930                 maxb = is_s->count;
931                 break;
932             }
933
934             IDX(state, possh, idx) = 0;
935             idx += 1;
936         }
937         for (; x < state->w; x++) {
938             maxb = min(maxb, IDX(state, maxh, idx));
939             is_f = IDX(state, gridi, idx);
940             if (is_f) {
941                 assert(is_s);
942                 np = min(maxb, is_f->count);
943
944                 if (s != -1) {
945                     for (i = s; i <= e; i++) {
946                         INDEX(state, possh, i, y) = bl ? 0 : np;
947                     }
948                 }
949                 s = x+1;
950                 bl = 0;
951                 is_s = is_f;
952                 maxb = is_s->count;
953             } else {
954                 e = x;
955                 if (IDX(state,grid,idx) & (G_LINEV|G_NOLINEH)) bl = 1;
956             }
957             idx += 1;
958         }
959         if (s != -1) {
960             for (i = s; i <= e; i++)
961                 INDEX(state, possh, i, y) = 0;
962         }
963     }
964 }
965
966 static void map_count(game_state *state)
967 {
968     int i, n, ax, ay;
969     grid_type flag, grid;
970     struct island *is;
971
972     for (i = 0; i < state->n_islands; i++) {
973         is = &state->islands[i];
974         is->count = 0;
975         for (n = 0; n < is->adj.npoints; n++) {
976             ax = is->adj.points[n].x;
977             ay = is->adj.points[n].y;
978             flag = (ax == is->x) ? G_LINEV : G_LINEH;
979             grid = GRID(state,ax,ay);
980             if (grid & flag) {
981                 is->count += INDEX(state,lines,ax,ay);
982             }
983         }
984     }
985 }
986
987 static void map_find_orthogonal(game_state *state)
988 {
989     int i;
990
991     for (i = 0; i < state->n_islands; i++) {
992         island_find_orthogonal(&state->islands[i]);
993     }
994 }
995
996 static int grid_degree(game_state *state, int x, int y, int *nx_r, int *ny_r)
997 {
998     grid_type grid = SCRATCH(state, x, y), gline = grid & G_LINE;
999     struct island *is;
1000     int x1, y1, x2, y2, c = 0, i, nx, ny;
1001
1002     nx = ny = -1; /* placate optimiser */
1003     is = INDEX(state, gridi, x, y);
1004     if (is) {
1005         for (i = 0; i < is->adj.npoints; i++) {
1006             gline = is->adj.points[i].dx ? G_LINEH : G_LINEV;
1007             if (SCRATCH(state,
1008                         is->adj.points[i].x,
1009                         is->adj.points[i].y) & gline) {
1010                 nx = is->adj.points[i].x;
1011                 ny = is->adj.points[i].y;
1012                 c++;
1013             }
1014         }
1015     } else if (gline) {
1016         if (gline & G_LINEV) {
1017             x1 = x2 = x;
1018             y1 = y-1; y2 = y+1;
1019         } else {
1020             x1 = x-1; x2 = x+1;
1021             y1 = y2 = y;
1022         }
1023         /* Non-island squares with edges in should never be pointing off the
1024          * edge of the grid. */
1025         assert(INGRID(state, x1, y1));
1026         assert(INGRID(state, x2, y2));
1027         if (SCRATCH(state, x1, y1) & (gline | G_ISLAND)) {
1028             nx = x1; ny = y1; c++;
1029         }
1030         if (SCRATCH(state, x2, y2) & (gline | G_ISLAND)) {
1031             nx = x2; ny = y2; c++;
1032         }
1033     }
1034     if (c == 1) {
1035         assert(nx != -1 && ny != -1); /* paranoia */
1036         *nx_r = nx; *ny_r = ny;
1037     }
1038     return c;
1039 }
1040
1041 static int map_hasloops(game_state *state, int mark)
1042 {
1043     int x, y, ox, oy, nx = 0, ny = 0, loop = 0;
1044
1045     memcpy(state->scratch, state->grid, GRIDSZ(state));
1046
1047     /* This algorithm is actually broken; if there are two loops connected
1048      * by bridges this will also highlight bridges. The correct algorithm
1049      * uses a dsf and a two-pass edge-detection algorithm (see check_correct
1050      * in slant.c); this is BALGE for now, especially since disallow-loops
1051      * is not the default for this puzzle. If we want to fix this later then
1052      * copy the alg in slant.c to the empty statement in map_group. */
1053
1054     /* Remove all 1-degree edges. */
1055     for (y = 0; y < state->h; y++) {
1056         for (x = 0; x < state->w; x++) {
1057             ox = x; oy = y;
1058             while (grid_degree(state, ox, oy, &nx, &ny) == 1) {
1059                 /*debug(("hasloops: removing 1-degree at (%d,%d).\n", ox, oy));*/
1060                 SCRATCH(state, ox, oy) &= ~(G_LINE|G_ISLAND);
1061                 ox = nx; oy = ny;
1062             }
1063         }
1064     }
1065     /* Mark any remaining edges as G_WARN, if required. */
1066     for (x = 0; x < state->w; x++) {
1067         for (y = 0; y < state->h; y++) {
1068             if (GRID(state,x,y) & G_ISLAND) continue;
1069
1070             if (SCRATCH(state, x, y) & G_LINE) {
1071                 if (mark) {
1072                     /*debug(("hasloops: marking loop square at (%d,%d).\n",
1073                            x, y));*/
1074                     GRID(state,x,y) |= G_WARN;
1075                     loop = 1;
1076                 } else
1077                     return 1; /* short-cut as soon as we find one */
1078             } else {
1079                 if (mark)
1080                     GRID(state,x,y) &= ~G_WARN;
1081             }
1082         }
1083     }
1084     return loop;
1085 }
1086
1087 static void map_group(game_state *state)
1088 {
1089     int i, wh = state->w*state->h, d1, d2;
1090     int x, y, x2, y2;
1091     int *dsf = state->solver->dsf;
1092     struct island *is, *is_join;
1093
1094     /* Initialise dsf. */
1095     dsf_init(dsf, wh);
1096
1097     /* For each island, find connected islands right or down
1098      * and merge the dsf for the island squares as well as the
1099      * bridge squares. */
1100     for (x = 0; x < state->w; x++) {
1101         for (y = 0; y < state->h; y++) {
1102             GRID(state,x,y) &= ~(G_SWEEP|G_WARN); /* for group_full. */
1103
1104             is = INDEX(state, gridi, x, y);
1105             if (!is) continue;
1106             d1 = DINDEX(x,y);
1107             for (i = 0; i < is->adj.npoints; i++) {
1108                 /* only want right/down */
1109                 if (is->adj.points[i].dx == -1 ||
1110                     is->adj.points[i].dy == -1) continue;
1111
1112                 is_join = island_find_connection(is, i);
1113                 if (!is_join) continue;
1114
1115                 d2 = DINDEX(is_join->x, is_join->y);
1116                 if (dsf_canonify(dsf,d1) == dsf_canonify(dsf,d2)) {
1117                     ; /* we have a loop. See comment in map_hasloops. */
1118                     /* However, we still want to merge all squares joining
1119                      * this side-that-makes-a-loop. */
1120                 }
1121                 /* merge all squares between island 1 and island 2. */
1122                 for (x2 = x; x2 <= is_join->x; x2++) {
1123                     for (y2 = y; y2 <= is_join->y; y2++) {
1124                         d2 = DINDEX(x2,y2);
1125                         if (d1 != d2) dsf_merge(dsf,d1,d2);
1126                     }
1127                 }
1128             }
1129         }
1130     }
1131 }
1132
1133 static int map_group_check(game_state *state, int canon, int warn,
1134                            int *nislands_r)
1135 {
1136     int *dsf = state->solver->dsf, nislands = 0;
1137     int x, y, i, allfull = 1;
1138     struct island *is;
1139
1140     for (i = 0; i < state->n_islands; i++) {
1141         is = &state->islands[i];
1142         if (dsf_canonify(dsf, DINDEX(is->x,is->y)) != canon) continue;
1143
1144         GRID(state, is->x, is->y) |= G_SWEEP;
1145         nislands++;
1146         if (island_countbridges(is) != is->count)
1147             allfull = 0;
1148     }
1149     if (warn && allfull && nislands != state->n_islands) {
1150         /* we're full and this island group isn't the whole set.
1151          * Mark all squares with this dsf canon as ERR. */
1152         for (x = 0; x < state->w; x++) {
1153             for (y = 0; y < state->h; y++) {
1154                 if (dsf_canonify(dsf, DINDEX(x,y)) == canon) {
1155                     GRID(state,x,y) |= G_WARN;
1156                 }
1157             }
1158         }
1159
1160     }
1161     if (nislands_r) *nislands_r = nislands;
1162     return allfull;
1163 }
1164
1165 static int map_group_full(game_state *state, int *ngroups_r)
1166 {
1167     int *dsf = state->solver->dsf, ngroups = 0;
1168     int i, anyfull = 0;
1169     struct island *is;
1170
1171     /* NB this assumes map_group (or sth else) has cleared G_SWEEP. */
1172
1173     for (i = 0; i < state->n_islands; i++) {
1174         is = &state->islands[i];
1175         if (GRID(state,is->x,is->y) & G_SWEEP) continue;
1176
1177         ngroups++;
1178         if (map_group_check(state, dsf_canonify(dsf, DINDEX(is->x,is->y)),
1179                             1, NULL))
1180             anyfull = 1;
1181     }
1182
1183     *ngroups_r = ngroups;
1184     return anyfull;
1185 }
1186
1187 static int map_check(game_state *state)
1188 {
1189     int ngroups;
1190
1191     /* Check for loops, if necessary. */
1192     if (!state->allowloops) {
1193         if (map_hasloops(state, 1))
1194             return 0;
1195     }
1196
1197     /* Place islands into island groups and check for early
1198      * satisfied-groups. */
1199     map_group(state); /* clears WARN and SWEEP */
1200     if (map_group_full(state, &ngroups)) {
1201         if (ngroups == 1) return 1;
1202     }
1203     return 0;
1204 }
1205
1206 static void map_clear(game_state *state)
1207 {
1208     int x, y;
1209
1210     for (x = 0; x < state->w; x++) {
1211         for (y = 0; y < state->h; y++) {
1212             /* clear most flags; might want to be slightly more careful here. */
1213             GRID(state,x,y) &= G_ISLAND;
1214         }
1215     }
1216 }
1217
1218 static void solve_join(struct island *is, int direction, int n, int is_max)
1219 {
1220     struct island *is_orth;
1221     int d1, d2, *dsf = is->state->solver->dsf;
1222     game_state *state = is->state; /* for DINDEX */
1223
1224     is_orth = INDEX(is->state, gridi,
1225                     ISLAND_ORTHX(is, direction),
1226                     ISLAND_ORTHY(is, direction));
1227     assert(is_orth);
1228     /*debug(("...joining (%d,%d) to (%d,%d) with %d bridge(s).\n",
1229            is->x, is->y, is_orth->x, is_orth->y, n));*/
1230     island_join(is, is_orth, n, is_max);
1231
1232     if (n > 0 && !is_max) {
1233         d1 = DINDEX(is->x, is->y);
1234         d2 = DINDEX(is_orth->x, is_orth->y);
1235         if (dsf_canonify(dsf, d1) != dsf_canonify(dsf, d2))
1236             dsf_merge(dsf, d1, d2);
1237     }
1238 }
1239
1240 static int solve_fillone(struct island *is)
1241 {
1242     int i, nadded = 0;
1243
1244     debug(("solve_fillone for island (%d,%d).\n", is->x, is->y));
1245
1246     for (i = 0; i < is->adj.npoints; i++) {
1247         if (island_isadj(is, i)) {
1248             if (island_hasbridge(is, i)) {
1249                 /* already attached; do nothing. */;
1250             } else {
1251                 solve_join(is, i, 1, 0);
1252                 nadded++;
1253             }
1254         }
1255     }
1256     return nadded;
1257 }
1258
1259 static int solve_fill(struct island *is)
1260 {
1261     /* for each unmarked adjacent, make sure we convert every possible bridge
1262      * to a real one, and then work out the possibles afresh. */
1263     int i, nnew, ncurr, nadded = 0, missing;
1264
1265     debug(("solve_fill for island (%d,%d).\n", is->x, is->y));
1266
1267     missing = is->count - island_countbridges(is);
1268     if (missing < 0) return 0;
1269
1270     /* very like island_countspaces. */
1271     for (i = 0; i < is->adj.npoints; i++) {
1272         nnew = island_adjspace(is, 1, missing, i);
1273         if (nnew) {
1274             ncurr = GRIDCOUNT(is->state,
1275                               is->adj.points[i].x, is->adj.points[i].y,
1276                               is->adj.points[i].dx ? G_LINEH : G_LINEV);
1277
1278             solve_join(is, i, nnew + ncurr, 0);
1279             nadded += nnew;
1280         }
1281     }
1282     return nadded;
1283 }
1284
1285 static int solve_island_stage1(struct island *is, int *didsth_r)
1286 {
1287     int bridges = island_countbridges(is);
1288     int nspaces = island_countspaces(is, 1);
1289     int nadj = island_countadj(is);
1290     int didsth = 0;
1291
1292     assert(didsth_r);
1293
1294     /*debug(("island at (%d,%d) filled %d/%d (%d spc) nadj %d\n",
1295            is->x, is->y, bridges, is->count, nspaces, nadj));*/
1296     if (bridges > is->count) {
1297         /* We only ever add bridges when we're sure they fit, or that's
1298          * the only place they can go. If we've added bridges such that
1299          * another island has become wrong, the puzzle must not have had
1300          * a solution. */
1301         debug(("...island at (%d,%d) is overpopulated!\n", is->x, is->y));
1302         return 0;
1303     } else if (bridges == is->count) {
1304         /* This island is full. Make sure it's marked (and update
1305          * possibles if we did). */
1306         if (!(GRID(is->state, is->x, is->y) & G_MARK)) {
1307             debug(("...marking island (%d,%d) as full.\n", is->x, is->y));
1308             island_togglemark(is);
1309             didsth = 1;
1310         }
1311     } else if (GRID(is->state, is->x, is->y) & G_MARK) {
1312         debug(("...island (%d,%d) is marked but unfinished!\n",
1313                is->x, is->y));
1314         return 0; /* island has been marked unfinished; no solution from here. */
1315     } else {
1316         /* This is the interesting bit; we try and fill in more information
1317          * about this island. */
1318         if (is->count == bridges + nspaces) {
1319             if (solve_fill(is) > 0) didsth = 1;
1320         } else if (is->count > ((nadj-1) * is->state->maxb)) {
1321             /* must have at least one bridge in each possible direction. */
1322             if (solve_fillone(is) > 0) didsth = 1;
1323         }
1324     }
1325     if (didsth) {
1326         map_update_possibles(is->state);
1327         *didsth_r = 1;
1328     }
1329     return 1;
1330 }
1331
1332 /* returns non-zero if a new line here would cause a loop. */
1333 static int solve_island_checkloop(struct island *is, int direction)
1334 {
1335     struct island *is_orth;
1336     int *dsf = is->state->solver->dsf, d1, d2;
1337     game_state *state = is->state;
1338
1339     if (is->state->allowloops) return 0; /* don't care anyway */
1340     if (island_hasbridge(is, direction)) return 0; /* already has a bridge */
1341     if (island_isadj(is, direction) == 0) return 0; /* no adj island */
1342
1343     is_orth = INDEX(is->state, gridi,
1344                     ISLAND_ORTHX(is,direction),
1345                     ISLAND_ORTHY(is,direction));
1346     if (!is_orth) return 0;
1347
1348     d1 = DINDEX(is->x, is->y);
1349     d2 = DINDEX(is_orth->x, is_orth->y);
1350     if (dsf_canonify(dsf, d1) == dsf_canonify(dsf, d2)) {
1351         /* two islands are connected already; don't join them. */
1352         return 1;
1353     }
1354     return 0;
1355 }
1356
1357 static int solve_island_stage2(struct island *is, int *didsth_r)
1358 {
1359     int added = 0, removed = 0, navail = 0, nadj, i;
1360
1361     assert(didsth_r);
1362
1363     for (i = 0; i < is->adj.npoints; i++) {
1364         if (solve_island_checkloop(is, i)) {
1365             debug(("removing possible loop at (%d,%d) direction %d.\n",
1366                    is->x, is->y, i));
1367             solve_join(is, i, -1, 0);
1368             map_update_possibles(is->state);
1369             removed = 1;
1370         } else {
1371             navail += island_isadj(is, i);
1372             /*debug(("stage2: navail for (%d,%d) direction (%d,%d) is %d.\n",
1373                    is->x, is->y,
1374                    is->adj.points[i].dx, is->adj.points[i].dy,
1375                    island_isadj(is, i)));*/
1376         }
1377     }
1378
1379     /*debug(("island at (%d,%d) navail %d: checking...\n", is->x, is->y, navail));*/
1380
1381     for (i = 0; i < is->adj.npoints; i++) {
1382         if (!island_hasbridge(is, i)) {
1383             nadj = island_isadj(is, i);
1384             if (nadj > 0 && (navail - nadj) < is->count) {
1385                 /* we couldn't now complete the island without at
1386                  * least one bridge here; put it in. */
1387                 /*debug(("nadj %d, navail %d, is->count %d.\n",
1388                        nadj, navail, is->count));*/
1389                 debug(("island at (%d,%d) direction (%d,%d) must have 1 bridge\n",
1390                        is->x, is->y,
1391                        is->adj.points[i].dx, is->adj.points[i].dy));
1392                 solve_join(is, i, 1, 0);
1393                 added = 1;
1394                 /*debug_state(is->state);
1395                 debug_possibles(is->state);*/
1396             }
1397         }
1398     }
1399     if (added) map_update_possibles(is->state);
1400     if (added || removed) *didsth_r = 1;
1401     return 1;
1402 }
1403
1404 static int solve_island_subgroup(struct island *is, int direction, int n)
1405 {
1406     struct island *is_join;
1407     int nislands, *dsf = is->state->solver->dsf;
1408     game_state *state = is->state;
1409
1410     debug(("..checking subgroups.\n"));
1411
1412     /* if is isn't full, return 0. */
1413     if (n < is->count) {
1414         debug(("...orig island (%d,%d) not full.\n", is->x, is->y));
1415         return 0;
1416     }
1417
1418     if (direction >= 0) {
1419         is_join = INDEX(state, gridi,
1420                         ISLAND_ORTHX(is, direction),
1421                         ISLAND_ORTHY(is, direction));
1422         assert(is_join);
1423
1424         /* if is_join isn't full, return 0. */
1425         if (island_countbridges(is_join) < is_join->count) {
1426             debug(("...dest island (%d,%d) not full.\n",
1427                    is_join->x, is_join->y));
1428             return 0;
1429         }
1430     }
1431
1432     /* Check group membership for is->dsf; if it's full return 1. */
1433     if (map_group_check(state, dsf_canonify(dsf, DINDEX(is->x,is->y)),
1434                         0, &nislands)) {
1435         if (nislands < state->n_islands) {
1436             /* we have a full subgroup that isn't the whole set.
1437              * This isn't allowed. */
1438             debug(("island at (%d,%d) makes full subgroup, disallowing.\n",
1439                    is->x, is->y, n));
1440             return 1;
1441         } else {
1442             debug(("...has finished puzzle.\n"));
1443         }
1444     }
1445     return 0;
1446 }
1447
1448 static int solve_island_impossible(game_state *state)
1449 {
1450     struct island *is;
1451     int i;
1452
1453     /* If any islands are impossible, return 1. */
1454     for (i = 0; i < state->n_islands; i++) {
1455         is = &state->islands[i];
1456         if (island_impossible(is, 0)) {
1457             debug(("island at (%d,%d) has become impossible, disallowing.\n",
1458                    is->x, is->y));
1459             return 1;
1460         }
1461     }
1462     return 0;
1463 }
1464
1465 /* Bear in mind that this function is really rather inefficient. */
1466 static int solve_island_stage3(struct island *is, int *didsth_r)
1467 {
1468     int i, n, x, y, missing, spc, curr, maxb, didsth = 0;
1469     int wh = is->state->w * is->state->h;
1470     struct solver_state *ss = is->state->solver;
1471
1472     assert(didsth_r);
1473
1474     missing = is->count - island_countbridges(is);
1475     if (missing <= 0) return 1;
1476
1477     for (i = 0; i < is->adj.npoints; i++) {
1478         /* We only do right- or down-pointing bridges. */
1479         if (is->adj.points[i].dx == -1 ||
1480             is->adj.points[i].dy == -1) continue;
1481
1482         x = is->adj.points[i].x;
1483         y = is->adj.points[i].y;
1484         spc = island_adjspace(is, 1, missing, i);
1485         if (spc == 0) continue;
1486
1487         curr = GRIDCOUNT(is->state, x, y,
1488                          is->adj.points[i].dx ? G_LINEH : G_LINEV);
1489         debug(("island at (%d,%d) s3, trying %d - %d bridges.\n",
1490                is->x, is->y, curr+1, curr+spc));
1491
1492         /* Now we know that this island could have more bridges,
1493          * to bring the total from curr+1 to curr+spc. */
1494         maxb = -1;
1495         /* We have to squirrel the dsf away and restore it afterwards;
1496          * it is additive only, and can't be removed from. */
1497         memcpy(ss->tmpdsf, ss->dsf, wh*sizeof(int));
1498         for (n = curr+1; n <= curr+spc; n++) {
1499             solve_join(is, i, n, 0);
1500             map_update_possibles(is->state);
1501
1502             if (solve_island_subgroup(is, i, n) ||
1503                 solve_island_impossible(is->state)) {
1504                 maxb = n-1;
1505                 debug(("island at (%d,%d) d(%d,%d) new max of %d bridges:\n",
1506                        is->x, is->y,
1507                        is->adj.points[i].dx, is->adj.points[i].dy,
1508                        maxb));
1509                 break;
1510             }
1511         }
1512         solve_join(is, i, curr, 0); /* put back to before. */
1513         memcpy(ss->dsf, ss->tmpdsf, wh*sizeof(int));
1514
1515         if (maxb != -1) {
1516             /*debug_state(is->state);*/
1517             if (maxb == 0) {
1518                 debug(("...adding NOLINE.\n"));
1519                 solve_join(is, i, -1, 0); /* we can't have any bridges here. */
1520             } else {
1521                 debug(("...setting maximum\n"));
1522                 solve_join(is, i, maxb, 1);
1523             }
1524             didsth = 1;
1525         }
1526         map_update_possibles(is->state);
1527     }
1528
1529     for (i = 0; i < is->adj.npoints; i++) {
1530         /*
1531          * Now check to see if any currently empty direction must have
1532          * at least one bridge in order to avoid forming an isolated
1533          * subgraph. This differs from the check above in that it
1534          * considers multiple target islands. For example:
1535          *
1536          *   2   2    4
1537          *                                  1     3     2
1538          *       3
1539          *                                        4
1540          *
1541          * The example on the left can be handled by the above loop:
1542          * it will observe that connecting the central 2 twice to the
1543          * left would form an isolated subgraph, and hence it will
1544          * restrict that 2 to at most one bridge in that direction.
1545          * But the example on the right won't be handled by that loop,
1546          * because the deduction requires us to imagine connecting the
1547          * 3 to _both_ the 1 and 2 at once to form an isolated
1548          * subgraph.
1549          *
1550          * This pass is necessary _as well_ as the above one, because
1551          * neither can do the other's job. In the left one,
1552          * restricting the direction which _would_ cause trouble can
1553          * be done even if it's not yet clear which of the remaining
1554          * directions has to have a compensatory bridge; whereas the
1555          * pass below that can handle the right-hand example does need
1556          * to know what direction to point the necessary bridge in.
1557          *
1558          * Neither pass can handle the most general case, in which we
1559          * observe that an arbitrary subset of an island's neighbours
1560          * would form an isolated subgraph with it if it connected
1561          * maximally to them, and hence that at least one bridge must
1562          * point to some neighbour outside that subset but we don't
1563          * know which neighbour. To handle that, we'd have to have a
1564          * richer data format for the solver, which could cope with
1565          * recording the idea that at least one of two edges must have
1566          * a bridge.
1567          */
1568         int got = 0;
1569         int before[4];
1570         int j;
1571
1572         spc = island_adjspace(is, 1, missing, i);
1573         if (spc == 0) continue;
1574
1575         for (j = 0; j < is->adj.npoints; j++)
1576             before[j] = GRIDCOUNT(is->state,
1577                                   is->adj.points[j].x,
1578                                   is->adj.points[j].y,
1579                                   is->adj.points[j].dx ? G_LINEH : G_LINEV);
1580         if (before[i] != 0) continue;  /* this idea is pointless otherwise */
1581
1582         memcpy(ss->tmpdsf, ss->dsf, wh*sizeof(int));
1583
1584         for (j = 0; j < is->adj.npoints; j++) {
1585             spc = island_adjspace(is, 1, missing, j);
1586             if (spc == 0) continue;
1587             if (j == i) continue;
1588             solve_join(is, j, before[j] + spc, 0);
1589         }
1590         map_update_possibles(is->state);
1591
1592         if (solve_island_subgroup(is, -1, n))
1593             got = 1;
1594
1595         for (j = 0; j < is->adj.npoints; j++)
1596             solve_join(is, j, before[j], 0);
1597         memcpy(ss->dsf, ss->tmpdsf, wh*sizeof(int));
1598
1599         if (got) {
1600             debug(("island at (%d,%d) must connect in direction (%d,%d) to"
1601                    " avoid full subgroup.\n",
1602                    is->x, is->y, is->adj.points[i].dx, is->adj.points[i].dy));
1603             solve_join(is, i, 1, 0);
1604             didsth = 1;
1605         }
1606
1607         map_update_possibles(is->state);
1608     }
1609
1610     if (didsth) *didsth_r = didsth;
1611     return 1;
1612 }
1613
1614 #define CONTINUE_IF_FULL do {                           \
1615 if (GRID(state, is->x, is->y) & G_MARK) {            \
1616     /* island full, don't try fixing it */           \
1617     continue;                                        \
1618 } } while(0)
1619
1620 static int solve_sub(game_state *state, int difficulty, int depth)
1621 {
1622     struct island *is;
1623     int i, didsth;
1624
1625     while (1) {
1626         didsth = 0;
1627
1628         /* First island iteration: things we can work out by looking at
1629          * properties of the island as a whole. */
1630         for (i = 0; i < state->n_islands; i++) {
1631             is = &state->islands[i];
1632             if (!solve_island_stage1(is, &didsth)) return 0;
1633         }
1634         if (didsth) continue;
1635         else if (difficulty < 1) break;
1636
1637         /* Second island iteration: thing we can work out by looking at
1638          * properties of individual island connections. */
1639         for (i = 0; i < state->n_islands; i++) {
1640             is = &state->islands[i];
1641             CONTINUE_IF_FULL;
1642             if (!solve_island_stage2(is, &didsth)) return 0;
1643         }
1644         if (didsth) continue;
1645         else if (difficulty < 2) break;
1646
1647         /* Third island iteration: things we can only work out by looking
1648          * at groups of islands. */
1649         for (i = 0; i < state->n_islands; i++) {
1650             is = &state->islands[i];
1651             if (!solve_island_stage3(is, &didsth)) return 0;
1652         }
1653         if (didsth) continue;
1654         else if (difficulty < 3) break;
1655
1656         /* If we can be bothered, write a recursive solver to finish here. */
1657         break;
1658     }
1659     if (map_check(state)) return 1; /* solved it */
1660     return 0;
1661 }
1662
1663 static void solve_for_hint(game_state *state)
1664 {
1665     map_group(state);
1666     solve_sub(state, 10, 0);
1667 }
1668
1669 static int solve_from_scratch(game_state *state, int difficulty)
1670 {
1671     map_clear(state);
1672     map_group(state);
1673     map_update_possibles(state);
1674     return solve_sub(state, difficulty, 0);
1675 }
1676
1677 /* --- New game functions --- */
1678
1679 static game_state *new_state(game_params *params)
1680 {
1681     game_state *ret = snew(game_state);
1682     int wh = params->w * params->h, i;
1683
1684     ret->w = params->w;
1685     ret->h = params->h;
1686     ret->allowloops = params->allowloops;
1687     ret->maxb = params->maxb;
1688     ret->params = *params;
1689
1690     ret->grid = snewn(wh, grid_type);
1691     memset(ret->grid, 0, GRIDSZ(ret));
1692     ret->scratch = snewn(wh, grid_type);
1693     memset(ret->scratch, 0, GRIDSZ(ret));
1694
1695     ret->wha = snewn(wh*N_WH_ARRAYS, char);
1696     memset(ret->wha, 0, wh*N_WH_ARRAYS*sizeof(char));
1697
1698     ret->possv = ret->wha;
1699     ret->possh = ret->wha + wh;
1700     ret->lines = ret->wha + wh*2;
1701     ret->maxv = ret->wha + wh*3;
1702     ret->maxh = ret->wha + wh*4;
1703
1704     memset(ret->maxv, ret->maxb, wh*sizeof(char));
1705     memset(ret->maxh, ret->maxb, wh*sizeof(char));
1706
1707     ret->islands = NULL;
1708     ret->n_islands = 0;
1709     ret->n_islands_alloc = 0;
1710
1711     ret->gridi = snewn(wh, struct island *);
1712     for (i = 0; i < wh; i++) ret->gridi[i] = NULL;
1713
1714     ret->solved = ret->completed = 0;
1715
1716     ret->solver = snew(struct solver_state);
1717     ret->solver->dsf = snew_dsf(wh);
1718     ret->solver->tmpdsf = snewn(wh, int);
1719
1720     ret->solver->refcount = 1;
1721
1722     return ret;
1723 }
1724
1725 static game_state *dup_game(game_state *state)
1726 {
1727     game_state *ret = snew(game_state);
1728     int wh = state->w*state->h;
1729
1730     ret->w = state->w;
1731     ret->h = state->h;
1732     ret->allowloops = state->allowloops;
1733     ret->maxb = state->maxb;
1734     ret->params = state->params;
1735
1736     ret->grid = snewn(wh, grid_type);
1737     memcpy(ret->grid, state->grid, GRIDSZ(ret));
1738     ret->scratch = snewn(wh, grid_type);
1739     memcpy(ret->scratch, state->scratch, GRIDSZ(ret));
1740
1741     ret->wha = snewn(wh*N_WH_ARRAYS, char);
1742     memcpy(ret->wha, state->wha, wh*N_WH_ARRAYS*sizeof(char));
1743
1744     ret->possv = ret->wha;
1745     ret->possh = ret->wha + wh;
1746     ret->lines = ret->wha + wh*2;
1747     ret->maxv = ret->wha + wh*3;
1748     ret->maxh = ret->wha + wh*4;
1749
1750     ret->islands = snewn(state->n_islands, struct island);
1751     memcpy(ret->islands, state->islands, state->n_islands * sizeof(struct island));
1752     ret->n_islands = ret->n_islands_alloc = state->n_islands;
1753
1754     ret->gridi = snewn(wh, struct island *);
1755     fixup_islands_for_realloc(ret);
1756
1757     ret->solved = state->solved;
1758     ret->completed = state->completed;
1759
1760     ret->solver = state->solver;
1761     ret->solver->refcount++;
1762
1763     return ret;
1764 }
1765
1766 static void free_game(game_state *state)
1767 {
1768     if (--state->solver->refcount <= 0) {
1769         sfree(state->solver->dsf);
1770         sfree(state->solver->tmpdsf);
1771         sfree(state->solver);
1772     }
1773
1774     sfree(state->islands);
1775     sfree(state->gridi);
1776
1777     sfree(state->wha);
1778
1779     sfree(state->scratch);
1780     sfree(state->grid);
1781     sfree(state);
1782 }
1783
1784 #define MAX_NEWISLAND_TRIES     50
1785 #define MIN_SENSIBLE_ISLANDS    3
1786
1787 #define ORDER(a,b) do { if (a < b) { int tmp=a; int a=b; int b=tmp; } } while(0)
1788
1789 static char *new_game_desc(game_params *params, random_state *rs,
1790                            char **aux, int interactive)
1791 {
1792     game_state *tobuild  = NULL;
1793     int i, j, wh = params->w * params->h, x, y, dx, dy;
1794     int minx, miny, maxx, maxy, joinx, joiny, newx, newy, diffx, diffy;
1795     int ni_req = max((params->islands * wh) / 100, MIN_SENSIBLE_ISLANDS), ni_curr, ni_bad;
1796     struct island *is, *is2;
1797     char *ret;
1798     unsigned int echeck;
1799
1800     /* pick a first island position randomly. */
1801 generate:
1802     if (tobuild) free_game(tobuild);
1803     tobuild = new_state(params);
1804
1805     x = random_upto(rs, params->w);
1806     y = random_upto(rs, params->h);
1807     island_add(tobuild, x, y, 0);
1808     ni_curr = 1;
1809     ni_bad = 0;
1810     debug(("Created initial island at (%d,%d).\n", x, y));
1811
1812     while (ni_curr < ni_req) {
1813         /* Pick a random island to try and extend from. */
1814         i = random_upto(rs, tobuild->n_islands);
1815         is = &tobuild->islands[i];
1816
1817         /* Pick a random direction to extend in. */
1818         j = random_upto(rs, is->adj.npoints);
1819         dx = is->adj.points[j].x - is->x;
1820         dy = is->adj.points[j].y - is->y;
1821
1822         /* Find out limits of where we could put a new island. */
1823         joinx = joiny = -1;
1824         minx = is->x + 2*dx; miny = is->y + 2*dy; /* closest is 2 units away. */
1825         x = is->x+dx; y = is->y+dy;
1826         if (GRID(tobuild,x,y) & (G_LINEV|G_LINEH)) {
1827             /* already a line next to the island, continue. */
1828             goto bad;
1829         }
1830         while (1) {
1831             if (x < 0 || x >= params->w || y < 0 || y >= params->h) {
1832                 /* got past the edge; put a possible at the island
1833                  * and exit. */
1834                 maxx = x-dx; maxy = y-dy;
1835                 goto foundmax;
1836             }
1837             if (GRID(tobuild,x,y) & G_ISLAND) {
1838                 /* could join up to an existing island... */
1839                 joinx = x; joiny = y;
1840                 /* ... or make a new one 2 spaces away. */
1841                 maxx = x - 2*dx; maxy = y - 2*dy;
1842                 goto foundmax;
1843             } else if (GRID(tobuild,x,y) & (G_LINEV|G_LINEH)) {
1844                 /* could make a new one 1 space away from the line. */
1845                 maxx = x - dx; maxy = y - dy;
1846                 goto foundmax;
1847             }
1848             x += dx; y += dy;
1849         }
1850
1851 foundmax:
1852         debug(("Island at (%d,%d) with d(%d,%d) has new positions "
1853                "(%d,%d) -> (%d,%d), join (%d,%d).\n",
1854                is->x, is->y, dx, dy, minx, miny, maxx, maxy, joinx, joiny));
1855         /* Now we know where we could either put a new island
1856          * (between min and max), or (if loops are allowed) could join on
1857          * to an existing island (at join). */
1858         if (params->allowloops && joinx != -1 && joiny != -1) {
1859             if (random_upto(rs, 100) < (unsigned long)params->expansion) {
1860                 is2 = INDEX(tobuild, gridi, joinx, joiny);
1861                 debug(("Joining island at (%d,%d) to (%d,%d).\n",
1862                        is->x, is->y, is2->x, is2->y));
1863                 goto join;
1864             }
1865         }
1866         diffx = (maxx - minx) * dx;
1867         diffy = (maxy - miny) * dy;
1868         if (diffx < 0 || diffy < 0)  goto bad;
1869         if (random_upto(rs,100) < (unsigned long)params->expansion) {
1870             newx = maxx; newy = maxy;
1871             debug(("Creating new island at (%d,%d) (expanded).\n", newx, newy));
1872         } else {
1873             newx = minx + random_upto(rs,diffx+1)*dx;
1874             newy = miny + random_upto(rs,diffy+1)*dy;
1875             debug(("Creating new island at (%d,%d).\n", newx, newy));
1876         }
1877         /* check we're not next to island in the other orthogonal direction. */
1878         if ((INGRID(tobuild,newx+dy,newy+dx) && (GRID(tobuild,newx+dy,newy+dx) & G_ISLAND)) ||
1879             (INGRID(tobuild,newx-dy,newy-dx) && (GRID(tobuild,newx-dy,newy-dx) & G_ISLAND))) {
1880             debug(("New location is adjacent to island, skipping.\n"));
1881             goto bad;
1882         }
1883         is2 = island_add(tobuild, newx, newy, 0);
1884         /* Must get is again at this point; the array might have
1885          * been realloced by island_add... */
1886         is = &tobuild->islands[i]; /* ...but order will not change. */
1887
1888         ni_curr++; ni_bad = 0;
1889 join:
1890         island_join(is, is2, random_upto(rs, tobuild->maxb)+1, 0);
1891         debug_state(tobuild);
1892         continue;
1893
1894 bad:
1895         ni_bad++;
1896         if (ni_bad > MAX_NEWISLAND_TRIES) {
1897             debug(("Unable to create any new islands after %d tries; "
1898                    "created %d [%d%%] (instead of %d [%d%%] requested).\n",
1899                    MAX_NEWISLAND_TRIES,
1900                    ni_curr, ni_curr * 100 / wh,
1901                    ni_req, ni_req * 100 / wh));
1902             goto generated;
1903         }
1904     }
1905
1906 generated:
1907     if (ni_curr == 1) {
1908         debug(("Only generated one island (!), retrying.\n"));
1909         goto generate;
1910     }
1911     /* Check we have at least one island on each extremity of the grid. */
1912     echeck = 0;
1913     for (x = 0; x < params->w; x++) {
1914         if (INDEX(tobuild, gridi, x, 0))           echeck |= 1;
1915         if (INDEX(tobuild, gridi, x, params->h-1)) echeck |= 2;
1916     }
1917     for (y = 0; y < params->h; y++) {
1918         if (INDEX(tobuild, gridi, 0,           y)) echeck |= 4;
1919         if (INDEX(tobuild, gridi, params->w-1, y)) echeck |= 8;
1920     }
1921     if (echeck != 15) {
1922         debug(("Generated grid doesn't fill to sides, retrying.\n"));
1923         goto generate;
1924     }
1925
1926     map_count(tobuild);
1927     map_find_orthogonal(tobuild);
1928
1929     if (params->difficulty > 0) {
1930         if ((ni_curr > MIN_SENSIBLE_ISLANDS) &&
1931             (solve_from_scratch(tobuild, params->difficulty-1) > 0)) {
1932             debug(("Grid is solvable at difficulty %d (too easy); retrying.\n",
1933                    params->difficulty-1));
1934             goto generate;
1935         }
1936     }
1937
1938     if (solve_from_scratch(tobuild, params->difficulty) == 0) {
1939         debug(("Grid not solvable at difficulty %d, (too hard); retrying.\n",
1940                params->difficulty));
1941         goto generate;
1942     }
1943
1944     /* ... tobuild is now solved. We rely on this making the diff for aux. */
1945     debug_state(tobuild);
1946     ret = encode_game(tobuild);
1947     {
1948         game_state *clean = dup_game(tobuild);
1949         map_clear(clean);
1950         map_update_possibles(clean);
1951         *aux = game_state_diff(clean, tobuild);
1952         free_game(clean);
1953     }
1954     free_game(tobuild);
1955
1956     return ret;
1957 }
1958
1959 static char *validate_desc(game_params *params, char *desc)
1960 {
1961     int i, wh = params->w * params->h;
1962
1963     for (i = 0; i < wh; i++) {
1964         if (*desc >= '1' && *desc <= '9')
1965             /* OK */;
1966         else if (*desc >= 'a' && *desc <= 'z')
1967             i += *desc - 'a'; /* plus the i++ */
1968         else if (*desc >= 'A' && *desc <= 'G')
1969             /* OK */;
1970         else if (*desc == 'V' || *desc == 'W' ||
1971                  *desc == 'X' || *desc == 'Y' ||
1972                  *desc == 'H' || *desc == 'I' ||
1973                  *desc == 'J' || *desc == 'K')
1974             /* OK */;
1975         else if (!*desc)
1976             return "Game description shorter than expected";
1977         else
1978             return "Game description containers unexpected character";
1979         desc++;
1980     }
1981     if (*desc || i > wh)
1982         return "Game description longer than expected";
1983
1984     return NULL;
1985 }
1986
1987 static game_state *new_game_sub(game_params *params, char *desc)
1988 {
1989     game_state *state = new_state(params);
1990     int x, y, run = 0;
1991
1992     debug(("new_game[_sub]: desc = '%s'.\n", desc));
1993
1994     for (y = 0; y < params->h; y++) {
1995         for (x = 0; x < params->w; x++) {
1996             char c = '\0';
1997
1998             if (run == 0) {
1999                 c = *desc++;
2000                 assert(c != 'S');
2001                 if (c >= 'a' && c <= 'z')
2002                     run = c - 'a' + 1;
2003             }
2004
2005             if (run > 0) {
2006                 c = 'S';
2007                 run--;
2008             }
2009
2010             switch (c) {
2011             case '1': case '2': case '3': case '4':
2012             case '5': case '6': case '7': case '8': case '9':
2013                 island_add(state, x, y, (c - '0'));
2014                 break;
2015
2016             case 'A': case 'B': case 'C': case 'D':
2017             case 'E': case 'F': case 'G':
2018                 island_add(state, x, y, (c - 'A') + 10);
2019                 break;
2020
2021             case 'S':
2022                 /* empty square */
2023                 break;
2024
2025             default:
2026                 assert(!"Malformed desc.");
2027                 break;
2028             }
2029         }
2030     }
2031     if (*desc) assert(!"Over-long desc.");
2032
2033     map_find_orthogonal(state);
2034     map_update_possibles(state);
2035
2036     return state;
2037 }
2038
2039 static game_state *new_game(midend *me, game_params *params, char *desc)
2040 {
2041     return new_game_sub(params, desc);
2042 }
2043
2044 struct game_ui {
2045     int dragx_src, dragy_src;   /* source; -1 means no drag */
2046     int dragx_dst, dragy_dst;   /* src's closest orth island. */
2047     grid_type todraw;
2048     int dragging, drag_is_noline, nlines;
2049
2050     int cur_x, cur_y, cur_visible;      /* cursor position */
2051     int show_hints;
2052 };
2053
2054 static char *ui_cancel_drag(game_ui *ui)
2055 {
2056     ui->dragx_src = ui->dragy_src = -1;
2057     ui->dragx_dst = ui->dragy_dst = -1;
2058     ui->dragging = 0;
2059     return "";
2060 }
2061
2062 static game_ui *new_ui(game_state *state)
2063 {
2064     game_ui *ui = snew(game_ui);
2065     ui_cancel_drag(ui);
2066     ui->cur_x = state->islands[0].x;
2067     ui->cur_y = state->islands[0].y;
2068     ui->cur_visible = 0;
2069     ui->show_hints = 0;
2070     return ui;
2071 }
2072
2073 static void free_ui(game_ui *ui)
2074 {
2075     sfree(ui);
2076 }
2077
2078 static char *encode_ui(game_ui *ui)
2079 {
2080     return NULL;
2081 }
2082
2083 static void decode_ui(game_ui *ui, char *encoding)
2084 {
2085 }
2086
2087 static void game_changed_state(game_ui *ui, game_state *oldstate,
2088                                game_state *newstate)
2089 {
2090 }
2091
2092 struct game_drawstate {
2093     int tilesize;
2094     int w, h;
2095     grid_type *grid;
2096     int *lv, *lh;
2097     int started, dragging;
2098     int show_hints;
2099 };
2100
2101 static char *update_drag_dst(game_state *state, game_ui *ui, game_drawstate *ds,
2102                             int nx, int ny)
2103 {
2104     int ox, oy, dx, dy, i, currl, maxb;
2105     struct island *is;
2106     grid_type gtype, ntype, mtype, curr;
2107
2108     if (ui->dragx_src == -1 || ui->dragy_src == -1) return NULL;
2109
2110     ui->dragx_dst = -1;
2111     ui->dragy_dst = -1;
2112
2113     /* work out which of the four directions we're closest to... */
2114     ox = COORD(ui->dragx_src) + TILE_SIZE/2;
2115     oy = COORD(ui->dragy_src) + TILE_SIZE/2;
2116
2117     if (abs(nx-ox) < abs(ny-oy)) {
2118         dx = 0;
2119         dy = (ny-oy) < 0 ? -1 : 1;
2120         gtype = G_LINEV; ntype = G_NOLINEV; mtype = G_MARKV;
2121         maxb = INDEX(state, maxv, ui->dragx_src+dx, ui->dragy_src+dy);
2122     } else {
2123         dy = 0;
2124         dx = (nx-ox) < 0 ? -1 : 1;
2125         gtype = G_LINEH; ntype = G_NOLINEH; mtype = G_MARKH;
2126         maxb = INDEX(state, maxh, ui->dragx_src+dx, ui->dragy_src+dy);
2127     }
2128     if (ui->drag_is_noline) {
2129         ui->todraw = ntype;
2130     } else {
2131         curr = GRID(state, ui->dragx_src+dx, ui->dragy_src+dy);
2132         currl = INDEX(state, lines, ui->dragx_src+dx, ui->dragy_src+dy);
2133
2134         if (curr & gtype) {
2135             if (currl == maxb) {
2136                 ui->todraw = 0;
2137                 ui->nlines = 0;
2138             } else {
2139                 ui->todraw = gtype;
2140                 ui->nlines = currl + 1;
2141             }
2142         } else {
2143             ui->todraw = gtype;
2144             ui->nlines = 1;
2145         }
2146     }
2147
2148     /* ... and see if there's an island off in that direction. */
2149     is = INDEX(state, gridi, ui->dragx_src, ui->dragy_src);
2150     for (i = 0; i < is->adj.npoints; i++) {
2151         if (is->adj.points[i].off == 0) continue;
2152         curr = GRID(state, is->x+dx, is->y+dy);
2153         if (curr & mtype) continue; /* don't allow changes to marked lines. */
2154         if (ui->drag_is_noline) {
2155             if (curr & gtype) continue; /* no no-line where already a line */
2156         } else {
2157             if (POSSIBLES(state, dx, is->x+dx, is->y+dy) == 0) continue; /* no line if !possible. */
2158             if (curr & ntype) continue; /* can't have a bridge where there's a no-line. */
2159         }
2160
2161         if (is->adj.points[i].dx == dx &&
2162             is->adj.points[i].dy == dy) {
2163             ui->dragx_dst = ISLAND_ORTHX(is,i);
2164             ui->dragy_dst = ISLAND_ORTHY(is,i);
2165         }
2166     }
2167     /*debug(("update_drag src (%d,%d) d(%d,%d) dst (%d,%d)\n",
2168            ui->dragx_src, ui->dragy_src, dx, dy,
2169            ui->dragx_dst, ui->dragy_dst));*/
2170     return "";
2171 }
2172
2173 static char *finish_drag(game_state *state, game_ui *ui)
2174 {
2175     char buf[80];
2176
2177     if (ui->dragx_src == -1 || ui->dragy_src == -1)
2178         return NULL;
2179     if (ui->dragx_dst == -1 || ui->dragy_dst == -1)
2180         return ui_cancel_drag(ui);
2181
2182     if (ui->drag_is_noline) {
2183         sprintf(buf, "N%d,%d,%d,%d",
2184                 ui->dragx_src, ui->dragy_src,
2185                 ui->dragx_dst, ui->dragy_dst);
2186     } else {
2187         sprintf(buf, "L%d,%d,%d,%d,%d",
2188                 ui->dragx_src, ui->dragy_src,
2189                 ui->dragx_dst, ui->dragy_dst, ui->nlines);
2190     }
2191
2192     ui_cancel_drag(ui);
2193
2194     return dupstr(buf);
2195 }
2196
2197 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2198                             int x, int y, int button)
2199 {
2200     int gx = FROMCOORD(x), gy = FROMCOORD(y);
2201     char buf[80], *ret;
2202     grid_type ggrid = INGRID(state,gx,gy) ? GRID(state,gx,gy) : 0;
2203
2204     if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
2205         if (!INGRID(state, gx, gy)) return NULL;
2206         ui->cur_visible = 0;
2207         if ((ggrid & G_ISLAND) && !(ggrid & G_MARK)) {
2208             ui->dragx_src = gx;
2209             ui->dragy_src = gy;
2210             return "";
2211         } else
2212             return ui_cancel_drag(ui);
2213     } else if (button == LEFT_DRAG || button == RIGHT_DRAG) {
2214         if (gx != ui->dragx_src || gy != ui->dragy_src) {
2215             ui->dragging = 1;
2216             ui->drag_is_noline = (button == RIGHT_DRAG) ? 1 : 0;
2217             return update_drag_dst(state, ui, ds, x, y);
2218         } else {
2219             /* cancel a drag when we go back to the starting point */
2220             ui->dragx_dst = -1;
2221             ui->dragy_dst = -1;
2222             return "";
2223         }
2224     } else if (button == LEFT_RELEASE || button == RIGHT_RELEASE) {
2225         if (ui->dragging) {
2226             return finish_drag(state, ui);
2227         } else {
2228             ui_cancel_drag(ui);
2229             if (!INGRID(state, gx, gy)) return NULL;
2230             if (!(GRID(state, gx, gy) & G_ISLAND)) return NULL;
2231             sprintf(buf, "M%d,%d", gx, gy);
2232             return dupstr(buf);
2233         }
2234     } else if (button == 'h' || button == 'H') {
2235         game_state *solved = dup_game(state);
2236         solve_for_hint(solved);
2237         ret = game_state_diff(state, solved);
2238         free_game(solved);
2239         return ret;
2240     } else if (IS_CURSOR_MOVE(button)) {
2241         ui->cur_visible = 1;
2242         if (ui->dragging) {
2243             int nx = ui->cur_x, ny = ui->cur_y;
2244
2245             move_cursor(button, &nx, &ny, state->w, state->h, 0);
2246             update_drag_dst(state, ui, ds,
2247                              COORD(nx)+TILE_SIZE/2,
2248                              COORD(ny)+TILE_SIZE/2);
2249             return finish_drag(state, ui);
2250         } else {
2251             int dx = (button == CURSOR_RIGHT) ? +1 : (button == CURSOR_LEFT) ? -1 : 0;
2252             int dy = (button == CURSOR_DOWN)  ? +1 : (button == CURSOR_UP)   ? -1 : 0;
2253             int dorthx = 1 - abs(dx), dorthy = 1 - abs(dy);
2254             int dir, orth, nx = x, ny = y;
2255
2256             /* 'orthorder' is a tweak to ensure that if you press RIGHT and
2257              * happen to move upwards, when you press LEFT you then tend
2258              * downwards (rather than upwards again). */
2259             int orthorder = (button == CURSOR_LEFT || button == CURSOR_UP) ? 1 : -1;
2260
2261             /* This attempts to find an island in the direction you're
2262              * asking for, broadly speaking. If you ask to go right, for
2263              * example, it'll look for islands to the right and slightly
2264              * above or below your current horiz. position, allowing
2265              * further above/below the further away it searches. */
2266
2267             assert(GRID(state, ui->cur_x, ui->cur_y) & G_ISLAND);
2268             /* currently this is depth-first (so orthogonally-adjacent
2269              * islands across the other side of the grid will be moved to
2270              * before closer islands slightly offset). Swap the order of
2271              * these two loops to change to breadth-first search. */
2272             for (orth = 0; ; orth++) {
2273                 int oingrid = 0;
2274                 for (dir = 1; ; dir++) {
2275                     int dingrid = 0;
2276
2277                     if (orth > dir) continue; /* only search in cone outwards. */
2278
2279                     nx = ui->cur_x + dir*dx + orth*dorthx*orthorder;
2280                     ny = ui->cur_y + dir*dy + orth*dorthy*orthorder;
2281                     if (INGRID(state, nx, ny)) {
2282                         dingrid = oingrid = 1;
2283                         if (GRID(state, nx, ny) & G_ISLAND) goto found;
2284                     }
2285
2286                     nx = ui->cur_x + dir*dx - orth*dorthx*orthorder;
2287                     ny = ui->cur_y + dir*dy - orth*dorthy*orthorder;
2288                     if (INGRID(state, nx, ny)) {
2289                         dingrid = oingrid = 1;
2290                         if (GRID(state, nx, ny) & G_ISLAND) goto found;
2291                     }
2292
2293                     if (!dingrid) break;
2294                 }
2295                 if (!oingrid) return "";
2296             }
2297             /* not reached */
2298
2299 found:
2300             ui->cur_x = nx;
2301             ui->cur_y = ny;
2302             return "";
2303         }
2304     } else if (IS_CURSOR_SELECT(button)) {
2305         if (!ui->cur_visible) {
2306             ui->cur_visible = 1;
2307             return "";
2308         }
2309         if (ui->dragging) {
2310             ui_cancel_drag(ui);
2311             if (ui->dragx_dst == -1 && ui->dragy_dst == -1) {
2312                 sprintf(buf, "M%d,%d", ui->cur_x, ui->cur_y);
2313                 return dupstr(buf);
2314             } else
2315                 return "";
2316         } else {
2317             grid_type v = GRID(state, ui->cur_x, ui->cur_y);
2318             if (v & G_ISLAND) {
2319                 ui->dragging = 1;
2320                 ui->dragx_src = ui->cur_x;
2321                 ui->dragy_src = ui->cur_y;
2322                 ui->dragx_dst = ui->dragy_dst = -1;
2323                 ui->drag_is_noline = (button == CURSOR_SELECT2) ? 1 : 0;
2324                 return "";
2325             }
2326         }
2327     } else if (button == 'g' || button == 'G') {
2328         ui->show_hints = 1 - ui->show_hints;
2329         return "";
2330     }
2331
2332     return NULL;
2333 }
2334
2335 static game_state *execute_move(game_state *state, char *move)
2336 {
2337     game_state *ret = dup_game(state);
2338     int x1, y1, x2, y2, nl, n;
2339     struct island *is1, *is2;
2340     char c;
2341
2342     debug(("execute_move: %s\n", move));
2343
2344     if (!*move) goto badmove;
2345     while (*move) {
2346         c = *move++;
2347         if (c == 'S') {
2348             ret->solved = TRUE;
2349             n = 0;
2350         } else if (c == 'L') {
2351             if (sscanf(move, "%d,%d,%d,%d,%d%n",
2352                        &x1, &y1, &x2, &y2, &nl, &n) != 5)
2353                 goto badmove;
2354             if (!INGRID(ret, x1, y1) || !INGRID(ret, x2, y2))
2355                 goto badmove;
2356             is1 = INDEX(ret, gridi, x1, y1);
2357             is2 = INDEX(ret, gridi, x2, y2);
2358             if (!is1 || !is2) goto badmove;
2359             if (nl < 0 || nl > state->maxb) goto badmove;
2360             island_join(is1, is2, nl, 0);
2361         } else if (c == 'N') {
2362             if (sscanf(move, "%d,%d,%d,%d%n",
2363                        &x1, &y1, &x2, &y2, &n) != 4)
2364                 goto badmove;
2365             if (!INGRID(ret, x1, y1) || !INGRID(ret, x2, y2))
2366                 goto badmove;
2367             is1 = INDEX(ret, gridi, x1, y1);
2368             is2 = INDEX(ret, gridi, x2, y2);
2369             if (!is1 || !is2) goto badmove;
2370             island_join(is1, is2, -1, 0);
2371         } else if (c == 'M') {
2372             if (sscanf(move, "%d,%d%n",
2373                        &x1, &y1, &n) != 2)
2374                 goto badmove;
2375             if (!INGRID(ret, x1, y1))
2376                 goto badmove;
2377             is1 = INDEX(ret, gridi, x1, y1);
2378             if (!is1) goto badmove;
2379             island_togglemark(is1);
2380         } else
2381             goto badmove;
2382
2383         move += n;
2384         if (*move == ';')
2385             move++;
2386         else if (*move) goto badmove;
2387     }
2388
2389     map_update_possibles(ret);
2390     if (map_check(ret)) {
2391         debug(("Game completed.\n"));
2392         ret->completed = 1;
2393     }
2394     return ret;
2395
2396 badmove:
2397     debug(("%s: unrecognised move.\n", move));
2398     free_game(ret);
2399     return NULL;
2400 }
2401
2402 static char *solve_game(game_state *state, game_state *currstate,
2403                         char *aux, char **error)
2404 {
2405     char *ret;
2406     game_state *solved;
2407
2408     if (aux) {
2409         debug(("solve_game: aux = %s\n", aux));
2410         solved = execute_move(state, aux);
2411         if (!solved) {
2412             *error = "Generated aux string is not a valid move (!).";
2413             return NULL;
2414         }
2415     } else {
2416         solved = dup_game(state);
2417         /* solve with max strength... */
2418         if (solve_from_scratch(solved, 10) == 0) {
2419             free_game(solved);
2420             *error = "Game does not have a (non-recursive) solution.";
2421             return NULL;
2422         }
2423     }
2424     ret = game_state_diff(currstate, solved);
2425     free_game(solved);
2426     debug(("solve_game: ret = %s\n", ret));
2427     return ret;
2428 }
2429
2430 /* ----------------------------------------------------------------------
2431  * Drawing routines.
2432  */
2433
2434 static void game_compute_size(game_params *params, int tilesize,
2435                               int *x, int *y)
2436 {
2437     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2438     struct { int tilesize; } ads, *ds = &ads;
2439     ads.tilesize = tilesize;
2440
2441     *x = TILE_SIZE * params->w + 2 * BORDER;
2442     *y = TILE_SIZE * params->h + 2 * BORDER;
2443 }
2444
2445 static void game_set_size(drawing *dr, game_drawstate *ds,
2446                           game_params *params, int tilesize)
2447 {
2448     ds->tilesize = tilesize;
2449 }
2450
2451 static float *game_colours(frontend *fe, int *ncolours)
2452 {
2453     float *ret = snewn(3 * NCOLOURS, float);
2454     int i;
2455
2456     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
2457
2458     for (i = 0; i < 3; i++) {
2459         ret[COL_FOREGROUND * 3 + i] = 0.0F;
2460         ret[COL_HINT * 3 + i] = ret[COL_LOWLIGHT * 3 + i];
2461         ret[COL_GRID * 3 + i] =
2462             (ret[COL_HINT * 3 + i] + ret[COL_BACKGROUND * 3 + i]) * 0.5F;
2463         ret[COL_MARK * 3 + i] = ret[COL_HIGHLIGHT * 3 + i];
2464     }
2465     ret[COL_WARNING * 3 + 0] = 1.0F;
2466     ret[COL_WARNING * 3 + 1] = 0.25F;
2467     ret[COL_WARNING * 3 + 2] = 0.25F;
2468
2469     ret[COL_SELECTED * 3 + 0] = 0.25F;
2470     ret[COL_SELECTED * 3 + 1] = 1.00F;
2471     ret[COL_SELECTED * 3 + 2] = 0.25F;
2472
2473     ret[COL_CURSOR * 3 + 0] = min(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
2474     ret[COL_CURSOR * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.8F;
2475     ret[COL_CURSOR * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 0.8F;
2476
2477     *ncolours = NCOLOURS;
2478     return ret;
2479 }
2480
2481 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2482 {
2483     struct game_drawstate *ds = snew(struct game_drawstate);
2484     int wh = state->w*state->h;
2485
2486     ds->tilesize = 0;
2487     ds->w = state->w;
2488     ds->h = state->h;
2489     ds->started = 0;
2490     ds->grid = snewn(wh, grid_type);
2491     memset(ds->grid, -1, wh*sizeof(grid_type));
2492     ds->lv = snewn(wh, int);
2493     ds->lh = snewn(wh, int);
2494     memset(ds->lv, 0, wh*sizeof(int));
2495     memset(ds->lh, 0, wh*sizeof(int));
2496     ds->show_hints = 0;
2497
2498     return ds;
2499 }
2500
2501 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2502 {
2503     sfree(ds->lv);
2504     sfree(ds->lh);
2505     sfree(ds->grid);
2506     sfree(ds);
2507 }
2508
2509 #define LINE_WIDTH (TILE_SIZE/8)
2510 #define TS8(x) (((x)*TILE_SIZE)/8)
2511
2512 #define OFFSET(thing) ((TILE_SIZE/2) - ((thing)/2))
2513
2514 static void lines_vert(drawing *dr, game_drawstate *ds,
2515                        int ox, int oy, int lv, int col, grid_type v)
2516 {
2517     int lw = LINE_WIDTH, gw = LINE_WIDTH, bw, i, loff;
2518     while ((bw = lw * lv + gw * (lv+1)) > TILE_SIZE)
2519         gw--;
2520     loff = OFFSET(bw);
2521     if (v & G_MARKV)
2522         draw_rect(dr, ox + loff, oy, bw, TILE_SIZE, COL_MARK);
2523     for (i = 0; i < lv; i++, loff += lw + gw)
2524         draw_rect(dr, ox + loff + gw, oy, lw, TILE_SIZE, col);
2525 }
2526
2527 static void lines_horiz(drawing *dr, game_drawstate *ds,
2528                         int ox, int oy, int lh, int col, grid_type v)
2529 {
2530     int lw = LINE_WIDTH, gw = LINE_WIDTH, bw, i, loff;
2531     while ((bw = lw * lh + gw * (lh+1)) > TILE_SIZE)
2532         gw--;
2533     loff = OFFSET(bw);
2534     if (v & G_MARKH)
2535         draw_rect(dr, ox, oy + loff, TILE_SIZE, bw, COL_MARK);
2536     for (i = 0; i < lh; i++, loff += lw + gw)
2537         draw_rect(dr, ox, oy + loff + gw, TILE_SIZE, lw, col);
2538 }
2539
2540 static void line_cross(drawing *dr, game_drawstate *ds,
2541                       int ox, int oy, int col, grid_type v)
2542 {
2543     int off = TS8(2);
2544     draw_line(dr, ox,     oy, ox+off, oy+off, col);
2545     draw_line(dr, ox+off, oy, ox,     oy+off, col);
2546 }
2547
2548 static int between_island(game_state *state, int sx, int sy, int dx, int dy)
2549 {
2550     int x = sx - dx, y = sy - dy;
2551
2552     while (INGRID(state, x, y)) {
2553         if (GRID(state, x, y) & G_ISLAND) goto found;
2554         x -= dx; y -= dy;
2555     }
2556     return 0;
2557 found:
2558     x = sx + dx, y = sy + dy;
2559     while (INGRID(state, x, y)) {
2560         if (GRID(state, x, y) & G_ISLAND) return 1;
2561         x += dx; y += dy;
2562     }
2563     return 0;
2564 }
2565
2566 static void lines_lvlh(game_state *state, game_ui *ui, int x, int y, grid_type v,
2567                        int *lv_r, int *lh_r)
2568 {
2569     int lh = 0, lv = 0;
2570
2571     if (v & G_LINEV) lv = INDEX(state,lines,x,y);
2572     if (v & G_LINEH) lh = INDEX(state,lines,x,y);
2573
2574     if (ui->show_hints) {
2575         if (between_island(state, x, y, 0, 1) && !lv) lv = 1;
2576         if (between_island(state, x, y, 1, 0) && !lh) lh = 1;
2577     }
2578     /*debug(("lvlh: (%d,%d) v 0x%x lv %d lh %d.\n", x, y, v, lv, lh));*/
2579     *lv_r = lv; *lh_r = lh;
2580 }
2581
2582 static void dsf_debug_draw(drawing *dr,
2583                            game_state *state, game_drawstate *ds,
2584                            int x, int y)
2585 {
2586 #ifdef DRAW_DSF
2587     int ts = TILE_SIZE/2;
2588     int ox = COORD(x) + ts/2, oy = COORD(y) + ts/2;
2589     char str[32];
2590
2591     sprintf(str, "%d", dsf_canonify(state->solver->dsf, DINDEX(x,y)));
2592     draw_text(dr, ox, oy, FONT_VARIABLE, ts,
2593               ALIGN_VCENTRE | ALIGN_HCENTRE, COL_WARNING, str);
2594 #endif
2595 }
2596
2597 static void lines_redraw(drawing *dr,
2598                          game_state *state, game_drawstate *ds, game_ui *ui,
2599                          int x, int y, grid_type v, int lv, int lh)
2600 {
2601     int ox = COORD(x), oy = COORD(y);
2602     int vcol = (v & G_FLASH) ? COL_HIGHLIGHT :
2603         (v & G_WARN) ? COL_WARNING : COL_FOREGROUND, hcol = vcol;
2604     grid_type todraw = v & G_NOLINE;
2605
2606     if (v & G_ISSEL) {
2607         if (ui->todraw & G_FLAGSH) hcol = COL_SELECTED;
2608         if (ui->todraw & G_FLAGSV) vcol = COL_SELECTED;
2609         todraw |= ui->todraw;
2610     }
2611
2612     draw_rect(dr, ox, oy, TILE_SIZE, TILE_SIZE, COL_BACKGROUND);
2613     /*if (v & G_CURSOR)
2614         draw_rect(dr, ox+TILE_SIZE/4, oy+TILE_SIZE/4,
2615                   TILE_SIZE/2, TILE_SIZE/2, COL_CURSOR);*/
2616
2617
2618     if (ui->show_hints) {
2619         if (between_island(state, x, y, 0, 1) && !(v & G_LINEV))
2620             vcol = COL_HINT;
2621         if (between_island(state, x, y, 1, 0) && !(v & G_LINEH))
2622             hcol = COL_HINT;
2623     }
2624 #ifdef DRAW_GRID
2625     draw_rect_outline(dr, ox, oy, TILE_SIZE, TILE_SIZE, COL_GRID);
2626 #endif
2627
2628     if (todraw & G_NOLINEV) {
2629         line_cross(dr, ds, ox + TS8(3), oy + TS8(1), vcol, todraw);
2630         line_cross(dr, ds, ox + TS8(3), oy + TS8(5), vcol, todraw);
2631     }
2632     if (todraw & G_NOLINEH) {
2633         line_cross(dr, ds, ox + TS8(1), oy + TS8(3), hcol, todraw);
2634         line_cross(dr, ds, ox + TS8(5), oy + TS8(3), hcol, todraw);
2635     }
2636     /* if we're drawing a real line and a hint, make sure we draw the real
2637      * line on top. */
2638     if (lv && vcol == COL_HINT) lines_vert(dr, ds, ox, oy, lv, vcol, v);
2639     if (lh) lines_horiz(dr, ds, ox, oy, lh, hcol, v);
2640     if (lv && vcol != COL_HINT) lines_vert(dr, ds, ox, oy, lv, vcol, v);
2641
2642     dsf_debug_draw(dr, state, ds, x, y);
2643     draw_update(dr, ox, oy, TILE_SIZE, TILE_SIZE);
2644 }
2645
2646 #define ISLAND_RADIUS ((TILE_SIZE*12)/20)
2647 #define ISLAND_NUMSIZE(is) \
2648     (((is)->count < 10) ? (TILE_SIZE*7)/10 : (TILE_SIZE*5)/10)
2649
2650 static void island_redraw(drawing *dr,
2651                           game_state *state, game_drawstate *ds,
2652                           struct island *is, grid_type v)
2653 {
2654     /* These overlap the edges of their squares, which is why they're drawn later.
2655      * We know they can't overlap each other because they're not allowed within 2
2656      * squares of each other. */
2657     int half = TILE_SIZE/2;
2658     int ox = COORD(is->x) + half, oy = COORD(is->y) + half;
2659     int orad = ISLAND_RADIUS, irad = orad - LINE_WIDTH;
2660     int updatesz = orad*2+1;
2661     int tcol = (v & G_FLASH) ? COL_HIGHLIGHT :
2662               (v & G_WARN)  ? COL_WARNING : COL_FOREGROUND;
2663     int col = (v & G_ISSEL) ? COL_SELECTED : tcol;
2664     int bg = (v & G_CURSOR) ? COL_CURSOR :
2665         (v & G_MARK) ? COL_MARK : COL_BACKGROUND;
2666     char str[32];
2667
2668 #ifdef DRAW_GRID
2669     draw_rect_outline(dr, COORD(is->x), COORD(is->y),
2670                       TILE_SIZE, TILE_SIZE, COL_GRID);
2671 #endif
2672
2673     /* draw a thick circle */
2674     draw_circle(dr, ox, oy, orad, col, col);
2675     draw_circle(dr, ox, oy, irad, bg, bg);
2676
2677     sprintf(str, "%d", is->count);
2678     draw_text(dr, ox, oy, FONT_VARIABLE, ISLAND_NUMSIZE(is),
2679               ALIGN_VCENTRE | ALIGN_HCENTRE, tcol, str);
2680
2681     dsf_debug_draw(dr, state, ds, is->x, is->y);
2682     draw_update(dr, ox - orad, oy - orad, updatesz, updatesz);
2683 }
2684
2685 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2686                         game_state *state, int dir, game_ui *ui,
2687                         float animtime, float flashtime)
2688 {
2689     int x, y, force = 0, i, j, redraw, lv, lh;
2690     grid_type v, dsv, flash = 0;
2691     struct island *is, *is_drag_src = NULL, *is_drag_dst = NULL;
2692
2693     if (flashtime) {
2694         int f = (int)(flashtime * 5 / FLASH_TIME);
2695         if (f == 1 || f == 3) flash = G_FLASH;
2696     }
2697
2698     /* Clear screen, if required. */
2699     if (!ds->started) {
2700         draw_rect(dr, 0, 0,
2701                   TILE_SIZE * ds->w + 2 * BORDER,
2702                   TILE_SIZE * ds->h + 2 * BORDER, COL_BACKGROUND);
2703 #ifdef DRAW_GRID
2704         draw_rect_outline(dr,
2705                           COORD(0)-1, COORD(0)-1,
2706                           TILE_SIZE * ds->w + 2, TILE_SIZE * ds->h + 2,
2707                           COL_GRID);
2708 #endif
2709         draw_update(dr, 0, 0,
2710                     TILE_SIZE * ds->w + 2 * BORDER,
2711                     TILE_SIZE * ds->h + 2 * BORDER);
2712         ds->started = 1;
2713         force = 1;
2714     }
2715
2716     if (ui->dragx_src != -1 && ui->dragy_src != -1) {
2717         ds->dragging = 1;
2718         is_drag_src = INDEX(state, gridi, ui->dragx_src, ui->dragy_src);
2719         assert(is_drag_src);
2720         if (ui->dragx_dst != -1 && ui->dragy_dst != -1) {
2721             is_drag_dst = INDEX(state, gridi, ui->dragx_dst, ui->dragy_dst);
2722             assert(is_drag_dst);
2723         }
2724     } else
2725         ds->dragging = 0;
2726
2727     if (ui->show_hints != ds->show_hints) {
2728         force = 1;
2729         ds->show_hints = ui->show_hints;
2730     }
2731
2732     /* Draw all lines (and hints, if we want), but *not* islands. */
2733     for (x = 0; x < ds->w; x++) {
2734         for (y = 0; y < ds->h; y++) {
2735             v = GRID(state, x, y) | flash;
2736             dsv = GRID(ds,x,y) & ~G_REDRAW;
2737
2738             if (v & G_ISLAND) continue;
2739
2740             if (is_drag_dst) {
2741                 if (WITHIN(x,is_drag_src->x, is_drag_dst->x) &&
2742                     WITHIN(y,is_drag_src->y, is_drag_dst->y))
2743                     v |= G_ISSEL;
2744             }
2745             lines_lvlh(state, ui, x, y, v, &lv, &lh);
2746
2747             /*if (ui->cur_visible && ui->cur_x == x && ui->cur_y == y)
2748                 v |= G_CURSOR;*/
2749
2750             if (v != dsv ||
2751                 lv != INDEX(ds,lv,x,y) ||
2752                 lh != INDEX(ds,lh,x,y) ||
2753                 force) {
2754                 GRID(ds, x, y) = v | G_REDRAW;
2755                 INDEX(ds,lv,x,y) = lv;
2756                 INDEX(ds,lh,x,y) = lh;
2757                 lines_redraw(dr, state, ds, ui, x, y, v, lv, lh);
2758             } else
2759                 GRID(ds,x,y) &= ~G_REDRAW;
2760         }
2761     }
2762
2763     /* Draw islands. */
2764     for (i = 0; i < state->n_islands; i++) {
2765         is = &state->islands[i];
2766         v = GRID(state, is->x, is->y) | flash;
2767
2768         redraw = 0;
2769         for (j = 0; j < is->adj.npoints; j++) {
2770             if (GRID(ds,is->adj.points[j].x,is->adj.points[j].y) & G_REDRAW) {
2771                 redraw = 1;
2772             }
2773         }
2774
2775         if (is_drag_src) {
2776             if (is == is_drag_src)
2777                 v |= G_ISSEL;
2778             else if (is_drag_dst && is == is_drag_dst)
2779                 v |= G_ISSEL;
2780         }
2781
2782         if (island_impossible(is, v & G_MARK)) v |= G_WARN;
2783
2784         if (ui->cur_visible && ui->cur_x == is->x && ui->cur_y == is->y)
2785             v |= G_CURSOR;
2786
2787         if ((v != GRID(ds, is->x, is->y)) || force || redraw) {
2788             GRID(ds,is->x,is->y) = v;
2789             island_redraw(dr, state, ds, is, v);
2790         }
2791     }
2792 }
2793
2794 static float game_anim_length(game_state *oldstate, game_state *newstate,
2795                               int dir, game_ui *ui)
2796 {
2797     return 0.0F;
2798 }
2799
2800 static float game_flash_length(game_state *oldstate, game_state *newstate,
2801                                int dir, game_ui *ui)
2802 {
2803     if (!oldstate->completed && newstate->completed &&
2804         !oldstate->solved && !newstate->solved)
2805         return FLASH_TIME;
2806
2807     return 0.0F;
2808 }
2809
2810 static int game_status(game_state *state)
2811 {
2812     return state->completed ? +1 : 0;
2813 }
2814
2815 static int game_timing_state(game_state *state, game_ui *ui)
2816 {
2817     return TRUE;
2818 }
2819
2820 static void game_print_size(game_params *params, float *x, float *y)
2821 {
2822     int pw, ph;
2823
2824     /* 10mm squares by default. */
2825     game_compute_size(params, 1000, &pw, &ph);
2826     *x = pw / 100.0F;
2827     *y = ph / 100.0F;
2828 }
2829
2830 static void game_print(drawing *dr, game_state *state, int ts)
2831 {
2832     int ink = print_mono_colour(dr, 0);
2833     int paper = print_mono_colour(dr, 1);
2834     int x, y, cx, cy, i, nl;
2835     int loff;
2836     grid_type grid;
2837
2838     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2839     game_drawstate ads, *ds = &ads;
2840     ads.tilesize = ts;
2841
2842     /* I don't think this wants a border. */
2843
2844     /* Bridges */
2845     loff = ts / (8 * sqrt((state->params.maxb - 1)));
2846     print_line_width(dr, ts / 12);
2847     for (x = 0; x < state->w; x++) {
2848         for (y = 0; y < state->h; y++) {
2849             cx = COORD(x); cy = COORD(y);
2850             grid = GRID(state,x,y);
2851             nl = INDEX(state,lines,x,y);
2852
2853             if (grid & G_ISLAND) continue;
2854             if (grid & G_LINEV) {
2855                 for (i = 0; i < nl; i++)
2856                     draw_line(dr, cx+ts/2+(2*i-nl+1)*loff, cy,
2857                               cx+ts/2+(2*i-nl+1)*loff, cy+ts, ink);
2858             }
2859             if (grid & G_LINEH) {
2860                 for (i = 0; i < nl; i++)
2861                     draw_line(dr, cx, cy+ts/2+(2*i-nl+1)*loff,
2862                               cx+ts, cy+ts/2+(2*i-nl+1)*loff, ink);
2863             }
2864         }
2865     }
2866
2867     /* Islands */
2868     for (i = 0; i < state->n_islands; i++) {
2869         char str[32];
2870         struct island *is = &state->islands[i];
2871         grid = GRID(state, is->x, is->y);
2872         cx = COORD(is->x) + ts/2;
2873         cy = COORD(is->y) + ts/2;
2874
2875         draw_circle(dr, cx, cy, ISLAND_RADIUS, paper, ink);
2876
2877         sprintf(str, "%d", is->count);
2878         draw_text(dr, cx, cy, FONT_VARIABLE, ISLAND_NUMSIZE(is),
2879                   ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
2880     }
2881 }
2882
2883 #ifdef COMBINED
2884 #define thegame bridges
2885 #endif
2886
2887 const struct game thegame = {
2888     "Bridges", "games.bridges", "bridges",
2889     default_params,
2890     game_fetch_preset,
2891     decode_params,
2892     encode_params,
2893     free_params,
2894     dup_params,
2895     TRUE, game_configure, custom_params,
2896     validate_params,
2897     new_game_desc,
2898     validate_desc,
2899     new_game,
2900     dup_game,
2901     free_game,
2902     TRUE, solve_game,
2903     TRUE, game_can_format_as_text_now, game_text_format,
2904     new_ui,
2905     free_ui,
2906     encode_ui,
2907     decode_ui,
2908     game_changed_state,
2909     interpret_move,
2910     execute_move,
2911     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2912     game_colours,
2913     game_new_drawstate,
2914     game_free_drawstate,
2915     game_redraw,
2916     game_anim_length,
2917     game_flash_length,
2918     game_status,
2919     TRUE, FALSE, game_print_size, game_print,
2920     FALSE,                             /* wants_statusbar */
2921     FALSE, game_timing_state,
2922     REQUIRE_RBUTTON,                   /* flags */
2923 };
2924
2925 /* vim: set shiftwidth=4 tabstop=8: */