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