chiark / gitweb /
Remove the speed optimisation in the stage 3 solver which makes the
[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         maxb = state->params.maxb;     /* placate optimiser */
944         /* Unset possible flags until we find an island. */
945         for (y = 0; y < state->h; y++) {
946             is_s = IDX(state, gridi, idx);
947             if (is_s) {
948                 maxb = is_s->count;
949                 break;
950             }
951
952             IDX(state, possv, idx) = 0;
953             idx += w;
954         }
955         for (; y < state->h; y++) {
956             maxb = min(maxb, IDX(state, maxv, idx));
957             is_f = IDX(state, gridi, idx);
958             if (is_f) {
959                 assert(is_s);
960                 np = min(maxb, is_f->count);
961
962                 if (s != -1) {
963                     for (i = s; i <= e; i++) {
964                         INDEX(state, possv, x, i) = bl ? 0 : np;
965                     }
966                 }
967                 s = y+1;
968                 bl = 0;
969                 is_s = is_f;
970                 maxb = is_s->count;
971             } else {
972                 e = y;
973                 if (IDX(state,grid,idx) & (G_LINEH|G_NOLINEV)) bl = 1;
974             }
975             idx += w;
976         }
977         if (s != -1) {
978             for (i = s; i <= e; i++)
979                 INDEX(state, possv, x, i) = 0;
980         }
981     }
982
983     /* ...and now do horizontal stripes [un]setting possh. */
984     /* can we lose this clone'n'hack? */
985     for (y = 0; y < state->h; y++) {
986         idx = y*w;
987         s = e = -1;
988         bl = 0;
989         maxb = state->params.maxb;     /* placate optimiser */
990         for (x = 0; x < state->w; x++) {
991             is_s = IDX(state, gridi, idx);
992             if (is_s) {
993                 maxb = is_s->count;
994                 break;
995             }
996
997             IDX(state, possh, idx) = 0;
998             idx += 1;
999         }
1000         for (; x < state->w; x++) {
1001             maxb = min(maxb, IDX(state, maxh, idx));
1002             is_f = IDX(state, gridi, idx);
1003             if (is_f) {
1004                 assert(is_s);
1005                 np = min(maxb, is_f->count);
1006
1007                 if (s != -1) {
1008                     for (i = s; i <= e; i++) {
1009                         INDEX(state, possh, i, y) = bl ? 0 : np;
1010                     }
1011                 }
1012                 s = x+1;
1013                 bl = 0;
1014                 is_s = is_f;
1015                 maxb = is_s->count;
1016             } else {
1017                 e = x;
1018                 if (IDX(state,grid,idx) & (G_LINEV|G_NOLINEH)) bl = 1;
1019             }
1020             idx += 1;
1021         }
1022         if (s != -1) {
1023             for (i = s; i <= e; i++)
1024                 INDEX(state, possh, i, y) = 0;
1025         }
1026     }
1027 }
1028
1029 static void map_count(game_state *state)
1030 {
1031     int i, n, ax, ay;
1032     grid_type flag, grid;
1033     struct island *is;
1034
1035     for (i = 0; i < state->n_islands; i++) {
1036         is = &state->islands[i];
1037         is->count = 0;
1038         for (n = 0; n < is->adj.npoints; n++) {
1039             ax = is->adj.points[n].x;
1040             ay = is->adj.points[n].y;
1041             flag = (ax == is->x) ? G_LINEV : G_LINEH;
1042             grid = GRID(state,ax,ay);
1043             if (grid & flag) {
1044                 is->count += INDEX(state,lines,ax,ay);
1045             }
1046         }
1047     }
1048 }
1049
1050 static void map_find_orthogonal(game_state *state)
1051 {
1052     int i;
1053
1054     for (i = 0; i < state->n_islands; i++) {
1055         island_find_orthogonal(&state->islands[i]);
1056     }
1057 }
1058
1059 static int grid_degree(game_state *state, int x, int y, int *nx_r, int *ny_r)
1060 {
1061     grid_type grid = SCRATCH(state, x, y), gline = grid & G_LINE;
1062     struct island *is;
1063     int x1, y1, x2, y2, c = 0, i, nx, ny;
1064
1065     nx = ny = -1; /* placate optimiser */
1066     is = INDEX(state, gridi, x, y);
1067     if (is) {
1068         for (i = 0; i < is->adj.npoints; i++) {
1069             gline = is->adj.points[i].dx ? G_LINEH : G_LINEV;
1070             if (SCRATCH(state,
1071                         is->adj.points[i].x,
1072                         is->adj.points[i].y) & gline) {
1073                 nx = is->adj.points[i].x;
1074                 ny = is->adj.points[i].y;
1075                 c++;
1076             }
1077         }
1078     } else if (gline) {
1079         if (gline & G_LINEV) {
1080             x1 = x2 = x;
1081             y1 = y-1; y2 = y+1;
1082         } else {
1083             x1 = x-1; x2 = x+1;
1084             y1 = y2 = y;
1085         }
1086         /* Non-island squares with edges in should never be pointing off the
1087          * edge of the grid. */
1088         assert(INGRID(state, x1, y1));
1089         assert(INGRID(state, x2, y2));
1090         if (SCRATCH(state, x1, y1) & (gline | G_ISLAND)) {
1091             nx = x1; ny = y1; c++;
1092         }
1093         if (SCRATCH(state, x2, y2) & (gline | G_ISLAND)) {
1094             nx = x2; ny = y2; c++;
1095         }
1096     }
1097     if (c == 1) {
1098         assert(nx != -1 && ny != -1); /* paranoia */
1099         *nx_r = nx; *ny_r = ny;
1100     }
1101     return c;
1102 }
1103
1104 static int map_hasloops(game_state *state, int mark)
1105 {
1106     int x, y, ox, oy, nx = 0, ny = 0, loop = 0;
1107
1108     memcpy(state->scratch, state->grid, GRIDSZ(state));
1109
1110     /* This algorithm is actually broken; if there are two loops connected
1111      * by bridges this will also highlight bridges. The correct algorithm
1112      * uses a dsf and a two-pass edge-detection algorithm (see check_correct
1113      * in slant.c); this is BALGE for now, especially since disallow-loops
1114      * is not the default for this puzzle. If we want to fix this later then
1115      * copy the alg in slant.c to the empty statement in map_group. */
1116
1117     /* Remove all 1-degree edges. */
1118     for (y = 0; y < state->h; y++) {
1119         for (x = 0; x < state->w; x++) {
1120             ox = x; oy = y;
1121             while (grid_degree(state, ox, oy, &nx, &ny) == 1) {
1122                 /*debug(("hasloops: removing 1-degree at (%d,%d).\n", ox, oy));*/
1123                 SCRATCH(state, ox, oy) &= ~(G_LINE|G_ISLAND);
1124                 ox = nx; oy = ny;
1125             }
1126         }
1127     }
1128     /* Mark any remaining edges as G_WARN, if required. */
1129     for (x = 0; x < state->w; x++) {
1130         for (y = 0; y < state->h; y++) {
1131             if (GRID(state,x,y) & G_ISLAND) continue;
1132
1133             if (SCRATCH(state, x, y) & G_LINE) {
1134                 if (mark) {
1135                     /*debug(("hasloops: marking loop square at (%d,%d).\n",
1136                            x, y));*/
1137                     GRID(state,x,y) |= G_WARN;
1138                     loop = 1;
1139                 } else
1140                     return 1; /* short-cut as soon as we find one */
1141             } else {
1142                 if (mark)
1143                     GRID(state,x,y) &= ~G_WARN;
1144             }
1145         }
1146     }
1147     return loop;
1148 }
1149
1150 static void map_group(game_state *state)
1151 {
1152     int i, wh = state->w*state->h, d1, d2;
1153     int x, y, x2, y2;
1154     int *dsf = state->solver->dsf;
1155     struct island *is, *is_join;
1156
1157     /* Initialise dsf. */
1158     dsf_init(dsf, wh);
1159
1160     /* For each island, find connected islands right or down
1161      * and merge the dsf for the island squares as well as the
1162      * bridge squares. */
1163     for (x = 0; x < state->w; x++) {
1164         for (y = 0; y < state->h; y++) {
1165             GRID(state,x,y) &= ~(G_SWEEP|G_WARN); /* for group_full. */
1166
1167             is = INDEX(state, gridi, x, y);
1168             if (!is) continue;
1169             d1 = DINDEX(x,y);
1170             for (i = 0; i < is->adj.npoints; i++) {
1171                 /* only want right/down */
1172                 if (is->adj.points[i].dx == -1 ||
1173                     is->adj.points[i].dy == -1) continue;
1174
1175                 is_join = island_find_connection(is, i);
1176                 if (!is_join) continue;
1177
1178                 d2 = DINDEX(is_join->x, is_join->y);
1179                 if (dsf_canonify(dsf,d1) == dsf_canonify(dsf,d2)) {
1180                     ; /* we have a loop. See comment in map_hasloops. */
1181                     /* However, we still want to merge all squares joining
1182                      * this side-that-makes-a-loop. */
1183                 }
1184                 /* merge all squares between island 1 and island 2. */
1185                 for (x2 = x; x2 <= is_join->x; x2++) {
1186                     for (y2 = y; y2 <= is_join->y; y2++) {
1187                         d2 = DINDEX(x2,y2);
1188                         if (d1 != d2) dsf_merge(dsf,d1,d2);
1189                     }
1190                 }
1191             }
1192         }
1193     }
1194 }
1195
1196 static int map_group_check(game_state *state, int canon, int warn,
1197                            int *nislands_r)
1198 {
1199     int *dsf = state->solver->dsf, nislands = 0;
1200     int x, y, i, allfull = 1;
1201     struct island *is;
1202
1203     for (i = 0; i < state->n_islands; i++) {
1204         is = &state->islands[i];
1205         if (dsf_canonify(dsf, DINDEX(is->x,is->y)) != canon) continue;
1206
1207         GRID(state, is->x, is->y) |= G_SWEEP;
1208         nislands++;
1209         if (island_countbridges(is) != is->count)
1210             allfull = 0;
1211     }
1212     if (warn && allfull && nislands != state->n_islands) {
1213         /* we're full and this island group isn't the whole set.
1214          * Mark all squares with this dsf canon as ERR. */
1215         for (x = 0; x < state->w; x++) {
1216             for (y = 0; y < state->h; y++) {
1217                 if (dsf_canonify(dsf, DINDEX(x,y)) == canon) {
1218                     GRID(state,x,y) |= G_WARN;
1219                 }
1220             }
1221         }
1222
1223     }
1224     if (nislands_r) *nislands_r = nislands;
1225     return allfull;
1226 }
1227
1228 static int map_group_full(game_state *state, int *ngroups_r)
1229 {
1230     int *dsf = state->solver->dsf, ngroups = 0;
1231     int i, anyfull = 0;
1232     struct island *is;
1233
1234     /* NB this assumes map_group (or sth else) has cleared G_SWEEP. */
1235
1236     for (i = 0; i < state->n_islands; i++) {
1237         is = &state->islands[i];
1238         if (GRID(state,is->x,is->y) & G_SWEEP) continue;
1239
1240         ngroups++;
1241         if (map_group_check(state, dsf_canonify(dsf, DINDEX(is->x,is->y)),
1242                             1, NULL))
1243             anyfull = 1;
1244     }
1245
1246     *ngroups_r = ngroups;
1247     return anyfull;
1248 }
1249
1250 static int map_check(game_state *state)
1251 {
1252     int ngroups;
1253
1254     /* Check for loops, if necessary. */
1255     if (!state->allowloops) {
1256         if (map_hasloops(state, 1))
1257             return 0;
1258     }
1259
1260     /* Place islands into island groups and check for early
1261      * satisfied-groups. */
1262     map_group(state); /* clears WARN and SWEEP */
1263     if (map_group_full(state, &ngroups)) {
1264         if (ngroups == 1) return 1;
1265     }
1266     return 0;
1267 }
1268
1269 static void map_clear(game_state *state)
1270 {
1271     int x, y;
1272
1273     for (x = 0; x < state->w; x++) {
1274         for (y = 0; y < state->h; y++) {
1275             /* clear most flags; might want to be slightly more careful here. */
1276             GRID(state,x,y) &= G_ISLAND;
1277         }
1278     }
1279 }
1280
1281 static void solve_join(struct island *is, int direction, int n, int is_max)
1282 {
1283     struct island *is_orth;
1284     int d1, d2, *dsf = is->state->solver->dsf;
1285     game_state *state = is->state; /* for DINDEX */
1286
1287     is_orth = INDEX(is->state, gridi,
1288                     ISLAND_ORTHX(is, direction),
1289                     ISLAND_ORTHY(is, direction));
1290     assert(is_orth);
1291     /*debug(("...joining (%d,%d) to (%d,%d) with %d bridge(s).\n",
1292            is->x, is->y, is_orth->x, is_orth->y, n));*/
1293     island_join(is, is_orth, n, is_max);
1294
1295     if (n > 0 && !is_max) {
1296         d1 = DINDEX(is->x, is->y);
1297         d2 = DINDEX(is_orth->x, is_orth->y);
1298         if (dsf_canonify(dsf, d1) != dsf_canonify(dsf, d2))
1299             dsf_merge(dsf, d1, d2);
1300     }
1301 }
1302
1303 static int solve_fillone(struct island *is)
1304 {
1305     int i, nadded = 0;
1306
1307     debug(("solve_fillone for island (%d,%d).\n", is->x, is->y));
1308
1309     for (i = 0; i < is->adj.npoints; i++) {
1310         if (island_isadj(is, i)) {
1311             if (island_hasbridge(is, i)) {
1312                 /* already attached; do nothing. */;
1313             } else {
1314                 solve_join(is, i, 1, 0);
1315                 nadded++;
1316             }
1317         }
1318     }
1319     return nadded;
1320 }
1321
1322 static int solve_fill(struct island *is)
1323 {
1324     /* for each unmarked adjacent, make sure we convert every possible bridge
1325      * to a real one, and then work out the possibles afresh. */
1326     int i, nnew, ncurr, nadded = 0, missing;
1327
1328     debug(("solve_fill for island (%d,%d).\n", is->x, is->y));
1329
1330     missing = is->count - island_countbridges(is);
1331     if (missing < 0) return 0;
1332
1333     /* very like island_countspaces. */
1334     for (i = 0; i < is->adj.npoints; i++) {
1335         nnew = island_adjspace(is, 1, missing, i);
1336         if (nnew) {
1337             ncurr = GRIDCOUNT(is->state,
1338                               is->adj.points[i].x, is->adj.points[i].y,
1339                               is->adj.points[i].dx ? G_LINEH : G_LINEV);
1340
1341             solve_join(is, i, nnew + ncurr, 0);
1342             nadded += nnew;
1343         }
1344     }
1345     return nadded;
1346 }
1347
1348 static int solve_island_stage1(struct island *is, int *didsth_r)
1349 {
1350     int bridges = island_countbridges(is);
1351     int nspaces = island_countspaces(is, 1);
1352     int nadj = island_countadj(is);
1353     int didsth = 0;
1354
1355     assert(didsth_r);
1356
1357     /*debug(("island at (%d,%d) filled %d/%d (%d spc) nadj %d\n",
1358            is->x, is->y, bridges, is->count, nspaces, nadj));*/
1359     if (bridges > is->count) {
1360         /* We only ever add bridges when we're sure they fit, or that's
1361          * the only place they can go. If we've added bridges such that
1362          * another island has become wrong, the puzzle must not have had
1363          * a solution. */
1364         debug(("...island at (%d,%d) is overpopulated!\n", is->x, is->y));
1365         return 0;
1366     } else if (bridges == is->count) {
1367         /* This island is full. Make sure it's marked (and update
1368          * possibles if we did). */
1369         if (!(GRID(is->state, is->x, is->y) & G_MARK)) {
1370             debug(("...marking island (%d,%d) as full.\n", is->x, is->y));
1371             island_togglemark(is);
1372             didsth = 1;
1373         }
1374     } else if (GRID(is->state, is->x, is->y) & G_MARK) {
1375         debug(("...island (%d,%d) is marked but unfinished!\n",
1376                is->x, is->y));
1377         return 0; /* island has been marked unfinished; no solution from here. */
1378     } else {
1379         /* This is the interesting bit; we try and fill in more information
1380          * about this island. */
1381         if (is->count == bridges + nspaces) {
1382             if (solve_fill(is) > 0) didsth = 1;
1383         } else if (is->count > ((nadj-1) * is->state->maxb)) {
1384             /* must have at least one bridge in each possible direction. */
1385             if (solve_fillone(is) > 0) didsth = 1;
1386         }
1387     }
1388     if (didsth) {
1389         map_update_possibles(is->state);
1390         *didsth_r = 1;
1391     }
1392     return 1;
1393 }
1394
1395 /* returns non-zero if a new line here would cause a loop. */
1396 static int solve_island_checkloop(struct island *is, int direction)
1397 {
1398     struct island *is_orth;
1399     int *dsf = is->state->solver->dsf, d1, d2;
1400     game_state *state = is->state;
1401
1402     if (is->state->allowloops) return 0; /* don't care anyway */
1403     if (island_hasbridge(is, direction)) return 0; /* already has a bridge */
1404     if (island_isadj(is, direction) == 0) return 0; /* no adj island */
1405
1406     is_orth = INDEX(is->state, gridi,
1407                     ISLAND_ORTHX(is,direction),
1408                     ISLAND_ORTHY(is,direction));
1409     if (!is_orth) return 0;
1410
1411     d1 = DINDEX(is->x, is->y);
1412     d2 = DINDEX(is_orth->x, is_orth->y);
1413     if (dsf_canonify(dsf, d1) == dsf_canonify(dsf, d2)) {
1414         /* two islands are connected already; don't join them. */
1415         return 1;
1416     }
1417     return 0;
1418 }
1419
1420 static int solve_island_stage2(struct island *is, int *didsth_r)
1421 {
1422     int added = 0, removed = 0, navail = 0, nadj, i;
1423
1424     assert(didsth_r);
1425
1426     for (i = 0; i < is->adj.npoints; i++) {
1427         if (solve_island_checkloop(is, i)) {
1428             debug(("removing possible loop at (%d,%d) direction %d.\n",
1429                    is->x, is->y, i));
1430             solve_join(is, i, -1, 0);
1431             map_update_possibles(is->state);
1432             removed = 1;
1433         } else {
1434             navail += island_isadj(is, i);
1435             /*debug(("stage2: navail for (%d,%d) direction (%d,%d) is %d.\n",
1436                    is->x, is->y,
1437                    is->adj.points[i].dx, is->adj.points[i].dy,
1438                    island_isadj(is, i)));*/
1439         }
1440     }
1441
1442     /*debug(("island at (%d,%d) navail %d: checking...\n", is->x, is->y, navail));*/
1443
1444     for (i = 0; i < is->adj.npoints; i++) {
1445         if (!island_hasbridge(is, i)) {
1446             nadj = island_isadj(is, i);
1447             if (nadj > 0 && (navail - nadj) < is->count) {
1448                 /* we couldn't now complete the island without at
1449                  * least one bridge here; put it in. */
1450                 /*debug(("nadj %d, navail %d, is->count %d.\n",
1451                        nadj, navail, is->count));*/
1452                 debug(("island at (%d,%d) direction (%d,%d) must have 1 bridge\n",
1453                        is->x, is->y,
1454                        is->adj.points[i].dx, is->adj.points[i].dy));
1455                 solve_join(is, i, 1, 0);
1456                 added = 1;
1457                 /*debug_state(is->state);
1458                 debug_possibles(is->state);*/
1459             }
1460         }
1461     }
1462     if (added) map_update_possibles(is->state);
1463     if (added || removed) *didsth_r = 1;
1464     return 1;
1465 }
1466
1467 static int solve_island_subgroup(struct island *is, int direction)
1468 {
1469     struct island *is_join;
1470     int nislands, *dsf = is->state->solver->dsf;
1471     game_state *state = is->state;
1472
1473     debug(("..checking subgroups.\n"));
1474
1475     /* if is isn't full, return 0. */
1476     if (island_countbridges(is) < is->count) {
1477         debug(("...orig island (%d,%d) not full.\n", is->x, is->y));
1478         return 0;
1479     }
1480
1481     if (direction >= 0) {
1482         is_join = INDEX(state, gridi,
1483                         ISLAND_ORTHX(is, direction),
1484                         ISLAND_ORTHY(is, direction));
1485         assert(is_join);
1486
1487         /* if is_join isn't full, return 0. */
1488         if (island_countbridges(is_join) < is_join->count) {
1489             debug(("...dest island (%d,%d) not full.\n",
1490                    is_join->x, is_join->y));
1491             return 0;
1492         }
1493     }
1494
1495     /* Check group membership for is->dsf; if it's full return 1. */
1496     if (map_group_check(state, dsf_canonify(dsf, DINDEX(is->x,is->y)),
1497                         0, &nislands)) {
1498         if (nislands < state->n_islands) {
1499             /* we have a full subgroup that isn't the whole set.
1500              * This isn't allowed. */
1501             debug(("island at (%d,%d) makes full subgroup, disallowing.\n",
1502                    is->x, is->y));
1503             return 1;
1504         } else {
1505             debug(("...has finished puzzle.\n"));
1506         }
1507     }
1508     return 0;
1509 }
1510
1511 static int solve_island_impossible(game_state *state)
1512 {
1513     struct island *is;
1514     int i;
1515
1516     /* If any islands are impossible, return 1. */
1517     for (i = 0; i < state->n_islands; i++) {
1518         is = &state->islands[i];
1519         if (island_impossible(is, 0)) {
1520             debug(("island at (%d,%d) has become impossible, disallowing.\n",
1521                    is->x, is->y));
1522             return 1;
1523         }
1524     }
1525     return 0;
1526 }
1527
1528 /* Bear in mind that this function is really rather inefficient. */
1529 static int solve_island_stage3(struct island *is, int *didsth_r)
1530 {
1531     int i, n, x, y, missing, spc, curr, maxb, didsth = 0;
1532     int wh = is->state->w * is->state->h;
1533     struct solver_state *ss = is->state->solver;
1534
1535     assert(didsth_r);
1536
1537     missing = is->count - island_countbridges(is);
1538     if (missing <= 0) return 1;
1539
1540     for (i = 0; i < is->adj.npoints; i++) {
1541         x = is->adj.points[i].x;
1542         y = is->adj.points[i].y;
1543         spc = island_adjspace(is, 1, missing, i);
1544         if (spc == 0) continue;
1545
1546         curr = GRIDCOUNT(is->state, x, y,
1547                          is->adj.points[i].dx ? G_LINEH : G_LINEV);
1548         debug(("island at (%d,%d) s3, trying %d - %d bridges.\n",
1549                is->x, is->y, curr+1, curr+spc));
1550
1551         /* Now we know that this island could have more bridges,
1552          * to bring the total from curr+1 to curr+spc. */
1553         maxb = -1;
1554         /* We have to squirrel the dsf away and restore it afterwards;
1555          * it is additive only, and can't be removed from. */
1556         memcpy(ss->tmpdsf, ss->dsf, wh*sizeof(int));
1557         for (n = curr+1; n <= curr+spc; n++) {
1558             solve_join(is, i, n, 0);
1559             map_update_possibles(is->state);
1560
1561             if (solve_island_subgroup(is, i) ||
1562                 solve_island_impossible(is->state)) {
1563                 maxb = n-1;
1564                 debug(("island at (%d,%d) d(%d,%d) new max of %d bridges:\n",
1565                        is->x, is->y,
1566                        is->adj.points[i].dx, is->adj.points[i].dy,
1567                        maxb));
1568                 break;
1569             }
1570         }
1571         solve_join(is, i, curr, 0); /* put back to before. */
1572         memcpy(ss->dsf, ss->tmpdsf, wh*sizeof(int));
1573
1574         if (maxb != -1) {
1575             /*debug_state(is->state);*/
1576             if (maxb == 0) {
1577                 debug(("...adding NOLINE.\n"));
1578                 solve_join(is, i, -1, 0); /* we can't have any bridges here. */
1579             } else {
1580                 debug(("...setting maximum\n"));
1581                 solve_join(is, i, maxb, 1);
1582             }
1583             didsth = 1;
1584         }
1585         map_update_possibles(is->state);
1586     }
1587
1588     for (i = 0; i < is->adj.npoints; i++) {
1589         /*
1590          * Now check to see if any currently empty direction must have
1591          * at least one bridge in order to avoid forming an isolated
1592          * subgraph. This differs from the check above in that it
1593          * considers multiple target islands. For example:
1594          *
1595          *   2   2    4
1596          *                                  1     3     2
1597          *       3
1598          *                                        4
1599          *
1600          * The example on the left can be handled by the above loop:
1601          * it will observe that connecting the central 2 twice to the
1602          * left would form an isolated subgraph, and hence it will
1603          * restrict that 2 to at most one bridge in that direction.
1604          * But the example on the right won't be handled by that loop,
1605          * because the deduction requires us to imagine connecting the
1606          * 3 to _both_ the 1 and 2 at once to form an isolated
1607          * subgraph.
1608          *
1609          * This pass is necessary _as well_ as the above one, because
1610          * neither can do the other's job. In the left one,
1611          * restricting the direction which _would_ cause trouble can
1612          * be done even if it's not yet clear which of the remaining
1613          * directions has to have a compensatory bridge; whereas the
1614          * pass below that can handle the right-hand example does need
1615          * to know what direction to point the necessary bridge in.
1616          *
1617          * Neither pass can handle the most general case, in which we
1618          * observe that an arbitrary subset of an island's neighbours
1619          * would form an isolated subgraph with it if it connected
1620          * maximally to them, and hence that at least one bridge must
1621          * point to some neighbour outside that subset but we don't
1622          * know which neighbour. To handle that, we'd have to have a
1623          * richer data format for the solver, which could cope with
1624          * recording the idea that at least one of two edges must have
1625          * a bridge.
1626          */
1627         int got = 0;
1628         int before[4];
1629         int j;
1630
1631         spc = island_adjspace(is, 1, missing, i);
1632         if (spc == 0) continue;
1633
1634         for (j = 0; j < is->adj.npoints; j++)
1635             before[j] = GRIDCOUNT(is->state,
1636                                   is->adj.points[j].x,
1637                                   is->adj.points[j].y,
1638                                   is->adj.points[j].dx ? G_LINEH : G_LINEV);
1639         if (before[i] != 0) continue;  /* this idea is pointless otherwise */
1640
1641         memcpy(ss->tmpdsf, ss->dsf, wh*sizeof(int));
1642
1643         for (j = 0; j < is->adj.npoints; j++) {
1644             spc = island_adjspace(is, 1, missing, j);
1645             if (spc == 0) continue;
1646             if (j == i) continue;
1647             solve_join(is, j, before[j] + spc, 0);
1648         }
1649         map_update_possibles(is->state);
1650
1651         if (solve_island_subgroup(is, -1))
1652             got = 1;
1653
1654         for (j = 0; j < is->adj.npoints; j++)
1655             solve_join(is, j, before[j], 0);
1656         memcpy(ss->dsf, ss->tmpdsf, wh*sizeof(int));
1657
1658         if (got) {
1659             debug(("island at (%d,%d) must connect in direction (%d,%d) to"
1660                    " avoid full subgroup.\n",
1661                    is->x, is->y, is->adj.points[i].dx, is->adj.points[i].dy));
1662             solve_join(is, i, 1, 0);
1663             didsth = 1;
1664         }
1665
1666         map_update_possibles(is->state);
1667     }
1668
1669     if (didsth) *didsth_r = didsth;
1670     return 1;
1671 }
1672
1673 #define CONTINUE_IF_FULL do {                           \
1674 if (GRID(state, is->x, is->y) & G_MARK) {            \
1675     /* island full, don't try fixing it */           \
1676     continue;                                        \
1677 } } while(0)
1678
1679 static int solve_sub(game_state *state, int difficulty, int depth)
1680 {
1681     struct island *is;
1682     int i, didsth;
1683
1684     while (1) {
1685         didsth = 0;
1686
1687         /* First island iteration: things we can work out by looking at
1688          * properties of the island as a whole. */
1689         for (i = 0; i < state->n_islands; i++) {
1690             is = &state->islands[i];
1691             if (!solve_island_stage1(is, &didsth)) return 0;
1692         }
1693         if (didsth) continue;
1694         else if (difficulty < 1) break;
1695
1696         /* Second island iteration: thing we can work out by looking at
1697          * properties of individual island connections. */
1698         for (i = 0; i < state->n_islands; i++) {
1699             is = &state->islands[i];
1700             CONTINUE_IF_FULL;
1701             if (!solve_island_stage2(is, &didsth)) return 0;
1702         }
1703         if (didsth) continue;
1704         else if (difficulty < 2) break;
1705
1706         /* Third island iteration: things we can only work out by looking
1707          * at groups of islands. */
1708         for (i = 0; i < state->n_islands; i++) {
1709             is = &state->islands[i];
1710             if (!solve_island_stage3(is, &didsth)) return 0;
1711         }
1712         if (didsth) continue;
1713         else if (difficulty < 3) break;
1714
1715         /* If we can be bothered, write a recursive solver to finish here. */
1716         break;
1717     }
1718     if (map_check(state)) return 1; /* solved it */
1719     return 0;
1720 }
1721
1722 static void solve_for_hint(game_state *state)
1723 {
1724     map_group(state);
1725     solve_sub(state, 10, 0);
1726 }
1727
1728 static int solve_from_scratch(game_state *state, int difficulty)
1729 {
1730     map_clear(state);
1731     map_group(state);
1732     map_update_possibles(state);
1733     return solve_sub(state, difficulty, 0);
1734 }
1735
1736 /* --- New game functions --- */
1737
1738 static game_state *new_state(game_params *params)
1739 {
1740     game_state *ret = snew(game_state);
1741     int wh = params->w * params->h, i;
1742
1743     ret->w = params->w;
1744     ret->h = params->h;
1745     ret->allowloops = params->allowloops;
1746     ret->maxb = params->maxb;
1747     ret->params = *params;
1748
1749     ret->grid = snewn(wh, grid_type);
1750     memset(ret->grid, 0, GRIDSZ(ret));
1751     ret->scratch = snewn(wh, grid_type);
1752     memset(ret->scratch, 0, GRIDSZ(ret));
1753
1754     ret->wha = snewn(wh*N_WH_ARRAYS, char);
1755     memset(ret->wha, 0, wh*N_WH_ARRAYS*sizeof(char));
1756
1757     ret->possv = ret->wha;
1758     ret->possh = ret->wha + wh;
1759     ret->lines = ret->wha + wh*2;
1760     ret->maxv = ret->wha + wh*3;
1761     ret->maxh = ret->wha + wh*4;
1762
1763     memset(ret->maxv, ret->maxb, wh*sizeof(char));
1764     memset(ret->maxh, ret->maxb, wh*sizeof(char));
1765
1766     ret->islands = NULL;
1767     ret->n_islands = 0;
1768     ret->n_islands_alloc = 0;
1769
1770     ret->gridi = snewn(wh, struct island *);
1771     for (i = 0; i < wh; i++) ret->gridi[i] = NULL;
1772
1773     ret->solved = ret->completed = 0;
1774
1775     ret->solver = snew(struct solver_state);
1776     ret->solver->dsf = snew_dsf(wh);
1777     ret->solver->tmpdsf = snewn(wh, int);
1778
1779     ret->solver->refcount = 1;
1780
1781     return ret;
1782 }
1783
1784 static game_state *dup_game(game_state *state)
1785 {
1786     game_state *ret = snew(game_state);
1787     int wh = state->w*state->h;
1788
1789     ret->w = state->w;
1790     ret->h = state->h;
1791     ret->allowloops = state->allowloops;
1792     ret->maxb = state->maxb;
1793     ret->params = state->params;
1794
1795     ret->grid = snewn(wh, grid_type);
1796     memcpy(ret->grid, state->grid, GRIDSZ(ret));
1797     ret->scratch = snewn(wh, grid_type);
1798     memcpy(ret->scratch, state->scratch, GRIDSZ(ret));
1799
1800     ret->wha = snewn(wh*N_WH_ARRAYS, char);
1801     memcpy(ret->wha, state->wha, wh*N_WH_ARRAYS*sizeof(char));
1802
1803     ret->possv = ret->wha;
1804     ret->possh = ret->wha + wh;
1805     ret->lines = ret->wha + wh*2;
1806     ret->maxv = ret->wha + wh*3;
1807     ret->maxh = ret->wha + wh*4;
1808
1809     ret->islands = snewn(state->n_islands, struct island);
1810     memcpy(ret->islands, state->islands, state->n_islands * sizeof(struct island));
1811     ret->n_islands = ret->n_islands_alloc = state->n_islands;
1812
1813     ret->gridi = snewn(wh, struct island *);
1814     fixup_islands_for_realloc(ret);
1815
1816     ret->solved = state->solved;
1817     ret->completed = state->completed;
1818
1819     ret->solver = state->solver;
1820     ret->solver->refcount++;
1821
1822     return ret;
1823 }
1824
1825 static void free_game(game_state *state)
1826 {
1827     if (--state->solver->refcount <= 0) {
1828         sfree(state->solver->dsf);
1829         sfree(state->solver->tmpdsf);
1830         sfree(state->solver);
1831     }
1832
1833     sfree(state->islands);
1834     sfree(state->gridi);
1835
1836     sfree(state->wha);
1837
1838     sfree(state->scratch);
1839     sfree(state->grid);
1840     sfree(state);
1841 }
1842
1843 #define MAX_NEWISLAND_TRIES     50
1844 #define MIN_SENSIBLE_ISLANDS    3
1845
1846 #define ORDER(a,b) do { if (a < b) { int tmp=a; int a=b; int b=tmp; } } while(0)
1847
1848 static char *new_game_desc(game_params *params, random_state *rs,
1849                            char **aux, int interactive)
1850 {
1851     game_state *tobuild  = NULL;
1852     int i, j, wh = params->w * params->h, x, y, dx, dy;
1853     int minx, miny, maxx, maxy, joinx, joiny, newx, newy, diffx, diffy;
1854     int ni_req = max((params->islands * wh) / 100, MIN_SENSIBLE_ISLANDS), ni_curr, ni_bad;
1855     struct island *is, *is2;
1856     char *ret;
1857     unsigned int echeck;
1858
1859     /* pick a first island position randomly. */
1860 generate:
1861     if (tobuild) free_game(tobuild);
1862     tobuild = new_state(params);
1863
1864     x = random_upto(rs, params->w);
1865     y = random_upto(rs, params->h);
1866     island_add(tobuild, x, y, 0);
1867     ni_curr = 1;
1868     ni_bad = 0;
1869     debug(("Created initial island at (%d,%d).\n", x, y));
1870
1871     while (ni_curr < ni_req) {
1872         /* Pick a random island to try and extend from. */
1873         i = random_upto(rs, tobuild->n_islands);
1874         is = &tobuild->islands[i];
1875
1876         /* Pick a random direction to extend in. */
1877         j = random_upto(rs, is->adj.npoints);
1878         dx = is->adj.points[j].x - is->x;
1879         dy = is->adj.points[j].y - is->y;
1880
1881         /* Find out limits of where we could put a new island. */
1882         joinx = joiny = -1;
1883         minx = is->x + 2*dx; miny = is->y + 2*dy; /* closest is 2 units away. */
1884         x = is->x+dx; y = is->y+dy;
1885         if (GRID(tobuild,x,y) & (G_LINEV|G_LINEH)) {
1886             /* already a line next to the island, continue. */
1887             goto bad;
1888         }
1889         while (1) {
1890             if (x < 0 || x >= params->w || y < 0 || y >= params->h) {
1891                 /* got past the edge; put a possible at the island
1892                  * and exit. */
1893                 maxx = x-dx; maxy = y-dy;
1894                 goto foundmax;
1895             }
1896             if (GRID(tobuild,x,y) & G_ISLAND) {
1897                 /* could join up to an existing island... */
1898                 joinx = x; joiny = y;
1899                 /* ... or make a new one 2 spaces away. */
1900                 maxx = x - 2*dx; maxy = y - 2*dy;
1901                 goto foundmax;
1902             } else if (GRID(tobuild,x,y) & (G_LINEV|G_LINEH)) {
1903                 /* could make a new one 1 space away from the line. */
1904                 maxx = x - dx; maxy = y - dy;
1905                 goto foundmax;
1906             }
1907             x += dx; y += dy;
1908         }
1909
1910 foundmax:
1911         debug(("Island at (%d,%d) with d(%d,%d) has new positions "
1912                "(%d,%d) -> (%d,%d), join (%d,%d).\n",
1913                is->x, is->y, dx, dy, minx, miny, maxx, maxy, joinx, joiny));
1914         /* Now we know where we could either put a new island
1915          * (between min and max), or (if loops are allowed) could join on
1916          * to an existing island (at join). */
1917         if (params->allowloops && joinx != -1 && joiny != -1) {
1918             if (random_upto(rs, 100) < (unsigned long)params->expansion) {
1919                 is2 = INDEX(tobuild, gridi, joinx, joiny);
1920                 debug(("Joining island at (%d,%d) to (%d,%d).\n",
1921                        is->x, is->y, is2->x, is2->y));
1922                 goto join;
1923             }
1924         }
1925         diffx = (maxx - minx) * dx;
1926         diffy = (maxy - miny) * dy;
1927         if (diffx < 0 || diffy < 0)  goto bad;
1928         if (random_upto(rs,100) < (unsigned long)params->expansion) {
1929             newx = maxx; newy = maxy;
1930             debug(("Creating new island at (%d,%d) (expanded).\n", newx, newy));
1931         } else {
1932             newx = minx + random_upto(rs,diffx+1)*dx;
1933             newy = miny + random_upto(rs,diffy+1)*dy;
1934             debug(("Creating new island at (%d,%d).\n", newx, newy));
1935         }
1936         /* check we're not next to island in the other orthogonal direction. */
1937         if ((INGRID(tobuild,newx+dy,newy+dx) && (GRID(tobuild,newx+dy,newy+dx) & G_ISLAND)) ||
1938             (INGRID(tobuild,newx-dy,newy-dx) && (GRID(tobuild,newx-dy,newy-dx) & G_ISLAND))) {
1939             debug(("New location is adjacent to island, skipping.\n"));
1940             goto bad;
1941         }
1942         is2 = island_add(tobuild, newx, newy, 0);
1943         /* Must get is again at this point; the array might have
1944          * been realloced by island_add... */
1945         is = &tobuild->islands[i]; /* ...but order will not change. */
1946
1947         ni_curr++; ni_bad = 0;
1948 join:
1949         island_join(is, is2, random_upto(rs, tobuild->maxb)+1, 0);
1950         debug_state(tobuild);
1951         continue;
1952
1953 bad:
1954         ni_bad++;
1955         if (ni_bad > MAX_NEWISLAND_TRIES) {
1956             debug(("Unable to create any new islands after %d tries; "
1957                    "created %d [%d%%] (instead of %d [%d%%] requested).\n",
1958                    MAX_NEWISLAND_TRIES,
1959                    ni_curr, ni_curr * 100 / wh,
1960                    ni_req, ni_req * 100 / wh));
1961             goto generated;
1962         }
1963     }
1964
1965 generated:
1966     if (ni_curr == 1) {
1967         debug(("Only generated one island (!), retrying.\n"));
1968         goto generate;
1969     }
1970     /* Check we have at least one island on each extremity of the grid. */
1971     echeck = 0;
1972     for (x = 0; x < params->w; x++) {
1973         if (INDEX(tobuild, gridi, x, 0))           echeck |= 1;
1974         if (INDEX(tobuild, gridi, x, params->h-1)) echeck |= 2;
1975     }
1976     for (y = 0; y < params->h; y++) {
1977         if (INDEX(tobuild, gridi, 0,           y)) echeck |= 4;
1978         if (INDEX(tobuild, gridi, params->w-1, y)) echeck |= 8;
1979     }
1980     if (echeck != 15) {
1981         debug(("Generated grid doesn't fill to sides, retrying.\n"));
1982         goto generate;
1983     }
1984
1985     map_count(tobuild);
1986     map_find_orthogonal(tobuild);
1987
1988     if (params->difficulty > 0) {
1989         if ((ni_curr > MIN_SENSIBLE_ISLANDS) &&
1990             (solve_from_scratch(tobuild, params->difficulty-1) > 0)) {
1991             debug(("Grid is solvable at difficulty %d (too easy); retrying.\n",
1992                    params->difficulty-1));
1993             goto generate;
1994         }
1995     }
1996
1997     if (solve_from_scratch(tobuild, params->difficulty) == 0) {
1998         debug(("Grid not solvable at difficulty %d, (too hard); retrying.\n",
1999                params->difficulty));
2000         goto generate;
2001     }
2002
2003     /* ... tobuild is now solved. We rely on this making the diff for aux. */
2004     debug_state(tobuild);
2005     ret = encode_game(tobuild);
2006     {
2007         game_state *clean = dup_game(tobuild);
2008         map_clear(clean);
2009         map_update_possibles(clean);
2010         *aux = game_state_diff(clean, tobuild);
2011         free_game(clean);
2012     }
2013     free_game(tobuild);
2014
2015     return ret;
2016 }
2017
2018 static char *validate_desc(game_params *params, char *desc)
2019 {
2020     int i, wh = params->w * params->h;
2021
2022     for (i = 0; i < wh; i++) {
2023         if (*desc >= '1' && *desc <= '9')
2024             /* OK */;
2025         else if (*desc >= 'a' && *desc <= 'z')
2026             i += *desc - 'a'; /* plus the i++ */
2027         else if (*desc >= 'A' && *desc <= 'G')
2028             /* OK */;
2029         else if (*desc == 'V' || *desc == 'W' ||
2030                  *desc == 'X' || *desc == 'Y' ||
2031                  *desc == 'H' || *desc == 'I' ||
2032                  *desc == 'J' || *desc == 'K')
2033             /* OK */;
2034         else if (!*desc)
2035             return "Game description shorter than expected";
2036         else
2037             return "Game description containers unexpected character";
2038         desc++;
2039     }
2040     if (*desc || i > wh)
2041         return "Game description longer than expected";
2042
2043     return NULL;
2044 }
2045
2046 static game_state *new_game_sub(game_params *params, char *desc)
2047 {
2048     game_state *state = new_state(params);
2049     int x, y, run = 0;
2050
2051     debug(("new_game[_sub]: desc = '%s'.\n", desc));
2052
2053     for (y = 0; y < params->h; y++) {
2054         for (x = 0; x < params->w; x++) {
2055             char c = '\0';
2056
2057             if (run == 0) {
2058                 c = *desc++;
2059                 assert(c != 'S');
2060                 if (c >= 'a' && c <= 'z')
2061                     run = c - 'a' + 1;
2062             }
2063
2064             if (run > 0) {
2065                 c = 'S';
2066                 run--;
2067             }
2068
2069             switch (c) {
2070             case '1': case '2': case '3': case '4':
2071             case '5': case '6': case '7': case '8': case '9':
2072                 island_add(state, x, y, (c - '0'));
2073                 break;
2074
2075             case 'A': case 'B': case 'C': case 'D':
2076             case 'E': case 'F': case 'G':
2077                 island_add(state, x, y, (c - 'A') + 10);
2078                 break;
2079
2080             case 'S':
2081                 /* empty square */
2082                 break;
2083
2084             default:
2085                 assert(!"Malformed desc.");
2086                 break;
2087             }
2088         }
2089     }
2090     if (*desc) assert(!"Over-long desc.");
2091
2092     map_find_orthogonal(state);
2093     map_update_possibles(state);
2094
2095     return state;
2096 }
2097
2098 static game_state *new_game(midend *me, game_params *params, char *desc)
2099 {
2100     return new_game_sub(params, desc);
2101 }
2102
2103 struct game_ui {
2104     int dragx_src, dragy_src;   /* source; -1 means no drag */
2105     int dragx_dst, dragy_dst;   /* src's closest orth island. */
2106     grid_type todraw;
2107     int dragging, drag_is_noline, nlines;
2108
2109     int cur_x, cur_y, cur_visible;      /* cursor position */
2110     int show_hints;
2111 };
2112
2113 static char *ui_cancel_drag(game_ui *ui)
2114 {
2115     ui->dragx_src = ui->dragy_src = -1;
2116     ui->dragx_dst = ui->dragy_dst = -1;
2117     ui->dragging = 0;
2118     return "";
2119 }
2120
2121 static game_ui *new_ui(game_state *state)
2122 {
2123     game_ui *ui = snew(game_ui);
2124     ui_cancel_drag(ui);
2125     ui->cur_x = state->islands[0].x;
2126     ui->cur_y = state->islands[0].y;
2127     ui->cur_visible = 0;
2128     ui->show_hints = 0;
2129     return ui;
2130 }
2131
2132 static void free_ui(game_ui *ui)
2133 {
2134     sfree(ui);
2135 }
2136
2137 static char *encode_ui(game_ui *ui)
2138 {
2139     return NULL;
2140 }
2141
2142 static void decode_ui(game_ui *ui, char *encoding)
2143 {
2144 }
2145
2146 static void game_changed_state(game_ui *ui, game_state *oldstate,
2147                                game_state *newstate)
2148 {
2149 }
2150
2151 struct game_drawstate {
2152     int tilesize;
2153     int w, h;
2154     grid_type *grid;
2155     int *lv, *lh;
2156     int started, dragging;
2157     int show_hints;
2158 };
2159
2160 static char *update_drag_dst(game_state *state, game_ui *ui, game_drawstate *ds,
2161                             int nx, int ny)
2162 {
2163     int ox, oy, dx, dy, i, currl, maxb;
2164     struct island *is;
2165     grid_type gtype, ntype, mtype, curr;
2166
2167     if (ui->dragx_src == -1 || ui->dragy_src == -1) return NULL;
2168
2169     ui->dragx_dst = -1;
2170     ui->dragy_dst = -1;
2171
2172     /* work out which of the four directions we're closest to... */
2173     ox = COORD(ui->dragx_src) + TILE_SIZE/2;
2174     oy = COORD(ui->dragy_src) + TILE_SIZE/2;
2175
2176     if (abs(nx-ox) < abs(ny-oy)) {
2177         dx = 0;
2178         dy = (ny-oy) < 0 ? -1 : 1;
2179         gtype = G_LINEV; ntype = G_NOLINEV; mtype = G_MARKV;
2180         maxb = INDEX(state, maxv, ui->dragx_src+dx, ui->dragy_src+dy);
2181     } else {
2182         dy = 0;
2183         dx = (nx-ox) < 0 ? -1 : 1;
2184         gtype = G_LINEH; ntype = G_NOLINEH; mtype = G_MARKH;
2185         maxb = INDEX(state, maxh, ui->dragx_src+dx, ui->dragy_src+dy);
2186     }
2187     if (ui->drag_is_noline) {
2188         ui->todraw = ntype;
2189     } else {
2190         curr = GRID(state, ui->dragx_src+dx, ui->dragy_src+dy);
2191         currl = INDEX(state, lines, ui->dragx_src+dx, ui->dragy_src+dy);
2192
2193         if (curr & gtype) {
2194             if (currl == maxb) {
2195                 ui->todraw = 0;
2196                 ui->nlines = 0;
2197             } else {
2198                 ui->todraw = gtype;
2199                 ui->nlines = currl + 1;
2200             }
2201         } else {
2202             ui->todraw = gtype;
2203             ui->nlines = 1;
2204         }
2205     }
2206
2207     /* ... and see if there's an island off in that direction. */
2208     is = INDEX(state, gridi, ui->dragx_src, ui->dragy_src);
2209     for (i = 0; i < is->adj.npoints; i++) {
2210         if (is->adj.points[i].off == 0) continue;
2211         curr = GRID(state, is->x+dx, is->y+dy);
2212         if (curr & mtype) continue; /* don't allow changes to marked lines. */
2213         if (ui->drag_is_noline) {
2214             if (curr & gtype) continue; /* no no-line where already a line */
2215         } else {
2216             if (POSSIBLES(state, dx, is->x+dx, is->y+dy) == 0) continue; /* no line if !possible. */
2217             if (curr & ntype) continue; /* can't have a bridge where there's a no-line. */
2218         }
2219
2220         if (is->adj.points[i].dx == dx &&
2221             is->adj.points[i].dy == dy) {
2222             ui->dragx_dst = ISLAND_ORTHX(is,i);
2223             ui->dragy_dst = ISLAND_ORTHY(is,i);
2224         }
2225     }
2226     /*debug(("update_drag src (%d,%d) d(%d,%d) dst (%d,%d)\n",
2227            ui->dragx_src, ui->dragy_src, dx, dy,
2228            ui->dragx_dst, ui->dragy_dst));*/
2229     return "";
2230 }
2231
2232 static char *finish_drag(game_state *state, game_ui *ui)
2233 {
2234     char buf[80];
2235
2236     if (ui->dragx_src == -1 || ui->dragy_src == -1)
2237         return NULL;
2238     if (ui->dragx_dst == -1 || ui->dragy_dst == -1)
2239         return ui_cancel_drag(ui);
2240
2241     if (ui->drag_is_noline) {
2242         sprintf(buf, "N%d,%d,%d,%d",
2243                 ui->dragx_src, ui->dragy_src,
2244                 ui->dragx_dst, ui->dragy_dst);
2245     } else {
2246         sprintf(buf, "L%d,%d,%d,%d,%d",
2247                 ui->dragx_src, ui->dragy_src,
2248                 ui->dragx_dst, ui->dragy_dst, ui->nlines);
2249     }
2250
2251     ui_cancel_drag(ui);
2252
2253     return dupstr(buf);
2254 }
2255
2256 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2257                             int x, int y, int button)
2258 {
2259     int gx = FROMCOORD(x), gy = FROMCOORD(y);
2260     char buf[80], *ret;
2261     grid_type ggrid = INGRID(state,gx,gy) ? GRID(state,gx,gy) : 0;
2262
2263     if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
2264         if (!INGRID(state, gx, gy)) return NULL;
2265         ui->cur_visible = 0;
2266         if ((ggrid & G_ISLAND) && !(ggrid & G_MARK)) {
2267             ui->dragx_src = gx;
2268             ui->dragy_src = gy;
2269             return "";
2270         } else
2271             return ui_cancel_drag(ui);
2272     } else if (button == LEFT_DRAG || button == RIGHT_DRAG) {
2273         if (gx != ui->dragx_src || gy != ui->dragy_src) {
2274             ui->dragging = 1;
2275             ui->drag_is_noline = (button == RIGHT_DRAG) ? 1 : 0;
2276             return update_drag_dst(state, ui, ds, x, y);
2277         } else {
2278             /* cancel a drag when we go back to the starting point */
2279             ui->dragx_dst = -1;
2280             ui->dragy_dst = -1;
2281             return "";
2282         }
2283     } else if (button == LEFT_RELEASE || button == RIGHT_RELEASE) {
2284         if (ui->dragging) {
2285             return finish_drag(state, ui);
2286         } else {
2287             ui_cancel_drag(ui);
2288             if (!INGRID(state, gx, gy)) return NULL;
2289             if (!(GRID(state, gx, gy) & G_ISLAND)) return NULL;
2290             sprintf(buf, "M%d,%d", gx, gy);
2291             return dupstr(buf);
2292         }
2293     } else if (button == 'h' || button == 'H') {
2294         game_state *solved = dup_game(state);
2295         solve_for_hint(solved);
2296         ret = game_state_diff(state, solved);
2297         free_game(solved);
2298         return ret;
2299     } else if (IS_CURSOR_MOVE(button)) {
2300         ui->cur_visible = 1;
2301         if (ui->dragging) {
2302             int nx = ui->cur_x, ny = ui->cur_y;
2303
2304             move_cursor(button, &nx, &ny, state->w, state->h, 0);
2305             update_drag_dst(state, ui, ds,
2306                              COORD(nx)+TILE_SIZE/2,
2307                              COORD(ny)+TILE_SIZE/2);
2308             return finish_drag(state, ui);
2309         } else {
2310             int dx = (button == CURSOR_RIGHT) ? +1 : (button == CURSOR_LEFT) ? -1 : 0;
2311             int dy = (button == CURSOR_DOWN)  ? +1 : (button == CURSOR_UP)   ? -1 : 0;
2312             int dorthx = 1 - abs(dx), dorthy = 1 - abs(dy);
2313             int dir, orth, nx = x, ny = y;
2314
2315             /* 'orthorder' is a tweak to ensure that if you press RIGHT and
2316              * happen to move upwards, when you press LEFT you then tend
2317              * downwards (rather than upwards again). */
2318             int orthorder = (button == CURSOR_LEFT || button == CURSOR_UP) ? 1 : -1;
2319
2320             /* This attempts to find an island in the direction you're
2321              * asking for, broadly speaking. If you ask to go right, for
2322              * example, it'll look for islands to the right and slightly
2323              * above or below your current horiz. position, allowing
2324              * further above/below the further away it searches. */
2325
2326             assert(GRID(state, ui->cur_x, ui->cur_y) & G_ISLAND);
2327             /* currently this is depth-first (so orthogonally-adjacent
2328              * islands across the other side of the grid will be moved to
2329              * before closer islands slightly offset). Swap the order of
2330              * these two loops to change to breadth-first search. */
2331             for (orth = 0; ; orth++) {
2332                 int oingrid = 0;
2333                 for (dir = 1; ; dir++) {
2334                     int dingrid = 0;
2335
2336                     if (orth > dir) continue; /* only search in cone outwards. */
2337
2338                     nx = ui->cur_x + dir*dx + orth*dorthx*orthorder;
2339                     ny = ui->cur_y + dir*dy + orth*dorthy*orthorder;
2340                     if (INGRID(state, nx, ny)) {
2341                         dingrid = oingrid = 1;
2342                         if (GRID(state, nx, ny) & G_ISLAND) goto found;
2343                     }
2344
2345                     nx = ui->cur_x + dir*dx - orth*dorthx*orthorder;
2346                     ny = ui->cur_y + dir*dy - orth*dorthy*orthorder;
2347                     if (INGRID(state, nx, ny)) {
2348                         dingrid = oingrid = 1;
2349                         if (GRID(state, nx, ny) & G_ISLAND) goto found;
2350                     }
2351
2352                     if (!dingrid) break;
2353                 }
2354                 if (!oingrid) return "";
2355             }
2356             /* not reached */
2357
2358 found:
2359             ui->cur_x = nx;
2360             ui->cur_y = ny;
2361             return "";
2362         }
2363     } else if (IS_CURSOR_SELECT(button)) {
2364         if (!ui->cur_visible) {
2365             ui->cur_visible = 1;
2366             return "";
2367         }
2368         if (ui->dragging) {
2369             ui_cancel_drag(ui);
2370             if (ui->dragx_dst == -1 && ui->dragy_dst == -1) {
2371                 sprintf(buf, "M%d,%d", ui->cur_x, ui->cur_y);
2372                 return dupstr(buf);
2373             } else
2374                 return "";
2375         } else {
2376             grid_type v = GRID(state, ui->cur_x, ui->cur_y);
2377             if (v & G_ISLAND) {
2378                 ui->dragging = 1;
2379                 ui->dragx_src = ui->cur_x;
2380                 ui->dragy_src = ui->cur_y;
2381                 ui->dragx_dst = ui->dragy_dst = -1;
2382                 ui->drag_is_noline = (button == CURSOR_SELECT2) ? 1 : 0;
2383                 return "";
2384             }
2385         }
2386     } else if (button == 'g' || button == 'G') {
2387         ui->show_hints = 1 - ui->show_hints;
2388         return "";
2389     }
2390
2391     return NULL;
2392 }
2393
2394 static game_state *execute_move(game_state *state, char *move)
2395 {
2396     game_state *ret = dup_game(state);
2397     int x1, y1, x2, y2, nl, n;
2398     struct island *is1, *is2;
2399     char c;
2400
2401     debug(("execute_move: %s\n", move));
2402
2403     if (!*move) goto badmove;
2404     while (*move) {
2405         c = *move++;
2406         if (c == 'S') {
2407             ret->solved = TRUE;
2408             n = 0;
2409         } else if (c == 'L') {
2410             if (sscanf(move, "%d,%d,%d,%d,%d%n",
2411                        &x1, &y1, &x2, &y2, &nl, &n) != 5)
2412                 goto badmove;
2413             if (!INGRID(ret, x1, y1) || !INGRID(ret, x2, y2))
2414                 goto badmove;
2415             is1 = INDEX(ret, gridi, x1, y1);
2416             is2 = INDEX(ret, gridi, x2, y2);
2417             if (!is1 || !is2) goto badmove;
2418             if (nl < 0 || nl > state->maxb) goto badmove;
2419             island_join(is1, is2, nl, 0);
2420         } else if (c == 'N') {
2421             if (sscanf(move, "%d,%d,%d,%d%n",
2422                        &x1, &y1, &x2, &y2, &n) != 4)
2423                 goto badmove;
2424             if (!INGRID(ret, x1, y1) || !INGRID(ret, x2, y2))
2425                 goto badmove;
2426             is1 = INDEX(ret, gridi, x1, y1);
2427             is2 = INDEX(ret, gridi, x2, y2);
2428             if (!is1 || !is2) goto badmove;
2429             island_join(is1, is2, -1, 0);
2430         } else if (c == 'M') {
2431             if (sscanf(move, "%d,%d%n",
2432                        &x1, &y1, &n) != 2)
2433                 goto badmove;
2434             if (!INGRID(ret, x1, y1))
2435                 goto badmove;
2436             is1 = INDEX(ret, gridi, x1, y1);
2437             if (!is1) goto badmove;
2438             island_togglemark(is1);
2439         } else
2440             goto badmove;
2441
2442         move += n;
2443         if (*move == ';')
2444             move++;
2445         else if (*move) goto badmove;
2446     }
2447
2448     map_update_possibles(ret);
2449     if (map_check(ret)) {
2450         debug(("Game completed.\n"));
2451         ret->completed = 1;
2452     }
2453     return ret;
2454
2455 badmove:
2456     debug(("%s: unrecognised move.\n", move));
2457     free_game(ret);
2458     return NULL;
2459 }
2460
2461 static char *solve_game(game_state *state, game_state *currstate,
2462                         char *aux, char **error)
2463 {
2464     char *ret;
2465     game_state *solved;
2466
2467     if (aux) {
2468         debug(("solve_game: aux = %s\n", aux));
2469         solved = execute_move(state, aux);
2470         if (!solved) {
2471             *error = "Generated aux string is not a valid move (!).";
2472             return NULL;
2473         }
2474     } else {
2475         solved = dup_game(state);
2476         /* solve with max strength... */
2477         if (solve_from_scratch(solved, 10) == 0) {
2478             free_game(solved);
2479             *error = "Game does not have a (non-recursive) solution.";
2480             return NULL;
2481         }
2482     }
2483     ret = game_state_diff(currstate, solved);
2484     free_game(solved);
2485     debug(("solve_game: ret = %s\n", ret));
2486     return ret;
2487 }
2488
2489 /* ----------------------------------------------------------------------
2490  * Drawing routines.
2491  */
2492
2493 static void game_compute_size(game_params *params, int tilesize,
2494                               int *x, int *y)
2495 {
2496     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2497     struct { int tilesize; } ads, *ds = &ads;
2498     ads.tilesize = tilesize;
2499
2500     *x = TILE_SIZE * params->w + 2 * BORDER;
2501     *y = TILE_SIZE * params->h + 2 * BORDER;
2502 }
2503
2504 static void game_set_size(drawing *dr, game_drawstate *ds,
2505                           game_params *params, int tilesize)
2506 {
2507     ds->tilesize = tilesize;
2508 }
2509
2510 static float *game_colours(frontend *fe, int *ncolours)
2511 {
2512     float *ret = snewn(3 * NCOLOURS, float);
2513     int i;
2514
2515     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
2516
2517     for (i = 0; i < 3; i++) {
2518         ret[COL_FOREGROUND * 3 + i] = 0.0F;
2519         ret[COL_HINT * 3 + i] = ret[COL_LOWLIGHT * 3 + i];
2520         ret[COL_GRID * 3 + i] =
2521             (ret[COL_HINT * 3 + i] + ret[COL_BACKGROUND * 3 + i]) * 0.5F;
2522         ret[COL_MARK * 3 + i] = ret[COL_HIGHLIGHT * 3 + i];
2523     }
2524     ret[COL_WARNING * 3 + 0] = 1.0F;
2525     ret[COL_WARNING * 3 + 1] = 0.25F;
2526     ret[COL_WARNING * 3 + 2] = 0.25F;
2527
2528     ret[COL_SELECTED * 3 + 0] = 0.25F;
2529     ret[COL_SELECTED * 3 + 1] = 1.00F;
2530     ret[COL_SELECTED * 3 + 2] = 0.25F;
2531
2532     ret[COL_CURSOR * 3 + 0] = min(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
2533     ret[COL_CURSOR * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.8F;
2534     ret[COL_CURSOR * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 0.8F;
2535
2536     *ncolours = NCOLOURS;
2537     return ret;
2538 }
2539
2540 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2541 {
2542     struct game_drawstate *ds = snew(struct game_drawstate);
2543     int wh = state->w*state->h;
2544
2545     ds->tilesize = 0;
2546     ds->w = state->w;
2547     ds->h = state->h;
2548     ds->started = 0;
2549     ds->grid = snewn(wh, grid_type);
2550     memset(ds->grid, -1, wh*sizeof(grid_type));
2551     ds->lv = snewn(wh, int);
2552     ds->lh = snewn(wh, int);
2553     memset(ds->lv, 0, wh*sizeof(int));
2554     memset(ds->lh, 0, wh*sizeof(int));
2555     ds->show_hints = 0;
2556
2557     return ds;
2558 }
2559
2560 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2561 {
2562     sfree(ds->lv);
2563     sfree(ds->lh);
2564     sfree(ds->grid);
2565     sfree(ds);
2566 }
2567
2568 #define LINE_WIDTH (TILE_SIZE/8)
2569 #define TS8(x) (((x)*TILE_SIZE)/8)
2570
2571 #define OFFSET(thing) ((TILE_SIZE/2) - ((thing)/2))
2572
2573 static void lines_vert(drawing *dr, game_drawstate *ds,
2574                        int ox, int oy, int lv, int col, grid_type v)
2575 {
2576     int lw = LINE_WIDTH, gw = LINE_WIDTH, bw, i, loff;
2577     while ((bw = lw * lv + gw * (lv+1)) > TILE_SIZE)
2578         gw--;
2579     loff = OFFSET(bw);
2580     if (v & G_MARKV)
2581         draw_rect(dr, ox + loff, oy, bw, TILE_SIZE, COL_MARK);
2582     for (i = 0; i < lv; i++, loff += lw + gw)
2583         draw_rect(dr, ox + loff + gw, oy, lw, TILE_SIZE, col);
2584 }
2585
2586 static void lines_horiz(drawing *dr, game_drawstate *ds,
2587                         int ox, int oy, int lh, int col, grid_type v)
2588 {
2589     int lw = LINE_WIDTH, gw = LINE_WIDTH, bw, i, loff;
2590     while ((bw = lw * lh + gw * (lh+1)) > TILE_SIZE)
2591         gw--;
2592     loff = OFFSET(bw);
2593     if (v & G_MARKH)
2594         draw_rect(dr, ox, oy + loff, TILE_SIZE, bw, COL_MARK);
2595     for (i = 0; i < lh; i++, loff += lw + gw)
2596         draw_rect(dr, ox, oy + loff + gw, TILE_SIZE, lw, col);
2597 }
2598
2599 static void line_cross(drawing *dr, game_drawstate *ds,
2600                       int ox, int oy, int col, grid_type v)
2601 {
2602     int off = TS8(2);
2603     draw_line(dr, ox,     oy, ox+off, oy+off, col);
2604     draw_line(dr, ox+off, oy, ox,     oy+off, col);
2605 }
2606
2607 static int between_island(game_state *state, int sx, int sy, int dx, int dy)
2608 {
2609     int x = sx - dx, y = sy - dy;
2610
2611     while (INGRID(state, x, y)) {
2612         if (GRID(state, x, y) & G_ISLAND) goto found;
2613         x -= dx; y -= dy;
2614     }
2615     return 0;
2616 found:
2617     x = sx + dx, y = sy + dy;
2618     while (INGRID(state, x, y)) {
2619         if (GRID(state, x, y) & G_ISLAND) return 1;
2620         x += dx; y += dy;
2621     }
2622     return 0;
2623 }
2624
2625 static void lines_lvlh(game_state *state, game_ui *ui, int x, int y, grid_type v,
2626                        int *lv_r, int *lh_r)
2627 {
2628     int lh = 0, lv = 0;
2629
2630     if (v & G_LINEV) lv = INDEX(state,lines,x,y);
2631     if (v & G_LINEH) lh = INDEX(state,lines,x,y);
2632
2633     if (ui->show_hints) {
2634         if (between_island(state, x, y, 0, 1) && !lv) lv = 1;
2635         if (between_island(state, x, y, 1, 0) && !lh) lh = 1;
2636     }
2637     /*debug(("lvlh: (%d,%d) v 0x%x lv %d lh %d.\n", x, y, v, lv, lh));*/
2638     *lv_r = lv; *lh_r = lh;
2639 }
2640
2641 static void dsf_debug_draw(drawing *dr,
2642                            game_state *state, game_drawstate *ds,
2643                            int x, int y)
2644 {
2645 #ifdef DRAW_DSF
2646     int ts = TILE_SIZE/2;
2647     int ox = COORD(x) + ts/2, oy = COORD(y) + ts/2;
2648     char str[32];
2649
2650     sprintf(str, "%d", dsf_canonify(state->solver->dsf, DINDEX(x,y)));
2651     draw_text(dr, ox, oy, FONT_VARIABLE, ts,
2652               ALIGN_VCENTRE | ALIGN_HCENTRE, COL_WARNING, str);
2653 #endif
2654 }
2655
2656 static void lines_redraw(drawing *dr,
2657                          game_state *state, game_drawstate *ds, game_ui *ui,
2658                          int x, int y, grid_type v, int lv, int lh)
2659 {
2660     int ox = COORD(x), oy = COORD(y);
2661     int vcol = (v & G_FLASH) ? COL_HIGHLIGHT :
2662         (v & G_WARN) ? COL_WARNING : COL_FOREGROUND, hcol = vcol;
2663     grid_type todraw = v & G_NOLINE;
2664
2665     if (v & G_ISSEL) {
2666         if (ui->todraw & G_FLAGSH) hcol = COL_SELECTED;
2667         if (ui->todraw & G_FLAGSV) vcol = COL_SELECTED;
2668         todraw |= ui->todraw;
2669     }
2670
2671     draw_rect(dr, ox, oy, TILE_SIZE, TILE_SIZE, COL_BACKGROUND);
2672     /*if (v & G_CURSOR)
2673         draw_rect(dr, ox+TILE_SIZE/4, oy+TILE_SIZE/4,
2674                   TILE_SIZE/2, TILE_SIZE/2, COL_CURSOR);*/
2675
2676
2677     if (ui->show_hints) {
2678         if (between_island(state, x, y, 0, 1) && !(v & G_LINEV))
2679             vcol = COL_HINT;
2680         if (between_island(state, x, y, 1, 0) && !(v & G_LINEH))
2681             hcol = COL_HINT;
2682     }
2683 #ifdef DRAW_GRID
2684     draw_rect_outline(dr, ox, oy, TILE_SIZE, TILE_SIZE, COL_GRID);
2685 #endif
2686
2687     if (todraw & G_NOLINEV) {
2688         line_cross(dr, ds, ox + TS8(3), oy + TS8(1), vcol, todraw);
2689         line_cross(dr, ds, ox + TS8(3), oy + TS8(5), vcol, todraw);
2690     }
2691     if (todraw & G_NOLINEH) {
2692         line_cross(dr, ds, ox + TS8(1), oy + TS8(3), hcol, todraw);
2693         line_cross(dr, ds, ox + TS8(5), oy + TS8(3), hcol, todraw);
2694     }
2695     /* if we're drawing a real line and a hint, make sure we draw the real
2696      * line on top. */
2697     if (lv && vcol == COL_HINT) lines_vert(dr, ds, ox, oy, lv, vcol, v);
2698     if (lh) lines_horiz(dr, ds, ox, oy, lh, hcol, v);
2699     if (lv && vcol != COL_HINT) lines_vert(dr, ds, ox, oy, lv, vcol, v);
2700
2701     dsf_debug_draw(dr, state, ds, x, y);
2702     draw_update(dr, ox, oy, TILE_SIZE, TILE_SIZE);
2703 }
2704
2705 #define ISLAND_RADIUS ((TILE_SIZE*12)/20)
2706 #define ISLAND_NUMSIZE(is) \
2707     (((is)->count < 10) ? (TILE_SIZE*7)/10 : (TILE_SIZE*5)/10)
2708
2709 static void island_redraw(drawing *dr,
2710                           game_state *state, game_drawstate *ds,
2711                           struct island *is, grid_type v)
2712 {
2713     /* These overlap the edges of their squares, which is why they're drawn later.
2714      * We know they can't overlap each other because they're not allowed within 2
2715      * squares of each other. */
2716     int half = TILE_SIZE/2;
2717     int ox = COORD(is->x) + half, oy = COORD(is->y) + half;
2718     int orad = ISLAND_RADIUS, irad = orad - LINE_WIDTH;
2719     int updatesz = orad*2+1;
2720     int tcol = (v & G_FLASH) ? COL_HIGHLIGHT :
2721               (v & G_WARN)  ? COL_WARNING : COL_FOREGROUND;
2722     int col = (v & G_ISSEL) ? COL_SELECTED : tcol;
2723     int bg = (v & G_CURSOR) ? COL_CURSOR :
2724         (v & G_MARK) ? COL_MARK : COL_BACKGROUND;
2725     char str[32];
2726
2727 #ifdef DRAW_GRID
2728     draw_rect_outline(dr, COORD(is->x), COORD(is->y),
2729                       TILE_SIZE, TILE_SIZE, COL_GRID);
2730 #endif
2731
2732     /* draw a thick circle */
2733     draw_circle(dr, ox, oy, orad, col, col);
2734     draw_circle(dr, ox, oy, irad, bg, bg);
2735
2736     sprintf(str, "%d", is->count);
2737     draw_text(dr, ox, oy, FONT_VARIABLE, ISLAND_NUMSIZE(is),
2738               ALIGN_VCENTRE | ALIGN_HCENTRE, tcol, str);
2739
2740     dsf_debug_draw(dr, state, ds, is->x, is->y);
2741     draw_update(dr, ox - orad, oy - orad, updatesz, updatesz);
2742 }
2743
2744 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2745                         game_state *state, int dir, game_ui *ui,
2746                         float animtime, float flashtime)
2747 {
2748     int x, y, force = 0, i, j, redraw, lv, lh;
2749     grid_type v, dsv, flash = 0;
2750     struct island *is, *is_drag_src = NULL, *is_drag_dst = NULL;
2751
2752     if (flashtime) {
2753         int f = (int)(flashtime * 5 / FLASH_TIME);
2754         if (f == 1 || f == 3) flash = G_FLASH;
2755     }
2756
2757     /* Clear screen, if required. */
2758     if (!ds->started) {
2759         draw_rect(dr, 0, 0,
2760                   TILE_SIZE * ds->w + 2 * BORDER,
2761                   TILE_SIZE * ds->h + 2 * BORDER, COL_BACKGROUND);
2762 #ifdef DRAW_GRID
2763         draw_rect_outline(dr,
2764                           COORD(0)-1, COORD(0)-1,
2765                           TILE_SIZE * ds->w + 2, TILE_SIZE * ds->h + 2,
2766                           COL_GRID);
2767 #endif
2768         draw_update(dr, 0, 0,
2769                     TILE_SIZE * ds->w + 2 * BORDER,
2770                     TILE_SIZE * ds->h + 2 * BORDER);
2771         ds->started = 1;
2772         force = 1;
2773     }
2774
2775     if (ui->dragx_src != -1 && ui->dragy_src != -1) {
2776         ds->dragging = 1;
2777         is_drag_src = INDEX(state, gridi, ui->dragx_src, ui->dragy_src);
2778         assert(is_drag_src);
2779         if (ui->dragx_dst != -1 && ui->dragy_dst != -1) {
2780             is_drag_dst = INDEX(state, gridi, ui->dragx_dst, ui->dragy_dst);
2781             assert(is_drag_dst);
2782         }
2783     } else
2784         ds->dragging = 0;
2785
2786     if (ui->show_hints != ds->show_hints) {
2787         force = 1;
2788         ds->show_hints = ui->show_hints;
2789     }
2790
2791     /* Draw all lines (and hints, if we want), but *not* islands. */
2792     for (x = 0; x < ds->w; x++) {
2793         for (y = 0; y < ds->h; y++) {
2794             v = GRID(state, x, y) | flash;
2795             dsv = GRID(ds,x,y) & ~G_REDRAW;
2796
2797             if (v & G_ISLAND) continue;
2798
2799             if (is_drag_dst) {
2800                 if (WITHIN(x,is_drag_src->x, is_drag_dst->x) &&
2801                     WITHIN(y,is_drag_src->y, is_drag_dst->y))
2802                     v |= G_ISSEL;
2803             }
2804             lines_lvlh(state, ui, x, y, v, &lv, &lh);
2805
2806             /*if (ui->cur_visible && ui->cur_x == x && ui->cur_y == y)
2807                 v |= G_CURSOR;*/
2808
2809             if (v != dsv ||
2810                 lv != INDEX(ds,lv,x,y) ||
2811                 lh != INDEX(ds,lh,x,y) ||
2812                 force) {
2813                 GRID(ds, x, y) = v | G_REDRAW;
2814                 INDEX(ds,lv,x,y) = lv;
2815                 INDEX(ds,lh,x,y) = lh;
2816                 lines_redraw(dr, state, ds, ui, x, y, v, lv, lh);
2817             } else
2818                 GRID(ds,x,y) &= ~G_REDRAW;
2819         }
2820     }
2821
2822     /* Draw islands. */
2823     for (i = 0; i < state->n_islands; i++) {
2824         is = &state->islands[i];
2825         v = GRID(state, is->x, is->y) | flash;
2826
2827         redraw = 0;
2828         for (j = 0; j < is->adj.npoints; j++) {
2829             if (GRID(ds,is->adj.points[j].x,is->adj.points[j].y) & G_REDRAW) {
2830                 redraw = 1;
2831             }
2832         }
2833
2834         if (is_drag_src) {
2835             if (is == is_drag_src)
2836                 v |= G_ISSEL;
2837             else if (is_drag_dst && is == is_drag_dst)
2838                 v |= G_ISSEL;
2839         }
2840
2841         if (island_impossible(is, v & G_MARK)) v |= G_WARN;
2842
2843         if (ui->cur_visible && ui->cur_x == is->x && ui->cur_y == is->y)
2844             v |= G_CURSOR;
2845
2846         if ((v != GRID(ds, is->x, is->y)) || force || redraw) {
2847             GRID(ds,is->x,is->y) = v;
2848             island_redraw(dr, state, ds, is, v);
2849         }
2850     }
2851 }
2852
2853 static float game_anim_length(game_state *oldstate, game_state *newstate,
2854                               int dir, game_ui *ui)
2855 {
2856     return 0.0F;
2857 }
2858
2859 static float game_flash_length(game_state *oldstate, game_state *newstate,
2860                                int dir, game_ui *ui)
2861 {
2862     if (!oldstate->completed && newstate->completed &&
2863         !oldstate->solved && !newstate->solved)
2864         return FLASH_TIME;
2865
2866     return 0.0F;
2867 }
2868
2869 static int game_status(game_state *state)
2870 {
2871     return state->completed ? +1 : 0;
2872 }
2873
2874 static int game_timing_state(game_state *state, game_ui *ui)
2875 {
2876     return TRUE;
2877 }
2878
2879 static void game_print_size(game_params *params, float *x, float *y)
2880 {
2881     int pw, ph;
2882
2883     /* 10mm squares by default. */
2884     game_compute_size(params, 1000, &pw, &ph);
2885     *x = pw / 100.0F;
2886     *y = ph / 100.0F;
2887 }
2888
2889 static void game_print(drawing *dr, game_state *state, int ts)
2890 {
2891     int ink = print_mono_colour(dr, 0);
2892     int paper = print_mono_colour(dr, 1);
2893     int x, y, cx, cy, i, nl;
2894     int loff;
2895     grid_type grid;
2896
2897     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2898     game_drawstate ads, *ds = &ads;
2899     ads.tilesize = ts;
2900
2901     /* I don't think this wants a border. */
2902
2903     /* Bridges */
2904     loff = ts / (8 * sqrt((state->params.maxb - 1)));
2905     print_line_width(dr, ts / 12);
2906     for (x = 0; x < state->w; x++) {
2907         for (y = 0; y < state->h; y++) {
2908             cx = COORD(x); cy = COORD(y);
2909             grid = GRID(state,x,y);
2910             nl = INDEX(state,lines,x,y);
2911
2912             if (grid & G_ISLAND) continue;
2913             if (grid & G_LINEV) {
2914                 for (i = 0; i < nl; i++)
2915                     draw_line(dr, cx+ts/2+(2*i-nl+1)*loff, cy,
2916                               cx+ts/2+(2*i-nl+1)*loff, cy+ts, ink);
2917             }
2918             if (grid & G_LINEH) {
2919                 for (i = 0; i < nl; i++)
2920                     draw_line(dr, cx, cy+ts/2+(2*i-nl+1)*loff,
2921                               cx+ts, cy+ts/2+(2*i-nl+1)*loff, ink);
2922             }
2923         }
2924     }
2925
2926     /* Islands */
2927     for (i = 0; i < state->n_islands; i++) {
2928         char str[32];
2929         struct island *is = &state->islands[i];
2930         grid = GRID(state, is->x, is->y);
2931         cx = COORD(is->x) + ts/2;
2932         cy = COORD(is->y) + ts/2;
2933
2934         draw_circle(dr, cx, cy, ISLAND_RADIUS, paper, ink);
2935
2936         sprintf(str, "%d", is->count);
2937         draw_text(dr, cx, cy, FONT_VARIABLE, ISLAND_NUMSIZE(is),
2938                   ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
2939     }
2940 }
2941
2942 #ifdef COMBINED
2943 #define thegame bridges
2944 #endif
2945
2946 const struct game thegame = {
2947     "Bridges", "games.bridges", "bridges",
2948     default_params,
2949     game_fetch_preset,
2950     decode_params,
2951     encode_params,
2952     free_params,
2953     dup_params,
2954     TRUE, game_configure, custom_params,
2955     validate_params,
2956     new_game_desc,
2957     validate_desc,
2958     new_game,
2959     dup_game,
2960     free_game,
2961     TRUE, solve_game,
2962     TRUE, game_can_format_as_text_now, game_text_format,
2963     new_ui,
2964     free_ui,
2965     encode_ui,
2966     decode_ui,
2967     game_changed_state,
2968     interpret_move,
2969     execute_move,
2970     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2971     game_colours,
2972     game_new_drawstate,
2973     game_free_drawstate,
2974     game_redraw,
2975     game_anim_length,
2976     game_flash_length,
2977     game_status,
2978     TRUE, FALSE, game_print_size, game_print,
2979     FALSE,                             /* wants_statusbar */
2980     FALSE, game_timing_state,
2981     REQUIRE_RBUTTON,                   /* flags */
2982 };
2983
2984 /* vim: set shiftwidth=4 tabstop=8: */