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