chiark / gitweb /
Handle replacing an existing arrow
[sgt-puzzles.git] / galaxies.c
1 /*
2  * galaxies.c: implementation of 'Tentai Show' from Nikoli,
3  *             also sometimes called 'Spiral Galaxies'.
4  *
5  * Notes:
6  *
7  * Grid is stored as size (2n-1), holding edges as well as spaces
8  * (and thus vertices too, at edge intersections).
9  *
10  * Any dot will thus be positioned at one of our grid points,
11  * which saves any faffing with half-of-a-square stuff.
12  *
13  * Edges have on/off state; obviously the actual edges of the
14  * board are fixed to on, and everything else starts as off.
15  *
16  * TTD:
17    * Cleverer solver
18    * Think about how to display remote groups of tiles?
19  *
20  * Bugs:
21  *
22  * Notable puzzle IDs:
23  *
24  * Nikoli's example [web site has wrong highlighting]
25  * (at http://www.nikoli.co.jp/en/puzzles/astronomical_show/):
26  *  5x5:eBbbMlaBbOEnf
27  *
28  * The 'spiral galaxies puzzles are NP-complete' paper
29  * (at http://www.stetson.edu/~efriedma/papers/spiral.pdf):
30  *  7x7:chpgdqqqoezdddki
31  *
32  * Puzzle competition pdf examples
33  * (at http://www.puzzleratings.org/Yurekli2006puz.pdf):
34  *  6x6:EDbaMucCohbrecEi
35  *  10x10:beFbufEEzowDlxldibMHezBQzCdcFzjlci
36  *  13x13:dCemIHFFkJajjgDfdbdBzdzEgjccoPOcztHjBczLDjczqktJjmpreivvNcggFi
37  *
38  */
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <assert.h>
44 #include <ctype.h>
45 #include <math.h>
46
47 #include "puzzles.h"
48
49 #ifdef DEBUGGING
50 #define solvep debug
51 #else
52 int solver_show_working;
53 #define solvep(x) do { if (solver_show_working) { printf x; } } while(0)
54 #endif
55
56 #ifdef STANDALONE_PICTURE_GENERATOR
57 /*
58  * Dirty hack to enable the generator to construct a game ID which
59  * solves to a specified black-and-white bitmap. We define a global
60  * variable here which gives the desired colour of each square, and
61  * we arrange that the grid generator never merges squares of
62  * different colours.
63  *
64  * The bitmap as stored here is a simple int array (at these sizes
65  * it isn't worth doing fiddly bit-packing). picture[y*w+x] is 1
66  * iff the pixel at (x,y) is intended to be black.
67  *
68  * (It might be nice to be able to specify some pixels as
69  * don't-care, to give the generator more leeway. But that might be
70  * fiddly.)
71  */
72 static int *picture;
73 #endif
74
75 enum {
76     COL_BACKGROUND,
77     COL_WHITEBG,
78     COL_BLACKBG,
79     COL_WHITEDOT,
80     COL_BLACKDOT,
81     COL_GRID,
82     COL_EDGE,
83     COL_ARROW,
84     COL_CURSOR,
85     NCOLOURS
86 };
87
88 #define DIFFLIST(A)             \
89     A(NORMAL,Normal,n)          \
90     A(UNREASONABLE,Unreasonable,u)
91
92 #define ENUM(upper,title,lower) DIFF_ ## upper,
93 #define TITLE(upper,title,lower) #title,
94 #define ENCODE(upper,title,lower) #lower
95 #define CONFIG(upper,title,lower) ":" #title
96 enum { DIFFLIST(ENUM)
97     DIFF_IMPOSSIBLE, DIFF_AMBIGUOUS, DIFF_UNFINISHED, DIFF_MAX };
98 static char const *const galaxies_diffnames[] = {
99     DIFFLIST(TITLE) "Impossible", "Ambiguous", "Unfinished" };
100 static char const galaxies_diffchars[] = DIFFLIST(ENCODE);
101 #define DIFFCONFIG DIFFLIST(CONFIG)
102
103 struct game_params {
104     /* X and Y is the area of the board as seen by
105      * the user, not the (2n+1) area the game uses. */
106     int w, h, diff;
107 };
108
109 enum { s_tile, s_edge, s_vertex };
110
111 #define F_DOT           1       /* there's a dot here */
112 #define F_EDGE_SET      2       /* the edge is set */
113 #define F_TILE_ASSOC    4       /* this tile is associated with a dot. */
114 #define F_DOT_BLACK     8       /* (ui only) dot is black. */
115 #define F_MARK          16      /* scratch flag */
116 #define F_REACHABLE     32
117 #define F_SCRATCH       64
118 #define F_MULTIPLE      128
119 #define F_DOT_HOLD      256
120 #define F_GOOD          512
121
122 typedef struct space {
123     int x, y;           /* its position */
124     int type;
125     unsigned int flags;
126     int dotx, doty;     /* if flags & F_TILE_ASSOC */
127     int nassoc;         /* if flags & F_DOT */
128 } space;
129
130 #define INGRID(s,x,y) ((x) >= 0 && (y) >= 0 &&                  \
131                        (x) < (state)->sx && (y) < (state)->sy)
132 #define INUI(s,x,y)   ((x) > 0 && (y) > 0 &&                  \
133                        (x) < ((state)->sx-1) && (y) < ((state)->sy-1))
134
135 #define GRID(s,g,x,y) ((s)->g[((y)*(s)->sx)+(x)])
136 #define SPACE(s,x,y) GRID(s,grid,x,y)
137
138 struct game_state {
139     int w, h;           /* size from params */
140     int sx, sy;         /* allocated size, (2x-1)*(2y-1) */
141     space *grid;
142     int completed, used_solve;
143     int ndots;
144     space **dots;
145
146     midend *me;         /* to call supersede_game_desc */
147     int cdiff;          /* difficulty of current puzzle (for status bar),
148                            or -1 if stale. */
149 };
150
151 static int check_complete(const game_state *state, int *dsf, int *colours);
152 static int solver_state(game_state *state, int maxdiff);
153 static int solver_obvious(game_state *state);
154 static int solver_obvious_dot(game_state *state, space *dot);
155 static space *space_opposite_dot(const game_state *state, const space *sp,
156                                  const space *dot);
157 static space *tile_opposite(const game_state *state, const space *sp);
158
159 /* ----------------------------------------------------------
160  * Game parameters and presets
161  */
162
163 /* make up some sensible default sizes */
164
165 #define DEFAULT_PRESET 0
166
167 static const game_params galaxies_presets[] = {
168     {  7,  7, DIFF_NORMAL },
169     {  7,  7, DIFF_UNREASONABLE },
170     { 10, 10, DIFF_NORMAL },
171     { 15, 15, DIFF_NORMAL },
172 };
173
174 static int game_fetch_preset(int i, char **name, game_params **params)
175 {
176     game_params *ret;
177     char buf[80];
178
179     if (i < 0 || i >= lenof(galaxies_presets))
180         return FALSE;
181
182     ret = snew(game_params);
183     *ret = galaxies_presets[i]; /* structure copy */
184
185     sprintf(buf, "%dx%d %s", ret->w, ret->h,
186             galaxies_diffnames[ret->diff]);
187
188     if (name) *name = dupstr(buf);
189     *params = ret;
190     return TRUE;
191 }
192
193 static game_params *default_params(void)
194 {
195     game_params *ret;
196     game_fetch_preset(DEFAULT_PRESET, NULL, &ret);
197     return ret;
198 }
199
200 static void free_params(game_params *params)
201 {
202     sfree(params);
203 }
204
205 static game_params *dup_params(const game_params *params)
206 {
207     game_params *ret = snew(game_params);
208     *ret = *params;                    /* structure copy */
209     return ret;
210 }
211
212 static void decode_params(game_params *params, char const *string)
213 {
214     params->h = params->w = atoi(string);
215     params->diff = DIFF_NORMAL;
216     while (*string && isdigit((unsigned char)*string)) string++;
217     if (*string == 'x') {
218         string++;
219         params->h = atoi(string);
220         while (*string && isdigit((unsigned char)*string)) string++;
221     }
222     if (*string == 'd') {
223         int i;
224         string++;
225         for (i = 0; i <= DIFF_UNREASONABLE; i++)
226             if (*string == galaxies_diffchars[i])
227                 params->diff = i;
228         if (*string) string++;
229     }
230 }
231
232 static char *encode_params(const game_params *params, int full)
233 {
234     char str[80];
235     sprintf(str, "%dx%d", params->w, params->h);
236     if (full)
237         sprintf(str + strlen(str), "d%c", galaxies_diffchars[params->diff]);
238     return dupstr(str);
239 }
240
241 static config_item *game_configure(const game_params *params)
242 {
243     config_item *ret;
244     char buf[80];
245
246     ret = snewn(4, config_item);
247
248     ret[0].name = "Width";
249     ret[0].type = C_STRING;
250     sprintf(buf, "%d", params->w);
251     ret[0].sval = dupstr(buf);
252     ret[0].ival = 0;
253
254     ret[1].name = "Height";
255     ret[1].type = C_STRING;
256     sprintf(buf, "%d", params->h);
257     ret[1].sval = dupstr(buf);
258     ret[1].ival = 0;
259
260     ret[2].name = "Difficulty";
261     ret[2].type = C_CHOICES;
262     ret[2].sval = DIFFCONFIG;
263     ret[2].ival = params->diff;
264
265     ret[3].name = NULL;
266     ret[3].type = C_END;
267     ret[3].sval = NULL;
268     ret[3].ival = 0;
269
270     return ret;
271 }
272
273 static game_params *custom_params(const config_item *cfg)
274 {
275     game_params *ret = snew(game_params);
276
277     ret->w = atoi(cfg[0].sval);
278     ret->h = atoi(cfg[1].sval);
279     ret->diff = cfg[2].ival;
280
281     return ret;
282 }
283
284 static char *validate_params(const game_params *params, int full)
285 {
286     if (params->w < 3 || params->h < 3)
287         return "Width and height must both be at least 3";
288     /*
289      * This shouldn't be able to happen at all, since decode_params
290      * and custom_params will never generate anything that isn't
291      * within range.
292      */
293     assert(params->diff <= DIFF_UNREASONABLE);
294
295     return NULL;
296 }
297
298 /* ----------------------------------------------------------
299  * Game utility functions.
300  */
301
302 static void add_dot(space *space) {
303     assert(!(space->flags & F_DOT));
304     space->flags |= F_DOT;
305     space->nassoc = 0;
306 }
307
308 static void remove_dot(space *space) {
309     assert(space->flags & F_DOT);
310     space->flags &= ~F_DOT;
311 }
312
313 static void remove_assoc(const game_state *state, space *tile) {
314     if (tile->flags & F_TILE_ASSOC) {
315         SPACE(state, tile->dotx, tile->doty).nassoc--;
316         tile->flags &= ~F_TILE_ASSOC;
317         tile->dotx = -1;
318         tile->doty = -1;
319     }
320 }
321
322 static void remove_assoc_with_opposite(game_state *state, space *tile) {
323     space *opposite;
324
325     if (!(tile->flags & F_TILE_ASSOC)) {
326         return;
327     }
328
329     opposite = tile_opposite(state, tile);
330     remove_assoc(state, tile);
331
332     if (opposite != NULL && opposite != tile) {
333         remove_assoc(state, opposite);
334     }
335 }
336
337 static void add_assoc(const game_state *state, space *tile, space *dot) {
338     remove_assoc(state, tile);
339
340 #ifdef STANDALONE_PICTURE_GENERATOR
341     if (picture)
342         assert(!picture[(tile->y/2) * state->w + (tile->x/2)] ==
343                !(dot->flags & F_DOT_BLACK));
344 #endif
345     tile->flags |= F_TILE_ASSOC;
346     tile->dotx = dot->x;
347     tile->doty = dot->y;
348     dot->nassoc++;
349     /*debug(("add_assoc sp %d %d --> dot %d,%d, new nassoc %d.\n",
350            tile->x, tile->y, dot->x, dot->y, dot->nassoc));*/
351 }
352
353 static void add_assoc_with_opposite(game_state *state, space *tile, space *dot) {
354     int *colors;
355     space *opposite = space_opposite_dot(state, tile, dot);
356
357     if (opposite == NULL) {
358         return;
359     }
360     if (opposite->flags & F_DOT) {
361         return;
362     }
363
364     colors = snewn(state->w * state->h, int);
365     check_complete(state, NULL, colors);
366     if (colors[(tile->y - 1)/2 * state->w + (tile->x - 1)/2]) {
367         sfree(colors);
368         return;
369     }
370     if (colors[(opposite->y - 1)/2 * state->w + (opposite->x - 1)/2]) {
371         sfree(colors);
372         return;
373     }
374
375     sfree(colors);
376     remove_assoc_with_opposite(state, tile);
377     add_assoc(state, tile, dot);
378     remove_assoc_with_opposite(state, opposite);
379     add_assoc(state, opposite, dot);
380 }
381
382 static space *sp2dot(const game_state *state, int x, int y)
383 {
384     space *sp = &SPACE(state, x, y);
385     if (!(sp->flags & F_TILE_ASSOC)) return NULL;
386     return &SPACE(state, sp->dotx, sp->doty);
387 }
388
389 #define IS_VERTICAL_EDGE(x) ((x % 2) == 0)
390
391 static int game_can_format_as_text_now(const game_params *params)
392 {
393     return TRUE;
394 }
395
396 static char *game_text_format(const game_state *state)
397 {
398     int maxlen = (state->sx+1)*state->sy, x, y;
399     char *ret, *p;
400     space *sp;
401
402     ret = snewn(maxlen+1, char);
403     p = ret;
404
405     for (y = 0; y < state->sy; y++) {
406         for (x = 0; x < state->sx; x++) {
407             sp = &SPACE(state, x, y);
408             if (sp->flags & F_DOT)
409                 *p++ = 'o';
410 #if 0
411             else if (sp->flags & (F_REACHABLE|F_MULTIPLE|F_MARK))
412                 *p++ = (sp->flags & F_MULTIPLE) ? 'M' :
413                     (sp->flags & F_REACHABLE) ? 'R' : 'X';
414 #endif
415             else {
416                 switch (sp->type) {
417                 case s_tile:
418                     if (sp->flags & F_TILE_ASSOC) {
419                         space *dot = sp2dot(state, sp->x, sp->y);
420                         if (dot && dot->flags & F_DOT)
421                             *p++ = (dot->flags & F_DOT_BLACK) ? 'B' : 'W';
422                         else
423                             *p++ = '?'; /* association with not-a-dot. */
424                     } else
425                         *p++ = ' ';
426                     break;
427
428                 case s_vertex:
429                     *p++ = '+';
430                     break;
431
432                 case s_edge:
433                     if (sp->flags & F_EDGE_SET)
434                         *p++ = (IS_VERTICAL_EDGE(x)) ? '|' : '-';
435                     else
436                         *p++ = ' ';
437                     break;
438
439                 default:
440                     assert(!"shouldn't get here!");
441                 }
442             }
443         }
444         *p++ = '\n';
445     }
446
447     assert(p - ret == maxlen);
448     *p = '\0';
449
450     return ret;
451 }
452
453 static void dbg_state(const game_state *state)
454 {
455 #ifdef DEBUGGING
456     char *temp = game_text_format(state);
457     debug(("%s\n", temp));
458     sfree(temp);
459 #endif
460 }
461
462 /* Space-enumeration callbacks should all return 1 for 'progress made',
463  * -1 for 'impossible', and 0 otherwise. */
464 typedef int (*space_cb)(game_state *state, space *sp, void *ctx);
465
466 #define IMPOSSIBLE_QUITS        1
467
468 static int foreach_sub(game_state *state, space_cb cb, unsigned int f,
469                        void *ctx, int startx, int starty)
470 {
471     int x, y, progress = 0, impossible = 0, ret;
472     space *sp;
473
474     for (y = starty; y < state->sy; y += 2) {
475         sp = &SPACE(state, startx, y);
476         for (x = startx; x < state->sx; x += 2) {
477             ret = cb(state, sp, ctx);
478             if (ret == -1) {
479                 if (f & IMPOSSIBLE_QUITS) return -1;
480                 impossible = -1;
481             } else if (ret == 1) {
482                 progress = 1;
483             }
484             sp += 2;
485         }
486     }
487     return impossible ? -1 : progress;
488 }
489
490 static int foreach_tile(game_state *state, space_cb cb, unsigned int f,
491                         void *ctx)
492 {
493     return foreach_sub(state, cb, f, ctx, 1, 1);
494 }
495
496 static int foreach_edge(game_state *state, space_cb cb, unsigned int f,
497                         void *ctx)
498 {
499     int ret1, ret2;
500
501     ret1 = foreach_sub(state, cb, f, ctx, 0, 1);
502     ret2 = foreach_sub(state, cb, f, ctx, 1, 0);
503
504     if (ret1 == -1 || ret2 == -1) return -1;
505     return (ret1 || ret2) ? 1 : 0;
506 }
507
508 #if 0
509 static int foreach_vertex(game_state *state, space_cb cb, unsigned int f,
510                           void *ctx)
511 {
512     return foreach_sub(state, cb, f, ctx, 0, 0);
513 }
514 #endif
515
516 #if 0
517 static int is_same_assoc(game_state *state,
518                          int x1, int y1, int x2, int y2)
519 {
520     space *s1, *s2;
521
522     if (!INGRID(state, x1, y1) || !INGRID(state, x2, y2))
523         return 0;
524
525     s1 = &SPACE(state, x1, y1);
526     s2 = &SPACE(state, x2, y2);
527     assert(s1->type == s_tile && s2->type == s_tile);
528     if ((s1->flags & F_TILE_ASSOC) && (s2->flags & F_TILE_ASSOC) &&
529         s1->dotx == s2->dotx && s1->doty == s2->doty)
530         return 1;
531     return 0; /* 0 if not same or not both associated. */
532 }
533 #endif
534
535 #if 0
536 static int edges_into_vertex(game_state *state,
537                              int x, int y)
538 {
539     int dx, dy, nx, ny, count = 0;
540
541     assert(SPACE(state, x, y).type == s_vertex);
542     for (dx = -1; dx <= 1; dx++) {
543         for (dy = -1; dy <= 1; dy++) {
544             if (dx != 0 && dy != 0) continue;
545             if (dx == 0 && dy == 0) continue;
546
547             nx = x+dx; ny = y+dy;
548             if (!INGRID(state, nx, ny)) continue;
549             assert(SPACE(state, nx, ny).type == s_edge);
550             if (SPACE(state, nx, ny).flags & F_EDGE_SET)
551                 count++;
552         }
553     }
554     return count;
555 }
556 #endif
557
558 static space *space_opposite_dot(const game_state *state, const space *sp,
559                                  const space *dot)
560 {
561     int dx, dy, tx, ty;
562     space *sp2;
563
564     dx = sp->x - dot->x;
565     dy = sp->y - dot->y;
566     tx = dot->x - dx;
567     ty = dot->y - dy;
568     if (!INGRID(state, tx, ty)) return NULL;
569
570     sp2 = &SPACE(state, tx, ty);
571     assert(sp2->type == sp->type);
572     return sp2;
573 }
574
575 static space *tile_opposite(const game_state *state, const space *sp)
576 {
577     space *dot;
578
579     assert(sp->flags & F_TILE_ASSOC);
580     dot = &SPACE(state, sp->dotx, sp->doty);
581     return space_opposite_dot(state, sp, dot);
582 }
583
584 static int dotfortile(game_state *state, space *tile, space *dot)
585 {
586     space *tile_opp = space_opposite_dot(state, tile, dot);
587
588     if (!tile_opp) return 0; /* opposite would be off grid */
589     if (tile_opp->flags & F_TILE_ASSOC &&
590             (tile_opp->dotx != dot->x || tile_opp->doty != dot->y))
591             return 0; /* opposite already associated with diff. dot */
592     return 1;
593 }
594
595 static void adjacencies(game_state *state, space *sp, space **a1s, space **a2s)
596 {
597     int dxs[4] = {-1, 1, 0, 0}, dys[4] = {0, 0, -1, 1};
598     int n, x, y;
599
600     /* this function needs optimising. */
601
602     for (n = 0; n < 4; n++) {
603         x = sp->x+dxs[n];
604         y = sp->y+dys[n];
605
606         if (INGRID(state, x, y)) {
607             a1s[n] = &SPACE(state, x, y);
608
609             x += dxs[n]; y += dys[n];
610
611             if (INGRID(state, x, y))
612                 a2s[n] = &SPACE(state, x, y);
613             else
614                 a2s[n] = NULL;
615         } else {
616             a1s[n] = a2s[n] = NULL;
617         }
618     }
619 }
620
621 static int outline_tile_fordot(game_state *state, space *tile, int mark)
622 {
623     space *tadj[4], *eadj[4];
624     int i, didsth = 0, edge, same;
625
626     assert(tile->type == s_tile);
627     adjacencies(state, tile, eadj, tadj);
628     for (i = 0; i < 4; i++) {
629         if (!eadj[i]) continue;
630
631         edge = (eadj[i]->flags & F_EDGE_SET) ? 1 : 0;
632         if (tadj[i]) {
633             if (!(tile->flags & F_TILE_ASSOC))
634                 same = (tadj[i]->flags & F_TILE_ASSOC) ? 0 : 1;
635             else
636                 same = ((tadj[i]->flags & F_TILE_ASSOC) &&
637                     tile->dotx == tadj[i]->dotx &&
638                     tile->doty == tadj[i]->doty) ? 1 : 0;
639         } else
640             same = 0;
641
642         if (!edge && !same) {
643             if (mark) eadj[i]->flags |= F_EDGE_SET;
644             didsth = 1;
645         } else if (edge && same) {
646             if (mark) eadj[i]->flags &= ~F_EDGE_SET;
647             didsth = 1;
648         }
649     }
650     return didsth;
651 }
652
653 static void tiles_from_edge(game_state *state, space *sp, space **ts)
654 {
655     int xs[2], ys[2];
656
657     if (IS_VERTICAL_EDGE(sp->x)) {
658         xs[0] = sp->x-1; ys[0] = sp->y;
659         xs[1] = sp->x+1; ys[1] = sp->y;
660     } else {
661         xs[0] = sp->x; ys[0] = sp->y-1;
662         xs[1] = sp->x; ys[1] = sp->y+1;
663     }
664     ts[0] = INGRID(state, xs[0], ys[0]) ? &SPACE(state, xs[0], ys[0]) : NULL;
665     ts[1] = INGRID(state, xs[1], ys[1]) ? &SPACE(state, xs[1], ys[1]) : NULL;
666 }
667
668 /* Returns a move string for use by 'solve', including the initial
669  * 'S' if issolve is true. */
670 static char *diff_game(const game_state *src, const game_state *dest,
671                        int issolve)
672 {
673     int movelen = 0, movesize = 256, x, y, len;
674     char *move = snewn(movesize, char), buf[80], *sep = "";
675     char achar = issolve ? 'a' : 'A';
676     space *sps, *spd;
677
678     assert(src->sx == dest->sx && src->sy == dest->sy);
679
680     if (issolve) {
681         move[movelen++] = 'S';
682         sep = ";";
683     }
684     move[movelen] = '\0';
685     for (x = 0; x < src->sx; x++) {
686         for (y = 0; y < src->sy; y++) {
687             sps = &SPACE(src, x, y);
688             spd = &SPACE(dest, x, y);
689
690             assert(sps->type == spd->type);
691
692             len = 0;
693             if (sps->type == s_tile) {
694                 if ((sps->flags & F_TILE_ASSOC) &&
695                     (spd->flags & F_TILE_ASSOC)) {
696                     if (sps->dotx != spd->dotx ||
697                         sps->doty != spd->doty)
698                     /* Both associated; change association, if different */
699                         len = sprintf(buf, "%s%c%d,%d,%d,%d", sep,
700                                       (int)achar, x, y, spd->dotx, spd->doty);
701                 } else if (sps->flags & F_TILE_ASSOC)
702                     /* Only src associated; remove. */
703                     len = sprintf(buf, "%sU%d,%d", sep, x, y);
704                 else if (spd->flags & F_TILE_ASSOC)
705                     /* Only dest associated; add. */
706                     len = sprintf(buf, "%s%c%d,%d,%d,%d", sep,
707                                   (int)achar, x, y, spd->dotx, spd->doty);
708             } else if (sps->type == s_edge) {
709                 if ((sps->flags & F_EDGE_SET) != (spd->flags & F_EDGE_SET))
710                     /* edge flags are different; flip them. */
711                     len = sprintf(buf, "%sE%d,%d", sep, x, y);
712             }
713             if (len) {
714                 if (movelen + len >= movesize) {
715                     movesize = movelen + len + 256;
716                     move = sresize(move, movesize, char);
717                 }
718                 strcpy(move + movelen, buf);
719                 movelen += len;
720                 sep = ";";
721             }
722         }
723     }
724     debug(("diff_game src then dest:\n"));
725     dbg_state(src);
726     dbg_state(dest);
727     debug(("diff string %s\n", move));
728     return move;
729 }
730
731 /* Returns 1 if a dot here would not be too close to any other dots
732  * (and would avoid other game furniture). */
733 static int dot_is_possible(game_state *state, space *sp, int allow_assoc)
734 {
735     int bx = 0, by = 0, dx, dy;
736     space *adj;
737 #ifdef STANDALONE_PICTURE_GENERATOR
738     int col = -1;
739 #endif
740
741     switch (sp->type) {
742     case s_tile:
743         bx = by = 1; break;
744     case s_edge:
745         if (IS_VERTICAL_EDGE(sp->x)) {
746             bx = 2; by = 1;
747         } else {
748             bx = 1; by = 2;
749         }
750         break;
751     case s_vertex:
752         bx = by = 2; break;
753     }
754
755     for (dx = -bx; dx <= bx; dx++) {
756         for (dy = -by; dy <= by; dy++) {
757             if (!INGRID(state, sp->x+dx, sp->y+dy)) continue;
758
759             adj = &SPACE(state, sp->x+dx, sp->y+dy);
760
761 #ifdef STANDALONE_PICTURE_GENERATOR
762             /*
763              * Check that all the squares we're looking at have the
764              * same colour.
765              */
766             if (picture) {
767                 if (adj->type == s_tile) {
768                     int c = picture[(adj->y / 2) * state->w + (adj->x / 2)];
769                     if (col < 0)
770                         col = c;
771                     if (c != col)
772                         return 0;          /* colour mismatch */
773                 }
774             }
775 #endif
776
777             if (!allow_assoc && (adj->flags & F_TILE_ASSOC))
778                 return 0;
779
780             if (dx != 0 || dy != 0) {
781                 /* Other than our own square, no dots nearby. */
782                 if (adj->flags & (F_DOT))
783                     return 0;
784             }
785
786             /* We don't want edges within our rectangle
787              * (but don't care about edges on the edge) */
788             if (abs(dx) < bx && abs(dy) < by &&
789                 adj->flags & F_EDGE_SET)
790                 return 0;
791         }
792     }
793     return 1;
794 }
795
796 /* ----------------------------------------------------------
797  * Game generation, structure creation, and descriptions.
798  */
799
800 static game_state *blank_game(int w, int h)
801 {
802     game_state *state = snew(game_state);
803     int x, y;
804
805     state->w = w;
806     state->h = h;
807
808     state->sx = (w*2)+1;
809     state->sy = (h*2)+1;
810     state->grid = snewn(state->sx * state->sy, space);
811     state->completed = state->used_solve = 0;
812
813     for (x = 0; x < state->sx; x++) {
814         for (y = 0; y < state->sy; y++) {
815             space *sp = &SPACE(state, x, y);
816             memset(sp, 0, sizeof(space));
817             sp->x = x;
818             sp->y = y;
819             if ((x % 2) == 0 && (y % 2) == 0)
820                 sp->type = s_vertex;
821             else if ((x % 2) == 0 || (y % 2) == 0) {
822                 sp->type = s_edge;
823                 if (x == 0 || y == 0 || x == state->sx-1 || y == state->sy-1)
824                     sp->flags |= F_EDGE_SET;
825             } else
826                 sp->type = s_tile;
827         }
828     }
829
830     state->ndots = 0;
831     state->dots = NULL;
832
833     state->me = NULL; /* filled in by new_game. */
834     state->cdiff = -1;
835
836     return state;
837 }
838
839 static void game_update_dots(game_state *state)
840 {
841     int i, n, sz = state->sx * state->sy;
842
843     if (state->dots) sfree(state->dots);
844     state->ndots = 0;
845
846     for (i = 0; i < sz; i++) {
847         if (state->grid[i].flags & F_DOT) state->ndots++;
848     }
849     state->dots = snewn(state->ndots, space *);
850     n = 0;
851     for (i = 0; i < sz; i++) {
852         if (state->grid[i].flags & F_DOT)
853             state->dots[n++] = &state->grid[i];
854     }
855 }
856
857 static void clear_game(game_state *state, int cleardots)
858 {
859     int x, y;
860
861     /* don't erase edge flags around outline! */
862     for (x = 1; x < state->sx-1; x++) {
863         for (y = 1; y < state->sy-1; y++) {
864             if (cleardots)
865                 SPACE(state, x, y).flags = 0;
866             else
867                 SPACE(state, x, y).flags &= (F_DOT|F_DOT_BLACK);
868         }
869     }
870     if (cleardots) game_update_dots(state);
871 }
872
873 static game_state *dup_game(const game_state *state)
874 {
875     game_state *ret = blank_game(state->w, state->h);
876
877     ret->completed = state->completed;
878     ret->used_solve = state->used_solve;
879
880     memcpy(ret->grid, state->grid,
881            ret->sx*ret->sy*sizeof(space));
882
883     game_update_dots(ret);
884
885     ret->me = state->me;
886     ret->cdiff = state->cdiff;
887
888     return ret;
889 }
890
891 static void free_game(game_state *state)
892 {
893     if (state->dots) sfree(state->dots);
894     sfree(state->grid);
895     sfree(state);
896 }
897
898 /* Game description is a sequence of letters representing the number
899  * of spaces (a = 0, y = 24) before the next dot; a-y for a white dot,
900  * and A-Y for a black dot. 'z' is 25 spaces (and no dot).
901  *
902  * I know it's a bitch to generate by hand, so we provide
903  * an edit mode.
904  */
905
906 static char *encode_game(game_state *state)
907 {
908     char *desc, *p;
909     int run, x, y, area;
910     unsigned int f;
911
912     area = (state->sx-2) * (state->sy-2);
913
914     desc = snewn(area, char);
915     p = desc;
916     run = 0;
917     for (y = 1; y < state->sy-1; y++) {
918         for (x = 1; x < state->sx-1; x++) {
919             f = SPACE(state, x, y).flags;
920
921             /* a/A is 0 spaces between, b/B is 1 space, ...
922              * y/Y is 24 spaces, za/zA is 25 spaces, ...
923              * It's easier to count from 0 because we then
924              * don't have to special-case the top left-hand corner
925              * (which could be a dot with 0 spaces before it). */
926             if (!(f & F_DOT))
927                 run++;
928             else {
929                 while (run > 24) {
930                     *p++ = 'z';
931                     run -= 25;
932                 }
933                 *p++ = ((f & F_DOT_BLACK) ? 'A' : 'a') + run;
934                 run = 0;
935             }
936         }
937     }
938     assert(p - desc < area);
939     *p++ = '\0';
940     desc = sresize(desc, p - desc, char);
941
942     return desc;
943 }
944
945 struct movedot {
946     int op;
947     space *olddot, *newdot;
948 };
949
950 enum { MD_CHECK, MD_MOVE };
951
952 static int movedot_cb(game_state *state, space *tile, void *vctx)
953 {
954    struct movedot *md = (struct movedot *)vctx;
955    space *newopp = NULL;
956
957    assert(tile->type == s_tile);
958    assert(md->olddot && md->newdot);
959
960    if (!(tile->flags & F_TILE_ASSOC)) return 0;
961    if (tile->dotx != md->olddot->x || tile->doty != md->olddot->y)
962        return 0;
963
964    newopp = space_opposite_dot(state, tile, md->newdot);
965
966    switch (md->op) {
967    case MD_CHECK:
968        /* If the tile is associated with the old dot, check its
969         * opposite wrt the _new_ dot is empty or same assoc. */
970        if (!newopp) return -1; /* no new opposite */
971        if (newopp->flags & F_TILE_ASSOC) {
972            if (newopp->dotx != md->olddot->x ||
973                newopp->doty != md->olddot->y)
974                return -1; /* associated, but wrong dot. */
975        }
976 #ifdef STANDALONE_PICTURE_GENERATOR
977        if (picture) {
978            /*
979             * Reject if either tile and the dot don't match in colour.
980             */
981            if (!(picture[(tile->y/2) * state->w + (tile->x/2)]) ^
982                !(md->newdot->flags & F_DOT_BLACK))
983                return -1;
984            if (!(picture[(newopp->y/2) * state->w + (newopp->x/2)]) ^
985                !(md->newdot->flags & F_DOT_BLACK))
986                return -1;
987        }
988 #endif
989        break;
990
991    case MD_MOVE:
992        /* Move dot associations: anything that was associated
993         * with the old dot, and its opposite wrt the new dot,
994         * become associated with the new dot. */
995        assert(newopp);
996        debug(("Associating %d,%d and %d,%d with new dot %d,%d.\n",
997               tile->x, tile->y, newopp->x, newopp->y,
998               md->newdot->x, md->newdot->y));
999        add_assoc(state, tile, md->newdot);
1000        add_assoc(state, newopp, md->newdot);
1001        return 1; /* we did something! */
1002    }
1003    return 0;
1004 }
1005
1006 /* For the given dot, first see if we could expand it into all the given
1007  * extra spaces (by checking for empty spaces on the far side), and then
1008  * see if we can move the dot to shift the CoG to include the new spaces.
1009  */
1010 static int dot_expand_or_move(game_state *state, space *dot,
1011                               space **toadd, int nadd)
1012 {
1013     space *tileopp;
1014     int i, ret, nnew, cx, cy;
1015     struct movedot md;
1016
1017     debug(("dot_expand_or_move: %d tiles for dot %d,%d\n",
1018            nadd, dot->x, dot->y));
1019     for (i = 0; i < nadd; i++)
1020         debug(("dot_expand_or_move:   dot %d,%d\n",
1021                toadd[i]->x, toadd[i]->y));
1022     assert(dot->flags & F_DOT);
1023
1024 #ifdef STANDALONE_PICTURE_GENERATOR
1025     if (picture) {
1026         /*
1027          * Reject the expansion totally if any of the new tiles are
1028          * the wrong colour.
1029          */
1030         for (i = 0; i < nadd; i++) {
1031             if (!(picture[(toadd[i]->y/2) * state->w + (toadd[i]->x/2)]) ^
1032                 !(dot->flags & F_DOT_BLACK))
1033                 return 0;
1034         }
1035     }
1036 #endif
1037
1038     /* First off, could we just expand the current dot's tile to cover
1039      * the space(s) passed in and their opposites? */
1040     for (i = 0; i < nadd; i++) {
1041         tileopp = space_opposite_dot(state, toadd[i], dot);
1042         if (!tileopp) goto noexpand;
1043         if (tileopp->flags & F_TILE_ASSOC) goto noexpand;
1044 #ifdef STANDALONE_PICTURE_GENERATOR
1045         if (picture) {
1046             /*
1047              * The opposite tiles have to be the right colour as well.
1048              */
1049             if (!(picture[(tileopp->y/2) * state->w + (tileopp->x/2)]) ^
1050                 !(dot->flags & F_DOT_BLACK))
1051                 goto noexpand;
1052         }
1053 #endif
1054     }
1055     /* OK, all spaces have valid empty opposites: associate spaces and
1056      * opposites with our dot. */
1057     for (i = 0; i < nadd; i++) {
1058         tileopp = space_opposite_dot(state, toadd[i], dot);
1059         add_assoc(state, toadd[i], dot);
1060         add_assoc(state, tileopp, dot);
1061         debug(("Added associations %d,%d and %d,%d --> %d,%d\n",
1062                toadd[i]->x, toadd[i]->y,
1063                tileopp->x, tileopp->y,
1064                dot->x, dot->y));
1065         dbg_state(state);
1066     }
1067     return 1;
1068
1069 noexpand:
1070     /* Otherwise, try to move dot so as to encompass given spaces: */
1071     /* first, calculate the 'centre of gravity' of the new dot. */
1072     nnew = dot->nassoc + nadd; /* number of tiles assoc. with new dot. */
1073     cx = dot->x * dot->nassoc;
1074     cy = dot->y * dot->nassoc;
1075     for (i = 0; i < nadd; i++) {
1076         cx += toadd[i]->x;
1077         cy += toadd[i]->y;
1078     }
1079     /* If the CoG isn't a whole number, it's not possible. */
1080     if ((cx % nnew) != 0 || (cy % nnew) != 0) {
1081         debug(("Unable to move dot %d,%d, CoG not whole number.\n",
1082                dot->x, dot->y));
1083         return 0;
1084     }
1085     cx /= nnew; cy /= nnew;
1086
1087     /* Check whether all spaces in the old tile would have a good
1088      * opposite wrt the new dot. */
1089     md.olddot = dot;
1090     md.newdot = &SPACE(state, cx, cy);
1091     md.op = MD_CHECK;
1092     ret = foreach_tile(state, movedot_cb, IMPOSSIBLE_QUITS, &md);
1093     if (ret == -1) {
1094         debug(("Unable to move dot %d,%d, new dot not symmetrical.\n",
1095                dot->x, dot->y));
1096         return 0;
1097     }
1098     /* Also check whether all spaces we're adding would have a good
1099      * opposite wrt the new dot. */
1100     for (i = 0; i < nadd; i++) {
1101         tileopp = space_opposite_dot(state, toadd[i], md.newdot);
1102         if (tileopp && (tileopp->flags & F_TILE_ASSOC) &&
1103             (tileopp->dotx != dot->x || tileopp->doty != dot->y)) {
1104             tileopp = NULL;
1105         }
1106         if (!tileopp) {
1107             debug(("Unable to move dot %d,%d, new dot not symmetrical.\n",
1108                dot->x, dot->y));
1109             return 0;
1110         }
1111 #ifdef STANDALONE_PICTURE_GENERATOR
1112         if (picture) {
1113             if (!(picture[(tileopp->y/2) * state->w + (tileopp->x/2)]) ^
1114                 !(dot->flags & F_DOT_BLACK))
1115                 return 0;
1116         }
1117 #endif
1118     }
1119
1120     /* If we've got here, we're ok. First, associate all of 'toadd'
1121      * with the _old_ dot (so they'll get fixed up, with their opposites,
1122      * in the next step). */
1123     for (i = 0; i < nadd; i++) {
1124         debug(("Associating to-add %d,%d with old dot %d,%d.\n",
1125                toadd[i]->x, toadd[i]->y, dot->x, dot->y));
1126         add_assoc(state, toadd[i], dot);
1127     }
1128
1129     /* Finally, move the dot and fix up all the old associations. */
1130     debug(("Moving dot at %d,%d to %d,%d\n",
1131            dot->x, dot->y, md.newdot->x, md.newdot->y));
1132     {
1133 #ifdef STANDALONE_PICTURE_GENERATOR
1134         int f = dot->flags & F_DOT_BLACK;
1135 #endif
1136         remove_dot(dot);
1137         add_dot(md.newdot);
1138 #ifdef STANDALONE_PICTURE_GENERATOR
1139         md.newdot->flags |= f;
1140 #endif
1141     }
1142
1143     md.op = MD_MOVE;
1144     ret = foreach_tile(state, movedot_cb, 0, &md);
1145     assert(ret == 1);
1146     dbg_state(state);
1147
1148     return 1;
1149 }
1150
1151 /* Hard-code to a max. of 2x2 squares, for speed (less malloc) */
1152 #define MAX_TOADD 4
1153 #define MAX_OUTSIDE 8
1154
1155 #define MAX_TILE_PERC 20
1156
1157 static int generate_try_block(game_state *state, random_state *rs,
1158                               int x1, int y1, int x2, int y2)
1159 {
1160     int x, y, nadd = 0, nout = 0, i, maxsz;
1161     space *sp, *toadd[MAX_TOADD], *outside[MAX_OUTSIDE], *dot;
1162
1163     if (!INGRID(state, x1, y1) || !INGRID(state, x2, y2)) return 0;
1164
1165     /* We limit the maximum size of tiles to be ~2*sqrt(area); so,
1166      * a 5x5 grid shouldn't have anything >10 tiles, a 20x20 grid
1167      * nothing >40 tiles. */
1168     maxsz = (int)sqrt((double)(state->w * state->h)) * 2;
1169     debug(("generate_try_block, maxsz %d\n", maxsz));
1170
1171     /* Make a static list of the spaces; if any space is already
1172      * associated then quit immediately. */
1173     for (x = x1; x <= x2; x += 2) {
1174         for (y = y1; y <= y2; y += 2) {
1175             assert(nadd < MAX_TOADD);
1176             sp = &SPACE(state, x, y);
1177             assert(sp->type == s_tile);
1178             if (sp->flags & F_TILE_ASSOC) return 0;
1179             toadd[nadd++] = sp;
1180         }
1181     }
1182
1183     /* Make a list of the spaces outside of our block, and shuffle it. */
1184 #define OUTSIDE(x, y) do {                              \
1185     if (INGRID(state, (x), (y))) {                      \
1186         assert(nout < MAX_OUTSIDE);                     \
1187         outside[nout++] = &SPACE(state, (x), (y));      \
1188     }                                                   \
1189 } while(0)
1190     for (x = x1; x <= x2; x += 2) {
1191         OUTSIDE(x, y1-2);
1192         OUTSIDE(x, y2+2);
1193     }
1194     for (y = y1; y <= y2; y += 2) {
1195         OUTSIDE(x1-2, y);
1196         OUTSIDE(x2+2, y);
1197     }
1198     shuffle(outside, nout, sizeof(space *), rs);
1199
1200     for (i = 0; i < nout; i++) {
1201         if (!(outside[i]->flags & F_TILE_ASSOC)) continue;
1202         dot = &SPACE(state, outside[i]->dotx, outside[i]->doty);
1203         if (dot->nassoc >= maxsz) {
1204             debug(("Not adding to dot %d,%d, large enough (%d) already.\n",
1205                    dot->x, dot->y, dot->nassoc));
1206             continue;
1207         }
1208         if (dot_expand_or_move(state, dot, toadd, nadd)) return 1;
1209     }
1210     return 0;
1211 }
1212
1213 #ifdef STANDALONE_SOLVER
1214 int maxtries;
1215 #define MAXTRIES maxtries
1216 #else
1217 #define MAXTRIES 50
1218 #endif
1219
1220 #define GP_DOTS   1
1221
1222 static void generate_pass(game_state *state, random_state *rs, int *scratch,
1223                          int perc, unsigned int flags)
1224 {
1225     int sz = state->sx*state->sy, nspc, i, ret;
1226
1227     shuffle(scratch, sz, sizeof(int), rs);
1228
1229     /* This bug took me a, er, little while to track down. On PalmOS,
1230      * which has 16-bit signed ints, puzzles over about 9x9 started
1231      * failing to generate because the nspc calculation would start
1232      * to overflow, causing the dots not to be filled in properly. */
1233     nspc = (int)(((long)perc * (long)sz) / 100L);
1234     debug(("generate_pass: %d%% (%d of %dx%d) squares, flags 0x%x\n",
1235            perc, nspc, state->sx, state->sy, flags));
1236
1237     for (i = 0; i < nspc; i++) {
1238         space *sp = &state->grid[scratch[i]];
1239         int x1 = sp->x, y1 = sp->y, x2 = sp->x, y2 = sp->y;
1240
1241         if (sp->type == s_edge) {
1242             if (IS_VERTICAL_EDGE(sp->x)) {
1243                 x1--; x2++;
1244             } else {
1245                 y1--; y2++;
1246             }
1247         }
1248         if (sp->type != s_vertex) {
1249             /* heuristic; expanding from vertices tends to generate lots of
1250              * too-big regions of tiles. */
1251             if (generate_try_block(state, rs, x1, y1, x2, y2))
1252                 continue; /* we expanded successfully. */
1253         }
1254
1255         if (!(flags & GP_DOTS)) continue;
1256
1257         if ((sp->type == s_edge) && (i % 2)) {
1258             debug(("Omitting edge %d,%d as half-of.\n", sp->x, sp->y));
1259             continue;
1260         }
1261
1262         /* If we've got here we might want to put a dot down. Check
1263          * if we can, and add one if so. */
1264         if (dot_is_possible(state, sp, 0)) {
1265             add_dot(sp);
1266 #ifdef STANDALONE_PICTURE_GENERATOR
1267             if (picture) {
1268                 if (picture[(sp->y/2) * state->w + (sp->x/2)])
1269                     sp->flags |= F_DOT_BLACK;
1270             }
1271 #endif
1272             ret = solver_obvious_dot(state, sp);
1273             assert(ret != -1);
1274             debug(("Added dot (and obvious associations) at %d,%d\n",
1275                    sp->x, sp->y));
1276             dbg_state(state);
1277         }
1278     }
1279     dbg_state(state);
1280 }
1281
1282 static char *new_game_desc(const game_params *params, random_state *rs,
1283                            char **aux, int interactive)
1284 {
1285     game_state *state = blank_game(params->w, params->h), *copy;
1286     char *desc;
1287     int *scratch, sz = state->sx*state->sy, i;
1288     int diff, ntries = 0, cc;
1289
1290     /* Random list of squares to try and process, one-by-one. */
1291     scratch = snewn(sz, int);
1292     for (i = 0; i < sz; i++) scratch[i] = i;
1293
1294 generate:
1295     clear_game(state, 1);
1296     ntries++;
1297
1298     /* generate_pass(state, rs, scratch, 10, GP_DOTS); */
1299     /* generate_pass(state, rs, scratch, 100, 0); */
1300     generate_pass(state, rs, scratch, 100, GP_DOTS);
1301
1302     game_update_dots(state);
1303
1304 #ifdef DEBUGGING
1305     {
1306         char *tmp = encode_game(state);
1307         debug(("new_game_desc state %dx%d:%s\n", params->w, params->h, tmp));
1308         sfree(tmp);
1309     }
1310 #endif
1311
1312     for (i = 0; i < state->sx*state->sy; i++)
1313         if (state->grid[i].type == s_tile)
1314             outline_tile_fordot(state, &state->grid[i], TRUE);
1315     cc = check_complete(state, NULL, NULL);
1316     assert(cc);
1317
1318     copy = dup_game(state);
1319     clear_game(copy, 0);
1320     dbg_state(copy);
1321     diff = solver_state(copy, params->diff);
1322     free_game(copy);
1323
1324     assert(diff != DIFF_IMPOSSIBLE);
1325     if (diff != params->diff) {
1326         /*
1327          * We'll grudgingly accept a too-easy puzzle, but we must
1328          * _not_ permit a too-hard one (one which the solver
1329          * couldn't handle at all).
1330          */
1331         if (diff > params->diff ||
1332             ntries < MAXTRIES) goto generate;
1333     }
1334
1335 #ifdef STANDALONE_PICTURE_GENERATOR
1336     /*
1337      * Postprocessing pass to prevent excessive numbers of adjacent
1338      * singletons. Iterate over all edges in random shuffled order;
1339      * for each edge that separates two regions, investigate
1340      * whether removing that edge and merging the regions would
1341      * still yield a valid and soluble puzzle. (The two regions
1342      * must also be the same colour, of course.) If so, do it.
1343      * 
1344      * This postprocessing pass is slow (due to repeated solver
1345      * invocations), and seems to be unnecessary during normal
1346      * unconstrained game generation. However, when generating a
1347      * game under colour constraints, excessive singletons seem to
1348      * turn up more often, so it's worth doing this.
1349      */
1350     {
1351         int *posns, nposns;
1352         int i, j, newdiff;
1353         game_state *copy2;
1354
1355         nposns = params->w * (params->h+1) + params->h * (params->w+1);
1356         posns = snewn(nposns, int);
1357         for (i = j = 0; i < state->sx*state->sy; i++)
1358             if (state->grid[i].type == s_edge)
1359                 posns[j++] = i;
1360         assert(j == nposns);
1361
1362         shuffle(posns, nposns, sizeof(*posns), rs);
1363
1364         for (i = 0; i < nposns; i++) {
1365             int x, y, x0, y0, x1, y1, cx, cy, cn, cx0, cy0, cx1, cy1, tx, ty;
1366             space *s0, *s1, *ts, *d0, *d1, *dn;
1367             int ok;
1368
1369             /* Coordinates of edge space */
1370             x = posns[i] % state->sx;
1371             y = posns[i] / state->sx;
1372
1373             /* Coordinates of square spaces on either side of edge */
1374             x0 = ((x+1) & ~1) - 1;     /* round down to next odd number */
1375             y0 = ((y+1) & ~1) - 1;
1376             x1 = 2*x-x0;               /* and reflect about x to get x1 */
1377             y1 = 2*y-y0;
1378
1379             if (!INGRID(state, x0, y0) || !INGRID(state, x1, y1))
1380                 continue;              /* outermost edge of grid */
1381             s0 = &SPACE(state, x0, y0);
1382             s1 = &SPACE(state, x1, y1);
1383             assert(s0->type == s_tile && s1->type == s_tile);
1384
1385             if (s0->dotx == s1->dotx && s0->doty == s1->doty)
1386                 continue;              /* tiles _already_ owned by same dot */
1387
1388             d0 = &SPACE(state, s0->dotx, s0->doty);
1389             d1 = &SPACE(state, s1->dotx, s1->doty);
1390
1391             if ((d0->flags ^ d1->flags) & F_DOT_BLACK)
1392                 continue;              /* different colours: cannot merge */
1393
1394             /*
1395              * Work out where the centre of gravity of the new
1396              * region would be.
1397              */
1398             cx = d0->nassoc * d0->x + d1->nassoc * d1->x;
1399             cy = d0->nassoc * d0->y + d1->nassoc * d1->y;
1400             cn = d0->nassoc + d1->nassoc;
1401             if (cx % cn || cy % cn)
1402                 continue;              /* CoG not at integer coordinates */
1403             cx /= cn;
1404             cy /= cn;
1405             assert(INUI(state, cx, cy));
1406
1407             /*
1408              * Ensure that the CoG would actually be _in_ the new
1409              * region, by verifying that all its surrounding tiles
1410              * belong to one or other of our two dots.
1411              */
1412             cx0 = ((cx+1) & ~1) - 1;   /* round down to next odd number */
1413             cy0 = ((cy+1) & ~1) - 1;
1414             cx1 = 2*cx-cx0;            /* and reflect about cx to get cx1 */
1415             cy1 = 2*cy-cy0;
1416             ok = TRUE;
1417             for (ty = cy0; ty <= cy1; ty += 2)
1418                 for (tx = cx0; tx <= cx1; tx += 2) {
1419                     ts = &SPACE(state, tx, ty);
1420                     assert(ts->type == s_tile);
1421                     if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1422                         (ts->dotx != d1->x || ts->doty != d1->y))
1423                         ok = FALSE;
1424                 }
1425             if (!ok)
1426                 continue;
1427
1428             /*
1429              * Verify that for every tile in either source region,
1430              * that tile's image in the new CoG is also in one of
1431              * the two source regions.
1432              */
1433             for (ty = 1; ty < state->sy; ty += 2) {
1434                 for (tx = 1; tx < state->sx; tx += 2) {
1435                     int tx1, ty1;
1436
1437                     ts = &SPACE(state, tx, ty);
1438                     assert(ts->type == s_tile);
1439                     if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1440                         (ts->dotx != d1->x || ts->doty != d1->y))
1441                         continue;      /* not part of these tiles anyway */
1442                     tx1 = 2*cx-tx;
1443                     ty1 = 2*cy-ty;
1444                     if (!INGRID(state, tx1, ty1)) {
1445                         ok = FALSE;
1446                         break;
1447                     }
1448                     ts = &SPACE(state, cx+cx-tx, cy+cy-ty);
1449                     if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1450                         (ts->dotx != d1->x || ts->doty != d1->y)) {
1451                         ok = FALSE;
1452                         break;
1453                     }
1454                 }
1455                 if (!ok)
1456                     break;
1457             }
1458             if (!ok)
1459                 continue;
1460
1461             /*
1462              * Now we're clear to attempt the merge. We take a copy
1463              * of the game state first, so we can revert it easily
1464              * if the resulting puzzle turns out to have become
1465              * insoluble.
1466              */
1467             copy2 = dup_game(state);
1468
1469             remove_dot(d0);
1470             remove_dot(d1);
1471             dn = &SPACE(state, cx, cy);
1472             add_dot(dn);
1473             dn->flags |= (d0->flags & F_DOT_BLACK);
1474             for (ty = 1; ty < state->sy; ty += 2) {
1475                 for (tx = 1; tx < state->sx; tx += 2) {
1476                     ts = &SPACE(state, tx, ty);
1477                     assert(ts->type == s_tile);
1478                     if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1479                         (ts->dotx != d1->x || ts->doty != d1->y))
1480                         continue;      /* not part of these tiles anyway */
1481                     add_assoc(state, ts, dn);
1482                 }
1483             }
1484
1485             copy = dup_game(state);
1486             clear_game(copy, 0);
1487             dbg_state(copy);
1488             newdiff = solver_state(copy, params->diff);
1489             free_game(copy);
1490             if (diff == newdiff) {
1491                 /* Still just as soluble. Let the merge stand. */
1492                 free_game(copy2);
1493             } else {
1494                 /* Became insoluble. Revert. */
1495                 free_game(state);
1496                 state = copy2;
1497             }
1498         }
1499         sfree(posns);
1500     }
1501 #endif
1502
1503     desc = encode_game(state);
1504 #ifndef STANDALONE_SOLVER
1505     debug(("new_game_desc generated: \n"));
1506     dbg_state(state);
1507 #endif
1508
1509     free_game(state);
1510     sfree(scratch);
1511
1512     return desc;
1513 }
1514
1515 static int dots_too_close(game_state *state)
1516 {
1517     /* Quick-and-dirty check, using half the solver:
1518      * solver_obvious will only fail if the dots are
1519      * too close together, so dot-proximity associations
1520      * overlap. */
1521     game_state *tmp = dup_game(state);
1522     int ret = solver_obvious(tmp);
1523     free_game(tmp);
1524     return (ret == -1) ? 1 : 0;
1525 }
1526
1527 static game_state *load_game(const game_params *params, const char *desc,
1528                              char **why_r)
1529 {
1530     game_state *state = blank_game(params->w, params->h);
1531     char *why = NULL;
1532     int i, x, y, n;
1533     unsigned int df;
1534
1535     i = 0;
1536     while (*desc) {
1537         n = *desc++;
1538         if (n == 'z') {
1539             i += 25;
1540             continue;
1541         }
1542         if (n >= 'a' && n <= 'y') {
1543             i += n - 'a';
1544             df = 0;
1545         } else if (n >= 'A' && n <= 'Y') {
1546             i += n - 'A';
1547             df = F_DOT_BLACK;
1548         } else {
1549             why = "Invalid characters in game description"; goto fail;
1550         }
1551         /* if we got here we incremented i and have a dot to add. */
1552         y = (i / (state->sx-2)) + 1;
1553         x = (i % (state->sx-2)) + 1;
1554         if (!INUI(state, x, y)) {
1555             why = "Too much data to fit in grid"; goto fail;
1556         }
1557         add_dot(&SPACE(state, x, y));
1558         SPACE(state, x, y).flags |= df;
1559         i++;
1560     }
1561     game_update_dots(state);
1562
1563     if (dots_too_close(state)) {
1564         why = "Dots too close together"; goto fail;
1565     }
1566
1567     return state;
1568
1569 fail:
1570     free_game(state);
1571     if (why_r) *why_r = why;
1572     return NULL;
1573 }
1574
1575 static char *validate_desc(const game_params *params, const char *desc)
1576 {
1577     char *why = NULL;
1578     game_state *dummy = load_game(params, desc, &why);
1579     if (dummy) {
1580         free_game(dummy);
1581         assert(!why);
1582     } else
1583         assert(why);
1584     return why;
1585 }
1586
1587 static game_state *new_game(midend *me, const game_params *params,
1588                             const char *desc)
1589 {
1590     game_state *state = load_game(params, desc, NULL);
1591     if (!state) {
1592         assert("Unable to load ?validated game.");
1593         return NULL;
1594     }
1595 #ifdef EDITOR
1596     state->me = me;
1597 #endif
1598     return state;
1599 }
1600
1601 /* ----------------------------------------------------------
1602  * Solver and all its little wizards.
1603  */
1604
1605 int solver_recurse_depth;
1606
1607 typedef struct solver_ctx {
1608     game_state *state;
1609     int sz;             /* state->sx * state->sy */
1610     space **scratch;    /* size sz */
1611
1612 } solver_ctx;
1613
1614 static solver_ctx *new_solver(game_state *state)
1615 {
1616     solver_ctx *sctx = snew(solver_ctx);
1617     sctx->state = state;
1618     sctx->sz = state->sx*state->sy;
1619     sctx->scratch = snewn(sctx->sz, space *);
1620     return sctx;
1621 }
1622
1623 static void free_solver(solver_ctx *sctx)
1624 {
1625     sfree(sctx->scratch);
1626     sfree(sctx);
1627 }
1628
1629     /* Solver ideas so far:
1630      *
1631      * For any empty space, work out how many dots it could associate
1632      * with:
1633        * it needs line-of-sight
1634        * it needs an empty space on the far side
1635        * any adjacent lines need corresponding line possibilities.
1636      */
1637
1638 /* The solver_ctx should keep a list of dot positions, for quicker looping.
1639  *
1640  * Solver techniques, in order of difficulty:
1641    * obvious adjacency to dots
1642    * transferring tiles to opposite side
1643    * transferring lines to opposite side
1644    * one possible dot for a given tile based on opposite availability
1645    * tile with 3 definite edges next to an associated tile must associate
1646       with same dot.
1647    *
1648    * one possible dot for a given tile based on line-of-sight
1649  */
1650
1651 static int solver_add_assoc(game_state *state, space *tile, int dx, int dy,
1652                             const char *why)
1653 {
1654     space *dot, *tile_opp;
1655
1656     dot = &SPACE(state, dx, dy);
1657     tile_opp = space_opposite_dot(state, tile, dot);
1658
1659     assert(tile->type == s_tile);
1660     if (tile->flags & F_TILE_ASSOC) {
1661         if ((tile->dotx != dx) || (tile->doty != dy)) {
1662             solvep(("%*sSet %d,%d --> %d,%d (%s) impossible; "
1663                     "already --> %d,%d.\n",
1664                     solver_recurse_depth*4, "",
1665                     tile->x, tile->y, dx, dy, why,
1666                     tile->dotx, tile->doty));
1667             return -1;
1668         }
1669         return 0; /* no-op */
1670     }
1671     if (!tile_opp) {
1672         solvep(("%*s%d,%d --> %d,%d impossible, no opposite tile.\n",
1673                 solver_recurse_depth*4, "", tile->x, tile->y, dx, dy));
1674         return -1;
1675     }
1676     if (tile_opp->flags & F_TILE_ASSOC &&
1677         (tile_opp->dotx != dx || tile_opp->doty != dy)) {
1678         solvep(("%*sSet %d,%d --> %d,%d (%s) impossible; "
1679                 "opposite already --> %d,%d.\n",
1680                 solver_recurse_depth*4, "",
1681                 tile->x, tile->y, dx, dy, why,
1682                 tile_opp->dotx, tile_opp->doty));
1683         return -1;
1684     }
1685
1686     add_assoc(state, tile, dot);
1687     add_assoc(state, tile_opp, dot);
1688     solvep(("%*sSetting %d,%d --> %d,%d (%s).\n",
1689             solver_recurse_depth*4, "",
1690             tile->x, tile->y,dx, dy, why));
1691     solvep(("%*sSetting %d,%d --> %d,%d (%s, opposite).\n",
1692             solver_recurse_depth*4, "",
1693             tile_opp->x, tile_opp->y, dx, dy, why));
1694     return 1;
1695 }
1696
1697 static int solver_obvious_dot(game_state *state, space *dot)
1698 {
1699     int dx, dy, ret, didsth = 0;
1700     space *tile;
1701
1702     debug(("%*ssolver_obvious_dot for %d,%d.\n",
1703            solver_recurse_depth*4, "", dot->x, dot->y));
1704
1705     assert(dot->flags & F_DOT);
1706     for (dx = -1; dx <= 1; dx++) {
1707         for (dy = -1; dy <= 1; dy++) {
1708             if (!INGRID(state, dot->x+dx, dot->y+dy)) continue;
1709
1710             tile = &SPACE(state, dot->x+dx, dot->y+dy);
1711             if (tile->type == s_tile) {
1712                 ret = solver_add_assoc(state, tile, dot->x, dot->y,
1713                                        "next to dot");
1714                 if (ret < 0) return -1;
1715                 if (ret > 0) didsth = 1;
1716             }
1717         }
1718     }
1719     return didsth;
1720 }
1721
1722 static int solver_obvious(game_state *state)
1723 {
1724     int i, didsth = 0, ret;
1725
1726     debug(("%*ssolver_obvious.\n", solver_recurse_depth*4, ""));
1727
1728     for (i = 0; i < state->ndots; i++) {
1729         ret = solver_obvious_dot(state, state->dots[i]);
1730         if (ret < 0) return -1;
1731         if (ret > 0) didsth = 1;
1732     }
1733     return didsth;
1734 }
1735
1736 static int solver_lines_opposite_cb(game_state *state, space *edge, void *ctx)
1737 {
1738     int didsth = 0, n, dx, dy;
1739     space *tiles[2], *tile_opp, *edge_opp;
1740
1741     assert(edge->type == s_edge);
1742
1743     tiles_from_edge(state, edge, tiles);
1744
1745     /* if tiles[0] && tiles[1] && they're both associated
1746      * and they're both associated with different dots,
1747      * ensure the line is set. */
1748     if (!(edge->flags & F_EDGE_SET) &&
1749         tiles[0] && tiles[1] &&
1750         (tiles[0]->flags & F_TILE_ASSOC) &&
1751         (tiles[1]->flags & F_TILE_ASSOC) &&
1752         (tiles[0]->dotx != tiles[1]->dotx ||
1753          tiles[0]->doty != tiles[1]->doty)) {
1754         /* No edge, but the two adjacent tiles are both
1755          * associated with different dots; add the edge. */
1756         solvep(("%*sSetting edge %d,%d - tiles different dots.\n",
1757                solver_recurse_depth*4, "", edge->x, edge->y));
1758         edge->flags |= F_EDGE_SET;
1759         didsth = 1;
1760     }
1761
1762     if (!(edge->flags & F_EDGE_SET)) return didsth;
1763     for (n = 0; n < 2; n++) {
1764         if (!tiles[n]) continue;
1765         assert(tiles[n]->type == s_tile);
1766         if (!(tiles[n]->flags & F_TILE_ASSOC)) continue;
1767
1768         tile_opp = tile_opposite(state, tiles[n]);
1769         if (!tile_opp) {
1770             solvep(("%*simpossible: edge %d,%d has assoc. tile %d,%d"
1771                    " with no opposite.\n",
1772                    solver_recurse_depth*4, "",
1773                    edge->x, edge->y, tiles[n]->x, tiles[n]->y));
1774             /* edge of tile has no opposite edge (off grid?);
1775              * this is impossible. */
1776             return -1;
1777         }
1778
1779         dx = tiles[n]->x - edge->x;
1780         dy = tiles[n]->y - edge->y;
1781         assert(INGRID(state, tile_opp->x+dx, tile_opp->y+dy));
1782         edge_opp = &SPACE(state, tile_opp->x+dx, tile_opp->y+dy);
1783         if (!(edge_opp->flags & F_EDGE_SET)) {
1784             solvep(("%*sSetting edge %d,%d as opposite %d,%d\n",
1785                    solver_recurse_depth*4, "",
1786                    tile_opp->x-dx, tile_opp->y-dy, edge->x, edge->y));
1787             edge_opp->flags |= F_EDGE_SET;
1788             didsth = 1;
1789         }
1790     }
1791     return didsth;
1792 }
1793
1794 static int solver_spaces_oneposs_cb(game_state *state, space *tile, void *ctx)
1795 {
1796     int n, eset, ret;
1797     space *edgeadj[4], *tileadj[4];
1798     int dotx, doty;
1799
1800     assert(tile->type == s_tile);
1801     if (tile->flags & F_TILE_ASSOC) return 0;
1802
1803     adjacencies(state, tile, edgeadj, tileadj);
1804
1805     /* Empty tile. If each edge is either set, or associated with
1806      * the same dot, we must also associate with dot. */
1807     eset = 0; dotx = -1; doty = -1;
1808     for (n = 0; n < 4; n++) {
1809         assert(edgeadj[n]);
1810         assert(edgeadj[n]->type == s_edge);
1811         if (edgeadj[n]->flags & F_EDGE_SET) {
1812             eset++;
1813         } else {
1814             assert(tileadj[n]);
1815             assert(tileadj[n]->type == s_tile);
1816
1817             /* If an adjacent tile is empty we can't make any deductions.*/
1818             if (!(tileadj[n]->flags & F_TILE_ASSOC))
1819                 return 0;
1820
1821             /* If an adjacent tile is assoc. with a different dot
1822              * we can't make any deductions. */
1823             if (dotx != -1 && doty != -1 &&
1824                 (tileadj[n]->dotx != dotx ||
1825                  tileadj[n]->doty != doty))
1826                 return 0;
1827
1828             dotx = tileadj[n]->dotx;
1829             doty = tileadj[n]->doty;
1830         }
1831     }
1832     if (eset == 4) {
1833         solvep(("%*simpossible: empty tile %d,%d has 4 edges\n",
1834                solver_recurse_depth*4, "",
1835                tile->x, tile->y));
1836         return -1;
1837     }
1838     assert(dotx != -1 && doty != -1);
1839
1840     ret = solver_add_assoc(state, tile, dotx, doty, "rest are edges");
1841     if (ret == -1) return -1;
1842     assert(ret != 0); /* really should have done something. */
1843
1844     return 1;
1845 }
1846
1847 /* Improved algorithm for tracking line-of-sight from dots, and not spaces.
1848  *
1849  * The solver_ctx already stores a list of dots: the algorithm proceeds by
1850  * expanding outwards from each dot in turn, expanding first to the boundary
1851  * of its currently-connected tile and then to all empty tiles that could see
1852  * it. Empty tiles will be flagged with a 'can see dot <x,y>' sticker.
1853  *
1854  * Expansion will happen by (symmetrically opposite) pairs of squares; if
1855  * a square hasn't an opposite number there's no point trying to expand through
1856  * it. Empty tiles will therefore also be tagged in pairs.
1857  *
1858  * If an empty tile already has a 'can see dot <x,y>' tag from a previous dot,
1859  * it (and its partner) gets untagged (or, rather, a 'can see two dots' tag)
1860  * because we're looking for single-dot possibilities.
1861  *
1862  * Once we've gone through all the dots, any which still have a 'can see dot'
1863  * tag get associated with that dot (because it must have been the only one);
1864  * any without any tag (i.e. that could see _no_ dots) cause an impossibility
1865  * marked.
1866  *
1867  * The expansion will happen each time with a stored list of (space *) pairs,
1868  * rather than a mark-and-sweep idea; that's horrifically inefficient.
1869  *
1870  * expansion algorithm:
1871  *
1872  * * allocate list of (space *) the size of s->sx*s->sy.
1873  * * allocate second grid for (flags, dotx, doty) size of sx*sy.
1874  *
1875  * clear second grid (flags = 0, all dotx and doty = 0)
1876  * flags: F_REACHABLE, F_MULTIPLE
1877  *
1878  *
1879  * * for each dot, start with one pair of tiles that are associated with it --
1880  *   * vertex --> (dx+1, dy+1), (dx-1, dy-1)
1881  *   * edge --> (adj1, adj2)
1882  *   * tile --> (tile, tile) ???
1883  * * mark that pair of tiles with F_MARK, clear all other F_MARKs.
1884  * * add two tiles to start of list.
1885  *
1886  * set start = 0, end = next = 2
1887  *
1888  * from (start to end-1, step 2) {
1889  * * we have two tiles (t1, t2), opposites wrt our dot.
1890  * * for each (at1) sensible adjacent tile to t1 (i.e. not past an edge):
1891  *   * work out at2 as the opposite to at1
1892  *   * assert at1 and at2 have the same F_MARK values.
1893  *   * if at1 & F_MARK ignore it (we've been there on a previous sweep)
1894  *   * if either are associated with a different dot
1895  *     * mark both with F_MARK (so we ignore them later)
1896  *   * otherwise (assoc. with our dot, or empty):
1897  *     * mark both with F_MARK
1898  *     * add their space * values to the end of the list, set next += 2.
1899  * }
1900  *
1901  * if (end == next)
1902  * * we didn't add any new squares; exit the loop.
1903  * else
1904  * * set start = next+1, end = next. go round again
1905  *
1906  * We've finished expanding from the dot. Now, for each square we have
1907  * in our list (--> each square with F_MARK):
1908  * * if the tile is empty:
1909  *   * if F_REACHABLE was already set
1910  *     * set F_MULTIPLE
1911  *   * otherwise
1912  *     * set F_REACHABLE, set dotx and doty to our dot.
1913  *
1914  * Then, continue the whole thing for each dot in turn.
1915  *
1916  * Once we've done for each dot, go through the entire grid looking for
1917  * empty tiles: for each empty tile:
1918    * if F_REACHABLE and not F_MULTIPLE, set that dot (and its double)
1919    * if !F_REACHABLE, return as impossible.
1920  *
1921  */
1922
1923 /* Returns 1 if this tile is either already associated with this dot,
1924  * or blank. */
1925 static int solver_expand_checkdot(space *tile, space *dot)
1926 {
1927     if (!(tile->flags & F_TILE_ASSOC)) return 1;
1928     if (tile->dotx == dot->x && tile->doty == dot->y) return 1;
1929     return 0;
1930 }
1931
1932 static void solver_expand_fromdot(game_state *state, space *dot, solver_ctx *sctx)
1933 {
1934     int i, j, x, y, start, end, next;
1935     space *sp;
1936
1937     /* Clear the grid of the (space) flags we'll use. */
1938
1939     /* This is well optimised; analysis showed that:
1940         for (i = 0; i < sctx->sz; i++) state->grid[i].flags &= ~F_MARK;
1941        took up ~85% of the total function time! */
1942     for (y = 1; y < state->sy; y += 2) {
1943         sp = &SPACE(state, 1, y);
1944         for (x = 1; x < state->sx; x += 2, sp += 2)
1945             sp->flags &= ~F_MARK;
1946     }
1947
1948     /* Seed the list of marked squares with two that must be associated
1949      * with our dot (possibly the same space) */
1950     if (dot->type == s_tile) {
1951         sctx->scratch[0] = sctx->scratch[1] = dot;
1952     } else if (dot->type == s_edge) {
1953         tiles_from_edge(state, dot, sctx->scratch);
1954     } else if (dot->type == s_vertex) {
1955         /* pick two of the opposite ones arbitrarily. */
1956         sctx->scratch[0] = &SPACE(state, dot->x-1, dot->y-1);
1957         sctx->scratch[1] = &SPACE(state, dot->x+1, dot->y+1);
1958     }
1959     assert(sctx->scratch[0]->flags & F_TILE_ASSOC);
1960     assert(sctx->scratch[1]->flags & F_TILE_ASSOC);
1961
1962     sctx->scratch[0]->flags |= F_MARK;
1963     sctx->scratch[1]->flags |= F_MARK;
1964
1965     debug(("%*sexpand from dot %d,%d seeded with %d,%d and %d,%d.\n",
1966            solver_recurse_depth*4, "", dot->x, dot->y,
1967            sctx->scratch[0]->x, sctx->scratch[0]->y,
1968            sctx->scratch[1]->x, sctx->scratch[1]->y));
1969
1970     start = 0; end = 2; next = 2;
1971
1972 expand:
1973     debug(("%*sexpand: start %d, end %d, next %d\n",
1974            solver_recurse_depth*4, "", start, end, next));
1975     for (i = start; i < end; i += 2) {
1976         space *t1 = sctx->scratch[i]/*, *t2 = sctx->scratch[i+1]*/;
1977         space *edges[4], *tileadj[4], *tileadj2;
1978
1979         adjacencies(state, t1, edges, tileadj);
1980
1981         for (j = 0; j < 4; j++) {
1982             assert(edges[j]);
1983             if (edges[j]->flags & F_EDGE_SET) continue;
1984             assert(tileadj[j]);
1985
1986             if (tileadj[j]->flags & F_MARK) continue; /* seen before. */
1987
1988             /* We have a tile adjacent to t1; find its opposite. */
1989             tileadj2 = space_opposite_dot(state, tileadj[j], dot);
1990             if (!tileadj2) {
1991                 debug(("%*sMarking %d,%d, no opposite.\n",
1992                        solver_recurse_depth*4, "",
1993                        tileadj[j]->x, tileadj[j]->y));
1994                 tileadj[j]->flags |= F_MARK;
1995                 continue; /* no opposite, so mark for next time. */
1996             }
1997             /* If the tile had an opposite we should have either seen both of
1998              * these, or neither of these, before. */
1999             assert(!(tileadj2->flags & F_MARK));
2000
2001             if (solver_expand_checkdot(tileadj[j], dot) &&
2002                 solver_expand_checkdot(tileadj2, dot)) {
2003                 /* Both tiles could associate with this dot; add them to
2004                  * our list. */
2005                 debug(("%*sAdding %d,%d and %d,%d to possibles list.\n",
2006                        solver_recurse_depth*4, "",
2007                        tileadj[j]->x, tileadj[j]->y, tileadj2->x, tileadj2->y));
2008                 sctx->scratch[next++] = tileadj[j];
2009                 sctx->scratch[next++] = tileadj2;
2010             }
2011             /* Either way, we've seen these tiles already so mark them. */
2012             debug(("%*sMarking %d,%d and %d,%d.\n",
2013                    solver_recurse_depth*4, "",
2014                        tileadj[j]->x, tileadj[j]->y, tileadj2->x, tileadj2->y));
2015             tileadj[j]->flags |= F_MARK;
2016             tileadj2->flags |= F_MARK;
2017         }
2018     }
2019     if (next > end) {
2020         /* We added more squares; go back and try again. */
2021         start = end; end = next; goto expand;
2022     }
2023
2024     /* We've expanded as far as we can go. Now we update the main flags
2025      * on all tiles we've expanded into -- if they were empty, we have
2026      * found possible associations for this dot. */
2027     for (i = 0; i < end; i++) {
2028         if (sctx->scratch[i]->flags & F_TILE_ASSOC) continue;
2029         if (sctx->scratch[i]->flags & F_REACHABLE) {
2030             /* This is (at least) the second dot this tile could
2031              * associate with. */
2032             debug(("%*sempty tile %d,%d could assoc. other dot %d,%d\n",
2033                    solver_recurse_depth*4, "",
2034                    sctx->scratch[i]->x, sctx->scratch[i]->y, dot->x, dot->y));
2035             sctx->scratch[i]->flags |= F_MULTIPLE;
2036         } else {
2037             /* This is the first (possibly only) dot. */
2038             debug(("%*sempty tile %d,%d could assoc. 1st dot %d,%d\n",
2039                    solver_recurse_depth*4, "",
2040                    sctx->scratch[i]->x, sctx->scratch[i]->y, dot->x, dot->y));
2041             sctx->scratch[i]->flags |= F_REACHABLE;
2042             sctx->scratch[i]->dotx = dot->x;
2043             sctx->scratch[i]->doty = dot->y;
2044         }
2045     }
2046     dbg_state(state);
2047 }
2048
2049 static int solver_expand_postcb(game_state *state, space *tile, void *ctx)
2050 {
2051     assert(tile->type == s_tile);
2052
2053     if (tile->flags & F_TILE_ASSOC) return 0;
2054
2055     if (!(tile->flags & F_REACHABLE)) {
2056         solvep(("%*simpossible: space (%d,%d) can reach no dots.\n",
2057                 solver_recurse_depth*4, "", tile->x, tile->y));
2058         return -1;
2059     }
2060     if (tile->flags & F_MULTIPLE) return 0;
2061
2062     return solver_add_assoc(state, tile, tile->dotx, tile->doty,
2063                             "single possible dot after expansion");
2064 }
2065
2066 static int solver_expand_dots(game_state *state, solver_ctx *sctx)
2067 {
2068     int i;
2069
2070     for (i = 0; i < sctx->sz; i++)
2071         state->grid[i].flags &= ~(F_REACHABLE|F_MULTIPLE);
2072
2073     for (i = 0; i < state->ndots; i++)
2074         solver_expand_fromdot(state, state->dots[i], sctx);
2075
2076     return foreach_tile(state, solver_expand_postcb, IMPOSSIBLE_QUITS, sctx);
2077 }
2078
2079 struct recurse_ctx {
2080     space *best;
2081     int bestn;
2082 };
2083
2084 static int solver_recurse_cb(game_state *state, space *tile, void *ctx)
2085 {
2086     struct recurse_ctx *rctx = (struct recurse_ctx *)ctx;
2087     int i, n = 0;
2088
2089     assert(tile->type == s_tile);
2090     if (tile->flags & F_TILE_ASSOC) return 0;
2091
2092     /* We're unassociated: count up all the dots we could associate with. */
2093     for (i = 0; i < state->ndots; i++) {
2094         if (dotfortile(state, tile, state->dots[i]))
2095             n++;
2096     }
2097     if (n > rctx->bestn) {
2098         rctx->bestn = n;
2099         rctx->best = tile;
2100     }
2101     return 0;
2102 }
2103
2104 #define MAXRECURSE 5
2105
2106 static int solver_recurse(game_state *state, int maxdiff)
2107 {
2108     int diff = DIFF_IMPOSSIBLE, ret, n, gsz = state->sx * state->sy;
2109     space *ingrid, *outgrid = NULL, *bestopp;
2110     struct recurse_ctx rctx;
2111
2112     if (solver_recurse_depth >= MAXRECURSE) {
2113         solvep(("Limiting recursion to %d, returning.", MAXRECURSE));
2114         return DIFF_UNFINISHED;
2115     }
2116
2117     /* Work out the cell to recurse on; go through all unassociated tiles
2118      * and find which one has the most possible dots it could associate
2119      * with. */
2120     rctx.best = NULL;
2121     rctx.bestn = 0;
2122
2123     foreach_tile(state, solver_recurse_cb, 0, &rctx);
2124     if (rctx.bestn == 0) return DIFF_IMPOSSIBLE; /* or assert? */
2125     assert(rctx.best);
2126
2127     solvep(("%*sRecursing around %d,%d, with %d possible dots.\n",
2128            solver_recurse_depth*4, "",
2129            rctx.best->x, rctx.best->y, rctx.bestn));
2130
2131 #ifdef STANDALONE_SOLVER
2132     solver_recurse_depth++;
2133 #endif
2134
2135     ingrid = snewn(gsz, space);
2136     memcpy(ingrid, state->grid, gsz * sizeof(space));
2137
2138     for (n = 0; n < state->ndots; n++) {
2139         memcpy(state->grid, ingrid, gsz * sizeof(space));
2140
2141         if (!dotfortile(state, rctx.best, state->dots[n])) continue;
2142
2143         /* set cell (temporarily) pointing to that dot. */
2144         solver_add_assoc(state, rctx.best,
2145                          state->dots[n]->x, state->dots[n]->y,
2146                          "Attempting for recursion");
2147
2148         ret = solver_state(state, maxdiff);
2149
2150         if (diff == DIFF_IMPOSSIBLE && ret != DIFF_IMPOSSIBLE) {
2151             /* we found our first solved grid; copy it away. */
2152             assert(!outgrid);
2153             outgrid = snewn(gsz, space);
2154             memcpy(outgrid, state->grid, gsz * sizeof(space));
2155         }
2156         /* reset cell back to unassociated. */
2157         bestopp = tile_opposite(state, rctx.best);
2158         assert(bestopp && bestopp->flags & F_TILE_ASSOC);
2159
2160         remove_assoc(state, rctx.best);
2161         remove_assoc(state, bestopp);
2162
2163         if (ret == DIFF_AMBIGUOUS || ret == DIFF_UNFINISHED)
2164             diff = ret;
2165         else if (ret == DIFF_IMPOSSIBLE)
2166             /* no change */;
2167         else {
2168             /* precisely one solution */
2169             if (diff == DIFF_IMPOSSIBLE)
2170                 diff = DIFF_UNREASONABLE;
2171             else
2172                 diff = DIFF_AMBIGUOUS;
2173         }
2174         /* if we've found >1 solution, or ran out of recursion,
2175          * give up immediately. */
2176         if (diff == DIFF_AMBIGUOUS || diff == DIFF_UNFINISHED)
2177             break;
2178     }
2179
2180 #ifdef STANDALONE_SOLVER
2181     solver_recurse_depth--;
2182 #endif
2183
2184     if (outgrid) {
2185         /* we found (at least one) soln; copy it back to state */
2186         memcpy(state->grid, outgrid, gsz * sizeof(space));
2187         sfree(outgrid);
2188     }
2189     sfree(ingrid);
2190     return diff;
2191 }
2192
2193 static int solver_state(game_state *state, int maxdiff)
2194 {
2195     solver_ctx *sctx = new_solver(state);
2196     int ret, diff = DIFF_NORMAL;
2197
2198 #ifdef STANDALONE_PICTURE_GENERATOR
2199     /* hack, hack: set picture to NULL during solving so that add_assoc
2200      * won't complain when we attempt recursive guessing and guess wrong */
2201     int *savepic = picture;
2202     picture = NULL;
2203 #endif
2204
2205     ret = solver_obvious(state);
2206     if (ret < 0) {
2207         diff = DIFF_IMPOSSIBLE;
2208         goto got_result;
2209     }
2210
2211 #define CHECKRET(d) do {                                        \
2212     if (ret < 0) { diff = DIFF_IMPOSSIBLE; goto got_result; }   \
2213     if (ret > 0) { diff = max(diff, (d)); goto cont; }          \
2214 } while(0)
2215
2216     while (1) {
2217 cont:
2218         ret = foreach_edge(state, solver_lines_opposite_cb,
2219                            IMPOSSIBLE_QUITS, sctx);
2220         CHECKRET(DIFF_NORMAL);
2221
2222         ret = foreach_tile(state, solver_spaces_oneposs_cb,
2223                            IMPOSSIBLE_QUITS, sctx);
2224         CHECKRET(DIFF_NORMAL);
2225
2226         ret = solver_expand_dots(state, sctx);
2227         CHECKRET(DIFF_NORMAL);
2228
2229         if (maxdiff <= DIFF_NORMAL)
2230             break;
2231
2232         /* harder still? */
2233
2234         /* if we reach here, we've made no deductions, so we terminate. */
2235         break;
2236     }
2237
2238     if (check_complete(state, NULL, NULL)) goto got_result;
2239
2240     diff = (maxdiff >= DIFF_UNREASONABLE) ?
2241         solver_recurse(state, maxdiff) : DIFF_UNFINISHED;
2242
2243 got_result:
2244     free_solver(sctx);
2245 #ifndef STANDALONE_SOLVER
2246     debug(("solver_state ends, diff %s:\n", galaxies_diffnames[diff]));
2247     dbg_state(state);
2248 #endif
2249
2250 #ifdef STANDALONE_PICTURE_GENERATOR
2251     picture = savepic;
2252 #endif
2253
2254     return diff;
2255 }
2256
2257 #ifndef EDITOR
2258 static char *solve_game(const game_state *state, const game_state *currstate,
2259                         const char *aux, char **error)
2260 {
2261     game_state *tosolve;
2262     char *ret;
2263     int i;
2264     int diff;
2265
2266     tosolve = dup_game(currstate);
2267     diff = solver_state(tosolve, DIFF_UNREASONABLE);
2268     if (diff != DIFF_UNFINISHED && diff != DIFF_IMPOSSIBLE) {
2269         debug(("solve_game solved with current state.\n"));
2270         goto solved;
2271     }
2272     free_game(tosolve);
2273
2274     tosolve = dup_game(state);
2275     diff = solver_state(tosolve, DIFF_UNREASONABLE);
2276     if (diff != DIFF_UNFINISHED && diff != DIFF_IMPOSSIBLE) {
2277         debug(("solve_game solved with original state.\n"));
2278         goto solved;
2279     }
2280     free_game(tosolve);
2281
2282     return NULL;
2283
2284 solved:
2285     /*
2286      * Clear tile associations: the solution will only include the
2287      * edges.
2288      */
2289     for (i = 0; i < tosolve->sx*tosolve->sy; i++)
2290         tosolve->grid[i].flags &= ~F_TILE_ASSOC;
2291     ret = diff_game(currstate, tosolve, 1);
2292     free_game(tosolve);
2293     return ret;
2294 }
2295 #endif
2296
2297 /* ----------------------------------------------------------
2298  * User interface.
2299  */
2300
2301 struct game_ui {
2302     int dragging;
2303     int dx, dy;         /* pixel coords of drag pos. */
2304     int dotx, doty;     /* grid coords of dot we're dragging from. */
2305     int srcx, srcy;     /* grid coords of drag start */
2306     int cur_x, cur_y, cur_visible;
2307 };
2308
2309 static game_ui *new_ui(const game_state *state)
2310 {
2311     game_ui *ui = snew(game_ui);
2312     ui->dragging = FALSE;
2313     ui->cur_x = ui->cur_y = 1;
2314     ui->cur_visible = 0;
2315     return ui;
2316 }
2317
2318 static void free_ui(game_ui *ui)
2319 {
2320     sfree(ui);
2321 }
2322
2323 static char *encode_ui(const game_ui *ui)
2324 {
2325     return NULL;
2326 }
2327
2328 static void decode_ui(game_ui *ui, const char *encoding)
2329 {
2330 }
2331
2332 static void game_changed_state(game_ui *ui, const game_state *oldstate,
2333                                const game_state *newstate)
2334 {
2335 }
2336
2337 #define FLASH_TIME 0.15F
2338
2339 #define PREFERRED_TILE_SIZE 32
2340 #define TILE_SIZE (ds->tilesize)
2341 #define DOT_SIZE        (TILE_SIZE / 4)
2342 #define EDGE_THICKNESS (max(TILE_SIZE / 16, 2))
2343 #define BORDER TILE_SIZE
2344
2345 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
2346 #define SCOORD(x) ( ((x) * TILE_SIZE)/2 + BORDER )
2347 #define FROMCOORD(x) ( ((x) - BORDER) / TILE_SIZE )
2348
2349 #define DRAW_WIDTH      (BORDER * 2 + ds->w * TILE_SIZE)
2350 #define DRAW_HEIGHT     (BORDER * 2 + ds->h * TILE_SIZE)
2351
2352 #define CURSOR_SIZE DOT_SIZE
2353
2354 struct game_drawstate {
2355     int started;
2356     int w, h;
2357     int tilesize;
2358     unsigned long *grid;
2359     int *dx, *dy;
2360     blitter *bl;
2361     blitter *blmirror;
2362
2363     int dragging, dragx, dragy;
2364
2365     int *colour_scratch;
2366
2367     int cx, cy, cur_visible;
2368     blitter *cur_bl;
2369 };
2370
2371 #define CORNER_TOLERANCE 0.15F
2372 #define CENTRE_TOLERANCE 0.15F
2373
2374 /*
2375  * Round FP coordinates to the centre of the nearest edge.
2376  */
2377 #ifndef EDITOR
2378 static void coord_round_to_edge(float x, float y, int *xr, int *yr)
2379 {
2380     float xs, ys, xv, yv, dx, dy;
2381
2382     /*
2383      * Find the nearest square-centre.
2384      */
2385     xs = (float)floor(x) + 0.5F;
2386     ys = (float)floor(y) + 0.5F;
2387
2388     /*
2389      * Find the nearest grid vertex.
2390      */
2391     xv = (float)floor(x + 0.5F);
2392     yv = (float)floor(y + 0.5F);
2393
2394     /*
2395      * Determine whether the horizontal or vertical edge from that
2396      * vertex alongside that square is closer to us, by comparing
2397      * distances from the square cente.
2398      */
2399     dx = (float)fabs(x - xs);
2400     dy = (float)fabs(y - ys);
2401     if (dx > dy) {
2402         /* Vertical edge: x-coord of corner,
2403          * y-coord of square centre. */
2404         *xr = 2 * (int)xv;
2405         *yr = 1 + 2 * (int)floor(ys);
2406     } else {
2407         /* Horizontal edge: x-coord of square centre,
2408          * y-coord of corner. */
2409         *xr = 1 + 2 * (int)floor(xs);
2410         *yr = 2 * (int)yv;
2411     }
2412 }
2413 #endif
2414
2415 #ifdef EDITOR
2416 static char *interpret_move(const game_state *state, game_ui *ui,
2417                             const game_drawstate *ds,
2418                             int x, int y, int button)
2419 {
2420     char buf[80];
2421     int px, py;
2422     space *sp;
2423
2424     px = 2*FROMCOORD((float)x) + 0.5;
2425     py = 2*FROMCOORD((float)y) + 0.5;
2426
2427     state->cdiff = -1;
2428
2429     if (button == 'C' || button == 'c') return dupstr("C");
2430
2431     if (button == 'S' || button == 's') {
2432         char *ret;
2433         game_state *tmp = dup_game(state);
2434         state->cdiff = solver_state(tmp, DIFF_UNREASONABLE-1);
2435         ret = diff_game(state, tmp, 0);
2436         free_game(tmp);
2437         return ret;
2438     }
2439
2440     if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
2441         if (!INUI(state, px, py)) return NULL;
2442         sp = &SPACE(state, px, py);
2443         if (!dot_is_possible(state, sp, 1)) return NULL;
2444         sprintf(buf, "%c%d,%d",
2445                 (char)((button == LEFT_BUTTON) ? 'D' : 'd'), px, py);
2446         return dupstr(buf);
2447     }
2448
2449     return NULL;
2450 }
2451 #else
2452 static char *interpret_move(const game_state *state, game_ui *ui,
2453                             const game_drawstate *ds,
2454                             int x, int y, int button)
2455 {
2456     /* UI operations (play mode):
2457      *
2458      * Toggle edge (set/unset) (left-click on edge)
2459      * Associate space with dot (left-drag from dot)
2460      * Unassociate space (left-drag from space off grid)
2461      * Autofill lines around shape? (right-click?)
2462      *
2463      * (edit mode; will clear all lines/associations)
2464      *
2465      * Add or remove dot (left-click)
2466      */
2467     char buf[80];
2468     const char *sep = "";
2469     int px, py;
2470     space *sp, *dot;
2471
2472     buf[0] = '\0';
2473
2474     if (button == 'H' || button == 'h') {
2475         char *ret;
2476         game_state *tmp = dup_game(state);
2477         solver_obvious(tmp);
2478         ret = diff_game(state, tmp, 0);
2479         free_game(tmp);
2480         return ret;
2481     }
2482
2483     if (button == LEFT_BUTTON) {
2484         ui->cur_visible = 0;
2485         coord_round_to_edge(FROMCOORD((float)x), FROMCOORD((float)y),
2486                             &px, &py);
2487
2488         if (!INUI(state, px, py)) return NULL;
2489
2490         sp = &SPACE(state, px, py);
2491         assert(sp->type == s_edge);
2492         {
2493             sprintf(buf, "E%d,%d", px, py);
2494             return dupstr(buf);
2495         }
2496     } else if (button == RIGHT_BUTTON) {
2497         int px1, py1;
2498
2499         ui->cur_visible = 0;
2500
2501         px = (int)(2*FROMCOORD((float)x) + 0.5);
2502         py = (int)(2*FROMCOORD((float)y) + 0.5);
2503
2504         dot = NULL;
2505
2506         /*
2507          * If there's a dot anywhere nearby, we pick up an arrow
2508          * pointing at that dot.
2509          */
2510         for (py1 = py-1; py1 <= py+1; py1++)
2511             for (px1 = px-1; px1 <= px+1; px1++) {
2512                 if (px1 >= 0 && px1 < state->sx &&
2513                     py1 >= 0 && py1 < state->sy &&
2514                     x >= SCOORD(px1-1) && x < SCOORD(px1+1) &&
2515                     y >= SCOORD(py1-1) && y < SCOORD(py1+1) &&
2516                     SPACE(state, px1, py1).flags & F_DOT) {
2517                     /*
2518                      * Found a dot. Begin a drag from it.
2519                      */
2520                     dot = &SPACE(state, px1, py1);
2521                     ui->srcx = px1;
2522                     ui->srcy = py1;
2523                     goto done;         /* multi-level break */
2524                 }
2525             }
2526
2527         /*
2528          * Otherwise, find the nearest _square_, and pick up the
2529          * same arrow as it's got on it, if any.
2530          */
2531         if (!dot) {
2532             px = 2*FROMCOORD(x+TILE_SIZE) - 1;
2533             py = 2*FROMCOORD(y+TILE_SIZE) - 1;
2534             if (px >= 0 && px < state->sx && py >= 0 && py < state->sy) {
2535                 sp = &SPACE(state, px, py);
2536                 if (sp->flags & F_TILE_ASSOC) {
2537                     dot = &SPACE(state, sp->dotx, sp->doty);
2538                     ui->srcx = px;
2539                     ui->srcy = py;
2540                 }
2541             }
2542         }
2543
2544         done:
2545         /*
2546          * Now, if we've managed to find a dot, begin a drag.
2547          */
2548         if (dot) {
2549             ui->dragging = TRUE;
2550             ui->dx = x;
2551             ui->dy = y;
2552             ui->dotx = dot->x;
2553             ui->doty = dot->y;
2554             return "";
2555         }
2556     } else if (button == RIGHT_DRAG && ui->dragging) {
2557         /* just move the drag coords. */
2558         ui->dx = x;
2559         ui->dy = y;
2560         return "";
2561     } else if (button == RIGHT_RELEASE && ui->dragging) {
2562         ui->dragging = FALSE;
2563
2564         /*
2565          * Drags are always targeted at a single square.
2566          */
2567         px = 2*FROMCOORD(x+TILE_SIZE) - 1;
2568         py = 2*FROMCOORD(y+TILE_SIZE) - 1;
2569
2570         /*
2571          * Dragging an arrow on to the same square it started from
2572          * is a null move; just update the ui and finish.
2573          */
2574         if (px == ui->srcx && py == ui->srcy)
2575             return "";
2576
2577         /*
2578          * Otherwise, we remove the arrow from its starting
2579          * square if we didn't start from a dot...
2580          */
2581         if ((ui->srcx != ui->dotx || ui->srcy != ui->doty) &&
2582             SPACE(state, ui->srcx, ui->srcy).flags & F_TILE_ASSOC) {
2583             sprintf(buf + strlen(buf), "%sU%d,%d", sep, ui->srcx, ui->srcy);
2584             sep = ";";
2585         }
2586
2587         /*
2588          * ... and if the square we're moving it _to_ is valid, we
2589          * add one there instead.
2590          */
2591         if (INUI(state, px, py)) {
2592             sp = &SPACE(state, px, py);
2593
2594             if (!(sp->flags & F_DOT))
2595                 sprintf(buf + strlen(buf), "%sA%d,%d,%d,%d",
2596                         sep, px, py, ui->dotx, ui->doty);
2597         }
2598
2599         if (buf[0])
2600             return dupstr(buf);
2601         else
2602             return "";
2603     } else if (IS_CURSOR_MOVE(button)) {
2604         move_cursor(button, &ui->cur_x, &ui->cur_y, state->sx-1, state->sy-1, 0);
2605         if (ui->cur_x < 1) ui->cur_x = 1;
2606         if (ui->cur_y < 1) ui->cur_y = 1;
2607         ui->cur_visible = 1;
2608         if (ui->dragging) {
2609             ui->dx = SCOORD(ui->cur_x);
2610             ui->dy = SCOORD(ui->cur_y);
2611         }
2612         return "";
2613     } else if (IS_CURSOR_SELECT(button)) {
2614         if (!ui->cur_visible) {
2615             ui->cur_visible = 1;
2616             return "";
2617         }
2618         sp = &SPACE(state, ui->cur_x, ui->cur_y);
2619         if (ui->dragging) {
2620             ui->dragging = FALSE;
2621
2622             if ((ui->srcx != ui->dotx || ui->srcy != ui->doty) &&
2623                 SPACE(state, ui->srcx, ui->srcy).flags & F_TILE_ASSOC) {
2624                 sprintf(buf, "%sU%d,%d", sep, ui->srcx, ui->srcy);
2625                 sep = ";";
2626             }
2627             if (sp->type == s_tile && !(sp->flags & F_DOT) && !(sp->flags & F_TILE_ASSOC)) {
2628                 sprintf(buf + strlen(buf), "%sA%d,%d,%d,%d",
2629                         sep, ui->cur_x, ui->cur_y, ui->dotx, ui->doty);
2630             }
2631             return dupstr(buf);
2632         } else if (sp->flags & F_DOT) {
2633             ui->dragging = TRUE;
2634             ui->dx = SCOORD(ui->cur_x);
2635             ui->dy = SCOORD(ui->cur_y);
2636             ui->dotx = ui->srcx = ui->cur_x;
2637             ui->doty = ui->srcy = ui->cur_y;
2638             return "";
2639         } else if (sp->flags & F_TILE_ASSOC) {
2640             assert(sp->type == s_tile);
2641             ui->dragging = TRUE;
2642             ui->dx = SCOORD(ui->cur_x);
2643             ui->dy = SCOORD(ui->cur_y);
2644             ui->dotx = sp->dotx;
2645             ui->doty = sp->doty;
2646             ui->srcx = ui->cur_x;
2647             ui->srcy = ui->cur_y;
2648             return "";
2649         } else if (sp->type == s_edge) {
2650             sprintf(buf, "E%d,%d", ui->cur_x, ui->cur_y);
2651             return dupstr(buf);
2652         }
2653     }
2654
2655     return NULL;
2656 }
2657 #endif
2658
2659 static int check_complete(const game_state *state, int *dsf, int *colours)
2660 {
2661     int w = state->w, h = state->h;
2662     int x, y, i, ret;
2663
2664     int free_dsf;
2665     struct sqdata {
2666         int minx, miny, maxx, maxy;
2667         int cx, cy;
2668         int valid, colour;
2669     } *sqdata;
2670
2671     if (!dsf) {
2672         dsf = snew_dsf(w*h);
2673         free_dsf = TRUE;
2674     } else {
2675         dsf_init(dsf, w*h);
2676         free_dsf = FALSE;
2677     }
2678
2679     /*
2680      * During actual game play, completion checking is done on the
2681      * basis of the edges rather than the square associations. So
2682      * first we must go through the grid figuring out the connected
2683      * components into which the edges divide it.
2684      */
2685     for (y = 0; y < h; y++)
2686         for (x = 0; x < w; x++) {
2687             if (y+1 < h && !(SPACE(state, 2*x+1, 2*y+2).flags & F_EDGE_SET))
2688                 dsf_merge(dsf, y*w+x, (y+1)*w+x);
2689             if (x+1 < w && !(SPACE(state, 2*x+2, 2*y+1).flags & F_EDGE_SET))
2690                 dsf_merge(dsf, y*w+x, y*w+(x+1));
2691         }
2692
2693     /*
2694      * That gives us our connected components. Now, for each
2695      * component, decide whether it's _valid_. A valid component is
2696      * one which:
2697      *
2698      *  - is 180-degree rotationally symmetric
2699      *  - has a dot at its centre of symmetry
2700      *  - has no other dots anywhere within it (including on its
2701      *    boundary)
2702      *  - contains no internal edges (i.e. edges separating two
2703      *    squares which are both part of the component).
2704      */
2705
2706     /*
2707      * First, go through the grid finding the bounding box of each
2708      * component.
2709      */
2710     sqdata = snewn(w*h, struct sqdata);
2711     for (i = 0; i < w*h; i++) {
2712         sqdata[i].minx = w+1;
2713         sqdata[i].miny = h+1;
2714         sqdata[i].maxx = sqdata[i].maxy = -1;
2715         sqdata[i].valid = FALSE;
2716     }
2717     for (y = 0; y < h; y++)
2718         for (x = 0; x < w; x++) {
2719             i = dsf_canonify(dsf, y*w+x);
2720             if (sqdata[i].minx > x)
2721                 sqdata[i].minx = x;
2722             if (sqdata[i].maxx < x)
2723                 sqdata[i].maxx = x;
2724             if (sqdata[i].miny > y)
2725                 sqdata[i].miny = y;
2726             if (sqdata[i].maxy < y)
2727                 sqdata[i].maxy = y;
2728             sqdata[i].valid = TRUE;
2729         }
2730
2731     /*
2732      * Now we're in a position to loop over each actual component
2733      * and figure out where its centre of symmetry has to be if
2734      * it's anywhere.
2735      */
2736     for (i = 0; i < w*h; i++)
2737         if (sqdata[i].valid) {
2738             int cx, cy;
2739             cx = sqdata[i].cx = sqdata[i].minx + sqdata[i].maxx + 1;
2740             cy = sqdata[i].cy = sqdata[i].miny + sqdata[i].maxy + 1;
2741             if (!(SPACE(state, sqdata[i].cx, sqdata[i].cy).flags & F_DOT))
2742                 sqdata[i].valid = FALSE;   /* no dot at centre of symmetry */
2743             if (dsf_canonify(dsf, (cy-1)/2*w+(cx-1)/2) != i ||
2744                 dsf_canonify(dsf, (cy)/2*w+(cx-1)/2) != i ||
2745                 dsf_canonify(dsf, (cy-1)/2*w+(cx)/2) != i ||
2746                 dsf_canonify(dsf, (cy)/2*w+(cx)/2) != i)
2747                 sqdata[i].valid = FALSE;   /* dot at cx,cy isn't ours */
2748             if (SPACE(state, sqdata[i].cx, sqdata[i].cy).flags & F_DOT_BLACK)
2749                 sqdata[i].colour = 2;
2750             else
2751                 sqdata[i].colour = 1;
2752         }
2753
2754     /*
2755      * Now we loop over the whole grid again, this time finding
2756      * extraneous dots (any dot which wholly or partially overlaps
2757      * a square and is not at the centre of symmetry of that
2758      * square's component disqualifies the component from validity)
2759      * and extraneous edges (any edge separating two squares
2760      * belonging to the same component also disqualifies that
2761      * component).
2762      */
2763     for (y = 1; y < state->sy-1; y++)
2764         for (x = 1; x < state->sx-1; x++) {
2765             space *sp = &SPACE(state, x, y);
2766
2767             if (sp->flags & F_DOT) {
2768                 /*
2769                  * There's a dot here. Use it to disqualify any
2770                  * component which deserves it.
2771                  */
2772                 int cx, cy;
2773                 for (cy = (y-1) >> 1; cy <= y >> 1; cy++)
2774                     for (cx = (x-1) >> 1; cx <= x >> 1; cx++) {
2775                         i = dsf_canonify(dsf, cy*w+cx);
2776                         if (x != sqdata[i].cx || y != sqdata[i].cy)
2777                             sqdata[i].valid = FALSE;
2778                     }
2779             }
2780
2781             if (sp->flags & F_EDGE_SET) {
2782                 /*
2783                  * There's an edge here. Use it to disqualify a
2784                  * component if necessary.
2785                  */
2786                 int cx1 = (x-1) >> 1, cx2 = x >> 1;
2787                 int cy1 = (y-1) >> 1, cy2 = y >> 1;
2788                 assert((cx1==cx2) ^ (cy1==cy2));
2789                 i = dsf_canonify(dsf, cy1*w+cx1);
2790                 if (i == dsf_canonify(dsf, cy2*w+cx2))
2791                     sqdata[i].valid = FALSE;
2792             }
2793         }
2794
2795     /*
2796      * And finally we test rotational symmetry: for each square in
2797      * the grid, find which component it's in, test that that
2798      * component also has a square in the symmetric position, and
2799      * disqualify it if it doesn't.
2800      */
2801     for (y = 0; y < h; y++)
2802         for (x = 0; x < w; x++) {
2803             int x2, y2;
2804
2805             i = dsf_canonify(dsf, y*w+x);
2806
2807             x2 = sqdata[i].cx - 1 - x;
2808             y2 = sqdata[i].cy - 1 - y;
2809             if (i != dsf_canonify(dsf, y2*w+x2))
2810                 sqdata[i].valid = FALSE;
2811         }
2812
2813     /*
2814      * That's it. We now have all the connected components marked
2815      * as valid or not valid. So now we return a `colours' array if
2816      * we were asked for one, and also we return an overall
2817      * true/false value depending on whether _every_ square in the
2818      * grid is part of a valid component.
2819      */
2820     ret = TRUE;
2821     for (i = 0; i < w*h; i++) {
2822         int ci = dsf_canonify(dsf, i);
2823         int thisok = sqdata[ci].valid;
2824         if (colours)
2825             colours[i] = thisok ? sqdata[ci].colour : 0;
2826         ret = ret && thisok;
2827     }
2828
2829     sfree(sqdata);
2830     if (free_dsf)
2831         sfree(dsf);
2832
2833     return ret;
2834 }
2835
2836 static game_state *execute_move(const game_state *state, const char *move)
2837 {
2838     int x, y, ax, ay, n, dx, dy;
2839     game_state *ret = dup_game(state);
2840     space *sp, *dot;
2841     int currently_solving = FALSE;
2842
2843     debug(("%s\n", move));
2844
2845     while (*move) {
2846         char c = *move;
2847         if (c == 'E' || c == 'U' || c == 'M'
2848 #ifdef EDITOR
2849             || c == 'D' || c == 'd'
2850 #endif
2851             ) {
2852             move++;
2853             if (sscanf(move, "%d,%d%n", &x, &y, &n) != 2 ||
2854                 !INUI(ret, x, y))
2855                 goto badmove;
2856
2857             sp = &SPACE(ret, x, y);
2858 #ifdef EDITOR
2859             if (c == 'D' || c == 'd') {
2860                 unsigned int currf, newf, maskf;
2861
2862                 if (!dot_is_possible(ret, sp, 1)) goto badmove;
2863
2864                 newf = F_DOT | (c == 'd' ? F_DOT_BLACK : 0);
2865                 currf = GRID(ret, grid, x, y).flags;
2866                 maskf = F_DOT | F_DOT_BLACK;
2867                 /* if we clicked 'white dot':
2868                  *   white --> empty, empty --> white, black --> white.
2869                  * if we clicked 'black dot':
2870                  *   black --> empty, empty --> black, white --> black.
2871                  */
2872                 if (currf & maskf) {
2873                     sp->flags &= ~maskf;
2874                     if ((currf & maskf) != newf)
2875                         sp->flags |= newf;
2876                 } else
2877                     sp->flags |= newf;
2878                 sp->nassoc = 0; /* edit-mode disallows associations. */
2879                 game_update_dots(ret);
2880             } else
2881 #endif
2882                    if (c == 'E') {
2883                 if (sp->type != s_edge) goto badmove;
2884                 sp->flags ^= F_EDGE_SET;
2885             } else if (c == 'U') {
2886                 if (sp->type != s_tile || !(sp->flags & F_TILE_ASSOC))
2887                     goto badmove;
2888                 /* The solver doesn't assume we'll mirror things */
2889                 if (currently_solving)
2890                     remove_assoc(ret, sp);
2891                 else
2892                     remove_assoc_with_opposite(ret, sp);
2893             } else if (c == 'M') {
2894                 if (!(sp->flags & F_DOT)) goto badmove;
2895                 sp->flags ^= F_DOT_HOLD;
2896             }
2897             move += n;
2898         } else if (c == 'A' || c == 'a') {
2899             move++;
2900             if (sscanf(move, "%d,%d,%d,%d%n", &x, &y, &ax, &ay, &n) != 4 ||
2901                 x < 1 || y < 1 || x >= (ret->sx-1) || y >= (ret->sy-1) ||
2902                 ax < 1 || ay < 1 || ax >= (ret->sx-1) || ay >= (ret->sy-1))
2903                 goto badmove;
2904
2905             dot = &GRID(ret, grid, ax, ay);
2906             if (!(dot->flags & F_DOT))goto badmove;
2907             if (dot->flags & F_DOT_HOLD) goto badmove;
2908
2909             for (dx = -1; dx <= 1; dx++) {
2910                 for (dy = -1; dy <= 1; dy++) {
2911                     sp = &GRID(ret, grid, x+dx, y+dy);
2912                     if (sp->type != s_tile) continue;
2913                     if (sp->flags & F_TILE_ASSOC) {
2914                         space *dot = &SPACE(ret, sp->dotx, sp->doty);
2915                         if (dot->flags & F_DOT_HOLD) continue;
2916                     }
2917                     /* The solver doesn't assume we'll mirror things */
2918                     if (currently_solving)
2919                         add_assoc(ret, sp, dot);
2920                     else
2921                         add_assoc_with_opposite(ret, sp, dot);
2922                 }
2923             }
2924             move += n;
2925 #ifdef EDITOR
2926         } else if (c == 'C') {
2927             move++;
2928             clear_game(ret, 1);
2929 #endif
2930         } else if (c == 'S') {
2931             move++;
2932             ret->used_solve = 1;
2933             currently_solving = TRUE;
2934         } else
2935             goto badmove;
2936
2937         if (*move == ';')
2938             move++;
2939         else if (*move)
2940             goto badmove;
2941     }
2942     if (check_complete(ret, NULL, NULL))
2943         ret->completed = 1;
2944     return ret;
2945
2946 badmove:
2947     free_game(ret);
2948     return NULL;
2949 }
2950
2951 /* ----------------------------------------------------------------------
2952  * Drawing routines.
2953  */
2954
2955 /* Lines will be much smaller size than squares; say, 1/8 the size?
2956  *
2957  * Need a 'top-left corner of location XxY' to take this into account;
2958  * alternaticaly, that could give the middle of that location, and the
2959  * drawing code would just know the expected dimensions.
2960  *
2961  * We also need something to take a click and work out what it was
2962  * we were interested in. Clicking on vertices is required because
2963  * we may want to drag from them, for example.
2964  */
2965
2966 static void game_compute_size(const game_params *params, int sz,
2967                               int *x, int *y)
2968 {
2969     struct { int tilesize, w, h; } ads, *ds = &ads;
2970
2971     ds->tilesize = sz;
2972     ds->w = params->w;
2973     ds->h = params->h;
2974
2975     *x = DRAW_WIDTH;
2976     *y = DRAW_HEIGHT;
2977 }
2978
2979 static void game_set_size(drawing *dr, game_drawstate *ds,
2980                           const game_params *params, int sz)
2981 {
2982     ds->tilesize = sz;
2983
2984     assert(TILE_SIZE > 0);
2985
2986     assert(!ds->bl);
2987     ds->bl = blitter_new(dr, TILE_SIZE, TILE_SIZE);
2988
2989     assert(!ds->blmirror);
2990     ds->blmirror = blitter_new(dr, TILE_SIZE, TILE_SIZE);
2991
2992     assert(!ds->cur_bl);
2993     ds->cur_bl = blitter_new(dr, TILE_SIZE, TILE_SIZE);
2994 }
2995
2996 static float *game_colours(frontend *fe, int *ncolours)
2997 {
2998     float *ret = snewn(3 * NCOLOURS, float);
2999     int i;
3000
3001     /*
3002      * We call game_mkhighlight to ensure the background colour
3003      * isn't completely white. We don't actually use the high- and
3004      * lowlight colours it generates.
3005      */
3006     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_WHITEBG, COL_BLACKBG);
3007
3008     for (i = 0; i < 3; i++) {
3009         /*
3010          * Currently, white dots and white-background squares are
3011          * both pure white.
3012          */
3013         ret[COL_WHITEDOT * 3 + i] = 1.0F;
3014         ret[COL_WHITEBG * 3 + i] = 1.0F;
3015
3016         /*
3017          * But black-background squares are a dark grey, whereas
3018          * black dots are really black.
3019          */
3020         ret[COL_BLACKDOT * 3 + i] = 0.0F;
3021         ret[COL_BLACKBG * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.3F;
3022
3023         /*
3024          * In unfilled squares, we draw a faint gridwork.
3025          */
3026         ret[COL_GRID * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.8F;
3027
3028         /*
3029          * Edges and arrows are filled in in pure black.
3030          */
3031         ret[COL_EDGE * 3 + i] = 0.0F;
3032         ret[COL_ARROW * 3 + i] = 0.0F;
3033     }
3034
3035 #ifdef EDITOR
3036     /* tinge the edit background to bluey */
3037     ret[COL_BACKGROUND * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
3038     ret[COL_BACKGROUND * 3 + 1] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
3039     ret[COL_BACKGROUND * 3 + 2] = min(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
3040 #endif
3041
3042     ret[COL_CURSOR * 3 + 0] = min(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
3043     ret[COL_CURSOR * 3 + 1] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
3044     ret[COL_CURSOR * 3 + 2] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
3045
3046     *ncolours = NCOLOURS;
3047     return ret;
3048 }
3049
3050 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
3051 {
3052     struct game_drawstate *ds = snew(struct game_drawstate);
3053     int i;
3054
3055     ds->started = 0;
3056     ds->w = state->w;
3057     ds->h = state->h;
3058
3059     ds->grid = snewn(ds->w*ds->h, unsigned long);
3060     for (i = 0; i < ds->w*ds->h; i++)
3061         ds->grid[i] = 0xFFFFFFFFUL;
3062     ds->dx = snewn(ds->w*ds->h, int);
3063     ds->dy = snewn(ds->w*ds->h, int);
3064
3065     ds->bl = NULL;
3066     ds->blmirror = NULL;
3067     ds->dragging = FALSE;
3068     ds->dragx = ds->dragy = 0;
3069
3070     ds->colour_scratch = snewn(ds->w * ds->h, int);
3071
3072     ds->cur_bl = NULL;
3073     ds->cx = ds->cy = 0;
3074     ds->cur_visible = 0;
3075
3076     return ds;
3077 }
3078
3079 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
3080 {
3081     if (ds->cur_bl) blitter_free(dr, ds->cur_bl);
3082     sfree(ds->colour_scratch);
3083     if (ds->blmirror) blitter_free(dr, ds->blmirror);
3084     if (ds->bl) blitter_free(dr, ds->bl);
3085     sfree(ds->dx);
3086     sfree(ds->dy);
3087     sfree(ds->grid);
3088     sfree(ds);
3089 }
3090
3091 #define DRAW_EDGE_L    0x0001
3092 #define DRAW_EDGE_R    0x0002
3093 #define DRAW_EDGE_U    0x0004
3094 #define DRAW_EDGE_D    0x0008
3095 #define DRAW_CORNER_UL 0x0010
3096 #define DRAW_CORNER_UR 0x0020
3097 #define DRAW_CORNER_DL 0x0040
3098 #define DRAW_CORNER_DR 0x0080
3099 #define DRAW_WHITE     0x0100
3100 #define DRAW_BLACK     0x0200
3101 #define DRAW_ARROW     0x0400
3102 #define DRAW_CURSOR    0x0800
3103 #define DOT_SHIFT_C    12
3104 #define DOT_SHIFT_M    2
3105 #define DOT_WHITE      1UL
3106 #define DOT_BLACK      2UL
3107
3108 /*
3109  * Draw an arrow centred on (cx,cy), pointing in the direction
3110  * (ddx,ddy). (I.e. pointing at the point (cx+ddx, cy+ddy).
3111  */
3112 static void draw_arrow(drawing *dr, game_drawstate *ds,
3113                        int cx, int cy, int ddx, int ddy, int col)
3114 {
3115     float vlen = (float)sqrt(ddx*ddx+ddy*ddy);
3116     float xdx = ddx/vlen, xdy = ddy/vlen;
3117     float ydx = -xdy, ydy = xdx;
3118     int e1x = cx + (int)(xdx*TILE_SIZE/3), e1y = cy + (int)(xdy*TILE_SIZE/3);
3119     int e2x = cx - (int)(xdx*TILE_SIZE/3), e2y = cy - (int)(xdy*TILE_SIZE/3);
3120     int adx = (int)((ydx-xdx)*TILE_SIZE/8), ady = (int)((ydy-xdy)*TILE_SIZE/8);
3121     int adx2 = (int)((-ydx-xdx)*TILE_SIZE/8), ady2 = (int)((-ydy-xdy)*TILE_SIZE/8);
3122
3123     draw_line(dr, e1x, e1y, e2x, e2y, col);
3124     draw_line(dr, e1x, e1y, e1x+adx, e1y+ady, col);
3125     draw_line(dr, e1x, e1y, e1x+adx2, e1y+ady2, col);
3126 }
3127
3128 static void draw_square(drawing *dr, game_drawstate *ds, int x, int y,
3129                         unsigned long flags, int ddx, int ddy)
3130 {
3131     int lx = COORD(x), ly = COORD(y);
3132     int dx, dy;
3133     int gridcol;
3134
3135     clip(dr, lx, ly, TILE_SIZE, TILE_SIZE);
3136
3137     /*
3138      * Draw the tile background.
3139      */
3140     draw_rect(dr, lx, ly, TILE_SIZE, TILE_SIZE,
3141               (flags & DRAW_WHITE ? COL_WHITEBG :
3142                flags & DRAW_BLACK ? COL_BLACKBG : COL_BACKGROUND));
3143
3144     /*
3145      * Draw the grid.
3146      */
3147     gridcol = (flags & DRAW_BLACK ? COL_BLACKDOT : COL_GRID);
3148     draw_rect(dr, lx, ly, 1, TILE_SIZE, gridcol);
3149     draw_rect(dr, lx, ly, TILE_SIZE, 1, gridcol);
3150
3151     /*
3152      * Draw the arrow, if present, or the cursor, if here.
3153      */
3154     if (flags & DRAW_ARROW)
3155         draw_arrow(dr, ds, lx + TILE_SIZE/2, ly + TILE_SIZE/2, ddx, ddy,
3156                    (flags & DRAW_CURSOR) ? COL_CURSOR : COL_ARROW);
3157     else if (flags & DRAW_CURSOR)
3158         draw_rect_outline(dr,
3159                           lx + TILE_SIZE/2 - CURSOR_SIZE,
3160                           ly + TILE_SIZE/2 - CURSOR_SIZE,
3161                           2*CURSOR_SIZE+1, 2*CURSOR_SIZE+1,
3162                           COL_CURSOR);
3163
3164     /*
3165      * Draw the edges.
3166      */
3167     if (flags & DRAW_EDGE_L)
3168         draw_rect(dr, lx, ly, EDGE_THICKNESS, TILE_SIZE, COL_EDGE);
3169     if (flags & DRAW_EDGE_R)
3170         draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1, ly,
3171                   EDGE_THICKNESS - 1, TILE_SIZE, COL_EDGE);
3172     if (flags & DRAW_EDGE_U)
3173         draw_rect(dr, lx, ly, TILE_SIZE, EDGE_THICKNESS, COL_EDGE);
3174     if (flags & DRAW_EDGE_D)
3175         draw_rect(dr, lx, ly + TILE_SIZE - EDGE_THICKNESS + 1,
3176                   TILE_SIZE, EDGE_THICKNESS - 1, COL_EDGE);
3177     if (flags & DRAW_CORNER_UL)
3178         draw_rect(dr, lx, ly, EDGE_THICKNESS, EDGE_THICKNESS, COL_EDGE);
3179     if (flags & DRAW_CORNER_UR)
3180         draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1, ly,
3181                   EDGE_THICKNESS - 1, EDGE_THICKNESS, COL_EDGE);
3182     if (flags & DRAW_CORNER_DL)
3183         draw_rect(dr, lx, ly + TILE_SIZE - EDGE_THICKNESS + 1,
3184                   EDGE_THICKNESS, EDGE_THICKNESS - 1, COL_EDGE);
3185     if (flags & DRAW_CORNER_DR)
3186         draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1,
3187                   ly + TILE_SIZE - EDGE_THICKNESS + 1,
3188                   EDGE_THICKNESS - 1, EDGE_THICKNESS - 1, COL_EDGE);
3189
3190     /*
3191      * Draw the dots.
3192      */
3193     for (dy = 0; dy < 3; dy++)
3194         for (dx = 0; dx < 3; dx++) {
3195             int dotval = (flags >> (DOT_SHIFT_C + DOT_SHIFT_M*(dy*3+dx)));
3196             dotval &= (1 << DOT_SHIFT_M)-1;
3197
3198             if (dotval)
3199                 draw_circle(dr, lx+dx*TILE_SIZE/2, ly+dy*TILE_SIZE/2,
3200                             DOT_SIZE,
3201                             (dotval == 1 ? COL_WHITEDOT : COL_BLACKDOT),
3202                             COL_BLACKDOT);
3203         }
3204
3205     unclip(dr);
3206     draw_update(dr, lx, ly, TILE_SIZE, TILE_SIZE);
3207 }
3208
3209 static void calculate_opposite_point(const game_ui *ui,
3210                                      const game_drawstate *ds, const int x,
3211                                      const int y, int *oppositex,
3212                                      int *oppositey)
3213 {
3214     /* oppositex - dotx = dotx - x <=> oppositex = 2 * dotx - x */
3215     *oppositex = 2 * SCOORD(ui->dotx) - x;
3216     *oppositey = 2 * SCOORD(ui->doty) - y;
3217 }
3218
3219 static void game_redraw(drawing *dr, game_drawstate *ds,
3220                         const game_state *oldstate, const game_state *state,
3221                         int dir, const game_ui *ui,
3222                         float animtime, float flashtime)
3223 {
3224     int w = ds->w, h = ds->h;
3225     int x, y, flashing = FALSE;
3226     int oppx, oppy;
3227
3228     if (flashtime > 0) {
3229         int frame = (int)(flashtime / FLASH_TIME);
3230         flashing = (frame % 2 == 0);
3231     }
3232
3233     if (ds->dragging) {
3234         assert(ds->bl);
3235         assert(ds->blmirror);
3236         calculate_opposite_point(ui, ds, ds->dragx + TILE_SIZE/2,
3237                                  ds->dragy + TILE_SIZE/2, &oppx, &oppy);
3238         oppx -= TILE_SIZE/2;
3239         oppy -= TILE_SIZE/2;
3240         blitter_load(dr, ds->bl, ds->dragx, ds->dragy);
3241         draw_update(dr, ds->dragx, ds->dragy, TILE_SIZE, TILE_SIZE);
3242         blitter_load(dr, ds->blmirror, oppx, oppy);
3243         draw_update(dr, oppx, oppy, TILE_SIZE, TILE_SIZE);
3244         ds->dragging = FALSE;
3245     }
3246     if (ds->cur_visible) {
3247         assert(ds->cur_bl);
3248         blitter_load(dr, ds->cur_bl, ds->cx, ds->cy);
3249         draw_update(dr, ds->cx, ds->cy, CURSOR_SIZE*2+1, CURSOR_SIZE*2+1);
3250         ds->cur_visible = FALSE;
3251     }
3252
3253     if (!ds->started) {
3254         draw_rect(dr, 0, 0, DRAW_WIDTH, DRAW_HEIGHT, COL_BACKGROUND);
3255         draw_rect(dr, BORDER - EDGE_THICKNESS + 1, BORDER - EDGE_THICKNESS + 1,
3256                   w*TILE_SIZE + EDGE_THICKNESS*2 - 1,
3257                   h*TILE_SIZE + EDGE_THICKNESS*2 - 1, COL_EDGE);
3258         draw_update(dr, 0, 0, DRAW_WIDTH, DRAW_HEIGHT);
3259         ds->started = TRUE;
3260     }
3261
3262     check_complete(state, NULL, ds->colour_scratch);
3263
3264     for (y = 0; y < h; y++)
3265         for (x = 0; x < w; x++) {
3266             unsigned long flags = 0;
3267             int ddx = 0, ddy = 0;
3268             space *sp, *opp;
3269             int dx, dy;
3270
3271             /*
3272              * Set up the flags for this square. Firstly, see if we
3273              * have edges.
3274              */
3275             if (SPACE(state, x*2, y*2+1).flags & F_EDGE_SET)
3276                 flags |= DRAW_EDGE_L;
3277             if (SPACE(state, x*2+2, y*2+1).flags & F_EDGE_SET)
3278                 flags |= DRAW_EDGE_R;
3279             if (SPACE(state, x*2+1, y*2).flags & F_EDGE_SET)
3280                 flags |= DRAW_EDGE_U;
3281             if (SPACE(state, x*2+1, y*2+2).flags & F_EDGE_SET)
3282                 flags |= DRAW_EDGE_D;
3283
3284             /*
3285              * Also, mark corners of neighbouring edges.
3286              */
3287             if ((x > 0 && SPACE(state, x*2-1, y*2).flags & F_EDGE_SET) ||
3288                 (y > 0 && SPACE(state, x*2, y*2-1).flags & F_EDGE_SET))
3289                 flags |= DRAW_CORNER_UL;
3290             if ((x+1 < w && SPACE(state, x*2+3, y*2).flags & F_EDGE_SET) ||
3291                 (y > 0 && SPACE(state, x*2+2, y*2-1).flags & F_EDGE_SET))
3292                 flags |= DRAW_CORNER_UR;
3293             if ((x > 0 && SPACE(state, x*2-1, y*2+2).flags & F_EDGE_SET) ||
3294                 (y+1 < h && SPACE(state, x*2, y*2+3).flags & F_EDGE_SET))
3295                 flags |= DRAW_CORNER_DL;
3296             if ((x+1 < w && SPACE(state, x*2+3, y*2+2).flags & F_EDGE_SET) ||
3297                 (y+1 < h && SPACE(state, x*2+2, y*2+3).flags & F_EDGE_SET))
3298                 flags |= DRAW_CORNER_DR;
3299
3300             /*
3301              * If this square is part of a valid region, paint it
3302              * that region's colour. Exception: if we're flashing,
3303              * everything goes briefly back to background colour.
3304              */
3305             sp = &SPACE(state, x*2+1, y*2+1);
3306             if (sp->flags & F_TILE_ASSOC) {
3307                 opp = tile_opposite(state, sp);
3308             } else {
3309                 opp = NULL;
3310             }
3311             if (ds->colour_scratch[y*w+x] && !flashing) {
3312                 flags |= (ds->colour_scratch[y*w+x] == 2 ?
3313                           DRAW_BLACK : DRAW_WHITE);
3314             }
3315
3316             /*
3317              * If this square is associated with a dot but it isn't
3318              * part of a valid region, draw an arrow in it pointing
3319              * in the direction of that dot.
3320              * 
3321              * Exception: if this is the source point of an active
3322              * drag, we don't draw the arrow.
3323              */
3324             if ((sp->flags & F_TILE_ASSOC) && !ds->colour_scratch[y*w+x]) {
3325                 if (ui->dragging && ui->srcx == x*2+1 && ui->srcy == y*2+1) {
3326                     /* tile is the source, don't do it */
3327                 } else if (ui->dragging && opp && ui->srcx == opp->x && ui->srcy == opp->y) {
3328                     /* opposite tile is the source, don't do it */
3329                 } else if (sp->doty != y*2+1 || sp->dotx != x*2+1) {
3330                     flags |= DRAW_ARROW;
3331                     ddy = sp->doty - (y*2+1);
3332                     ddx = sp->dotx - (x*2+1);
3333                 }
3334             }
3335
3336             /*
3337              * Now go through the nine possible places we could
3338              * have dots.
3339              */
3340             for (dy = 0; dy < 3; dy++)
3341                 for (dx = 0; dx < 3; dx++) {
3342                     sp = &SPACE(state, x*2+dx, y*2+dy);
3343                     if (sp->flags & F_DOT) {
3344                         unsigned long dotval = (sp->flags & F_DOT_BLACK ?
3345                                                 DOT_BLACK : DOT_WHITE);
3346                         flags |= dotval << (DOT_SHIFT_C +
3347                                             DOT_SHIFT_M*(dy*3+dx));
3348                     }
3349                 }
3350
3351             /*
3352              * Now work out if we have to draw a cursor for this square;
3353              * cursors-on-lines are taken care of below.
3354              */
3355             if (ui->cur_visible &&
3356                 ui->cur_x == x*2+1 && ui->cur_y == y*2+1 &&
3357                 !(SPACE(state, x*2+1, y*2+1).flags & F_DOT))
3358                 flags |= DRAW_CURSOR;
3359
3360             /*
3361              * Now we have everything we're going to need. Draw the
3362              * square.
3363              */
3364             if (ds->grid[y*w+x] != flags ||
3365                 ds->dx[y*w+x] != ddx ||
3366                 ds->dy[y*w+x] != ddy) {
3367                 draw_square(dr, ds, x, y, flags, ddx, ddy);
3368                 ds->grid[y*w+x] = flags;
3369                 ds->dx[y*w+x] = ddx;
3370                 ds->dy[y*w+x] = ddy;
3371             }
3372         }
3373
3374     /*
3375      * Draw a cursor. This secondary blitter is much less invasive than trying
3376      * to fix up all of the rest of the code with sufficient flags to be able to
3377      * display this sensibly.
3378      */
3379     if (ui->cur_visible) {
3380         space *sp = &SPACE(state, ui->cur_x, ui->cur_y);
3381         ds->cur_visible = TRUE;
3382         ds->cx = SCOORD(ui->cur_x) - CURSOR_SIZE;
3383         ds->cy = SCOORD(ui->cur_y) - CURSOR_SIZE;
3384         blitter_save(dr, ds->cur_bl, ds->cx, ds->cy);
3385         if (sp->flags & F_DOT) {
3386             /* draw a red dot (over the top of whatever would be there already) */
3387             draw_circle(dr, SCOORD(ui->cur_x), SCOORD(ui->cur_y), DOT_SIZE,
3388                         COL_CURSOR, COL_BLACKDOT);
3389         } else if (sp->type != s_tile) {
3390             /* draw an edge/vertex square; tile cursors are dealt with above. */
3391             int dx = (ui->cur_x % 2) ? CURSOR_SIZE : CURSOR_SIZE/3;
3392             int dy = (ui->cur_y % 2) ? CURSOR_SIZE : CURSOR_SIZE/3;
3393             int x1 = SCOORD(ui->cur_x)-dx, y1 = SCOORD(ui->cur_y)-dy;
3394             int xs = dx*2+1, ys = dy*2+1;
3395
3396             draw_rect(dr, x1, y1, xs, ys, COL_CURSOR);
3397         }
3398         draw_update(dr, ds->cx, ds->cy, CURSOR_SIZE*2+1, CURSOR_SIZE*2+1);
3399     }
3400
3401     if (ui->dragging) {
3402         ds->dragging = TRUE;
3403         ds->dragx = ui->dx - TILE_SIZE/2;
3404         ds->dragy = ui->dy - TILE_SIZE/2;
3405         calculate_opposite_point(ui, ds, ui->dx, ui->dy, &oppx, &oppy);
3406         blitter_save(dr, ds->bl, ds->dragx, ds->dragy);
3407         blitter_save(dr, ds->blmirror, oppx - TILE_SIZE/2, oppy - TILE_SIZE/2);
3408         draw_arrow(dr, ds, ui->dx, ui->dy, SCOORD(ui->dotx) - ui->dx,
3409                    SCOORD(ui->doty) - ui->dy, COL_ARROW);
3410         draw_arrow(dr, ds, oppx, oppy, SCOORD(ui->dotx) - oppx,
3411                    SCOORD(ui->doty) - oppy, COL_ARROW);
3412     }
3413 #ifdef EDITOR
3414     {
3415         char buf[256];
3416         if (state->cdiff != -1)
3417             sprintf(buf, "Puzzle is %s.", galaxies_diffnames[state->cdiff]);
3418         else
3419             buf[0] = '\0';
3420         status_bar(dr, buf);
3421     }
3422 #endif
3423 }
3424
3425 static float game_anim_length(const game_state *oldstate,
3426                               const game_state *newstate, int dir, game_ui *ui)
3427 {
3428     return 0.0F;
3429 }
3430
3431 static float game_flash_length(const game_state *oldstate,
3432                                const game_state *newstate, int dir, game_ui *ui)
3433 {
3434     if ((!oldstate->completed && newstate->completed) &&
3435         !(newstate->used_solve))
3436         return 3 * FLASH_TIME;
3437     else
3438         return 0.0F;
3439 }
3440
3441 static int game_status(const game_state *state)
3442 {
3443     return state->completed ? +1 : 0;
3444 }
3445
3446 static int game_timing_state(const game_state *state, game_ui *ui)
3447 {
3448     return TRUE;
3449 }
3450
3451 #ifndef EDITOR
3452 static void game_print_size(const game_params *params, float *x, float *y)
3453 {
3454    int pw, ph;
3455
3456    /*
3457     * 8mm squares by default. (There isn't all that much detail
3458     * that needs to go in each square.)
3459     */
3460    game_compute_size(params, 800, &pw, &ph);
3461    *x = pw / 100.0F;
3462    *y = ph / 100.0F;
3463 }
3464
3465 static void game_print(drawing *dr, const game_state *state, int sz)
3466 {
3467     int w = state->w, h = state->h;
3468     int white, black, blackish;
3469     int x, y, i, j;
3470     int *colours, *dsf;
3471     int *coords = NULL;
3472     int ncoords = 0, coordsize = 0;
3473
3474     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3475     game_drawstate ads, *ds = &ads;
3476     ds->tilesize = sz;
3477
3478     white = print_mono_colour(dr, 1);
3479     black = print_mono_colour(dr, 0);
3480     blackish = print_hatched_colour(dr, HATCH_X);
3481
3482     /*
3483      * Get the completion information.
3484      */
3485     dsf = snewn(w * h, int);
3486     colours = snewn(w * h, int);
3487     check_complete(state, dsf, colours);
3488
3489     /*
3490      * Draw the grid.
3491      */
3492     print_line_width(dr, TILE_SIZE / 64);
3493     for (x = 1; x < w; x++)
3494         draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h), black);
3495     for (y = 1; y < h; y++)
3496         draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y), black);
3497
3498     /*
3499      * Shade the completed regions. Just in case any particular
3500      * printing platform deals badly with adjacent
3501      * similarly-hatched regions, we'll fill each one as a single
3502      * polygon.
3503      */
3504     for (i = 0; i < w*h; i++) {
3505         j = dsf_canonify(dsf, i);
3506         if (colours[j] != 0) {
3507             int dx, dy, t;
3508
3509             /*
3510              * This is the first square we've run into belonging to
3511              * this polyomino, which means an edge of the polyomino
3512              * is certain to be to our left. (After we finish
3513              * tracing round it, we'll set the colours[] entry to
3514              * zero to prevent accidentally doing it again.)
3515              */
3516
3517             x = i % w;
3518             y = i / w;
3519             dx = -1;
3520             dy = 0;
3521             ncoords = 0;
3522             while (1) {
3523                 /*
3524                  * We are currently sitting on square (x,y), which
3525                  * we know to be in our polyomino, and we also know
3526                  * that (x+dx,y+dy) is not. The way I visualise
3527                  * this is that we're standing to the right of a
3528                  * boundary line, stretching our left arm out to
3529                  * point to the exterior square on the far side.
3530                  */
3531
3532                 /*
3533                  * First, check if we've gone round the entire
3534                  * polyomino.
3535                  */
3536                 if (ncoords > 0 &&
3537                     (x == i%w && y == i/w && dx == -1 && dy == 0))
3538                     break;
3539
3540                 /*
3541                  * Add to our coordinate list the coordinate
3542                  * backwards and to the left of where we are.
3543                  */
3544                 if (ncoords + 2 > coordsize) {
3545                     coordsize = (ncoords * 3 / 2) + 64;
3546                     coords = sresize(coords, coordsize, int);
3547                 }
3548                 coords[ncoords++] = COORD((2*x+1 + dx + dy) / 2);
3549                 coords[ncoords++] = COORD((2*y+1 + dy - dx) / 2);
3550
3551                 /*
3552                  * Follow the edge round. If the square directly in
3553                  * front of us is not part of the polyomino, we
3554                  * turn right; if it is and so is the square in
3555                  * front of (x+dx,y+dy), we turn left; otherwise we
3556                  * go straight on.
3557                  */
3558                 if (x-dy < 0 || x-dy >= w || y+dx < 0 || y+dx >= h ||
3559                     dsf_canonify(dsf, (y+dx)*w+(x-dy)) != j) {
3560                     /* Turn right. */
3561                     t = dx;
3562                     dx = -dy;
3563                     dy = t;
3564                 } else if (x+dx-dy >= 0 && x+dx-dy < w &&
3565                            y+dy+dx >= 0 && y+dy+dx < h &&
3566                            dsf_canonify(dsf, (y+dy+dx)*w+(x+dx-dy)) == j) {
3567                     /* Turn left. */
3568                     x += dx;
3569                     y += dy;
3570                     t = dx;
3571                     dx = dy;
3572                     dy = -t;
3573                     x -= dx;
3574                     y -= dy;
3575                 } else {
3576                     /* Straight on. */
3577                     x -= dy;
3578                     y += dx;
3579                 }
3580             }
3581
3582             /*
3583              * Now we have our polygon complete, so fill it.
3584              */
3585             draw_polygon(dr, coords, ncoords/2,
3586                          colours[j] == 2 ? blackish : -1, black);
3587
3588             /*
3589              * And mark this polyomino as done.
3590              */
3591             colours[j] = 0;
3592         }
3593     }
3594
3595     /*
3596      * Draw the edges.
3597      */
3598     for (y = 0; y <= h; y++)
3599         for (x = 0; x <= w; x++) {
3600             if (x < w && SPACE(state, x*2+1, y*2).flags & F_EDGE_SET)
3601                 draw_rect(dr, COORD(x)-EDGE_THICKNESS, COORD(y)-EDGE_THICKNESS,
3602                           EDGE_THICKNESS * 2 + TILE_SIZE, EDGE_THICKNESS * 2,
3603                           black);
3604             if (y < h && SPACE(state, x*2, y*2+1).flags & F_EDGE_SET)
3605                 draw_rect(dr, COORD(x)-EDGE_THICKNESS, COORD(y)-EDGE_THICKNESS,
3606                           EDGE_THICKNESS * 2, EDGE_THICKNESS * 2 + TILE_SIZE,
3607                           black);
3608         }
3609
3610     /*
3611      * Draw the dots.
3612      */
3613     for (y = 0; y <= 2*h; y++)
3614         for (x = 0; x <= 2*w; x++)
3615             if (SPACE(state, x, y).flags & F_DOT) {
3616                 draw_circle(dr, (int)COORD(x/2.0), (int)COORD(y/2.0), DOT_SIZE,
3617                             (SPACE(state, x, y).flags & F_DOT_BLACK ?
3618                              black : white), black);
3619             }
3620
3621     sfree(dsf);
3622     sfree(colours);
3623     sfree(coords);
3624 }
3625 #endif
3626
3627 #ifdef COMBINED
3628 #define thegame galaxies
3629 #endif
3630
3631 const struct game thegame = {
3632     "Galaxies", "games.galaxies", "galaxies",
3633     default_params,
3634     game_fetch_preset,
3635     decode_params,
3636     encode_params,
3637     free_params,
3638     dup_params,
3639     TRUE, game_configure, custom_params,
3640     validate_params,
3641     new_game_desc,
3642     validate_desc,
3643     new_game,
3644     dup_game,
3645     free_game,
3646 #ifdef EDITOR
3647     FALSE, NULL,
3648 #else
3649     TRUE, solve_game,
3650 #endif
3651     TRUE, game_can_format_as_text_now, game_text_format,
3652     new_ui,
3653     free_ui,
3654     encode_ui,
3655     decode_ui,
3656     game_changed_state,
3657     interpret_move,
3658     execute_move,
3659     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3660     game_colours,
3661     game_new_drawstate,
3662     game_free_drawstate,
3663     game_redraw,
3664     game_anim_length,
3665     game_flash_length,
3666     game_status,
3667 #ifdef EDITOR
3668     FALSE, FALSE, NULL, NULL,
3669     TRUE,                              /* wants_statusbar */
3670 #else
3671     TRUE, FALSE, game_print_size, game_print,
3672     FALSE,                             /* wants_statusbar */
3673 #endif
3674     FALSE, game_timing_state,
3675     REQUIRE_RBUTTON,                   /* flags */
3676 };
3677
3678 #ifdef STANDALONE_SOLVER
3679
3680 const char *quis;
3681
3682 #include <time.h>
3683
3684 static void usage_exit(const char *msg)
3685 {
3686     if (msg)
3687         fprintf(stderr, "%s: %s\n", quis, msg);
3688     fprintf(stderr, "Usage: %s [--seed SEED] --soak <params> | [game_id [game_id ...]]\n", quis);
3689     exit(1);
3690 }
3691
3692 static void dump_state(game_state *state)
3693 {
3694     char *temp = game_text_format(state);
3695     printf("%s\n", temp);
3696     sfree(temp);
3697 }
3698
3699 static int gen(game_params *p, random_state *rs, int debug)
3700 {
3701     char *desc;
3702     int diff;
3703     game_state *state;
3704
3705 #ifndef DEBUGGING
3706     solver_show_working = debug;
3707 #endif
3708     printf("Generating a %dx%d %s puzzle.\n",
3709            p->w, p->h, galaxies_diffnames[p->diff]);
3710
3711     desc = new_game_desc(p, rs, NULL, 0);
3712     state = new_game(NULL, p, desc);
3713     dump_state(state);
3714
3715     diff = solver_state(state, DIFF_UNREASONABLE);
3716     printf("Generated %s game %dx%d:%s\n",
3717            galaxies_diffnames[diff], p->w, p->h, desc);
3718     dump_state(state);
3719
3720     free_game(state);
3721     sfree(desc);
3722
3723     return diff;
3724 }
3725
3726 static void soak(game_params *p, random_state *rs)
3727 {
3728     time_t tt_start, tt_now, tt_last;
3729     char *desc;
3730     game_state *st;
3731     int diff, n = 0, i, diffs[DIFF_MAX], ndots = 0, nspaces = 0;
3732
3733 #ifndef DEBUGGING
3734     solver_show_working = 0;
3735 #endif
3736     tt_start = tt_now = time(NULL);
3737     for (i = 0; i < DIFF_MAX; i++) diffs[i] = 0;
3738     maxtries = 1;
3739
3740     printf("Soak-generating a %dx%d grid, max. diff %s.\n",
3741            p->w, p->h, galaxies_diffnames[p->diff]);
3742     printf("   [");
3743     for (i = 0; i < DIFF_MAX; i++)
3744         printf("%s%s", (i == 0) ? "" : ", ", galaxies_diffnames[i]);
3745     printf("]\n");
3746
3747     while (1) {
3748         desc = new_game_desc(p, rs, NULL, 0);
3749         st = new_game(NULL, p, desc);
3750         diff = solver_state(st, p->diff);
3751         nspaces += st->w*st->h;
3752         for (i = 0; i < st->sx*st->sy; i++)
3753             if (st->grid[i].flags & F_DOT) ndots++;
3754         free_game(st);
3755         sfree(desc);
3756
3757         diffs[diff]++;
3758         n++;
3759         tt_last = time(NULL);
3760         if (tt_last > tt_now) {
3761             tt_now = tt_last;
3762             printf("%d total, %3.1f/s, [",
3763                    n, (double)n / ((double)tt_now - tt_start));
3764             for (i = 0; i < DIFF_MAX; i++)
3765                 printf("%s%.1f%%", (i == 0) ? "" : ", ",
3766                        100.0 * ((double)diffs[i] / (double)n));
3767             printf("], %.1f%% dots\n",
3768                    100.0 * ((double)ndots / (double)nspaces));
3769         }
3770     }
3771 }
3772
3773 int main(int argc, char **argv)
3774 {
3775     game_params *p;
3776     char *id = NULL, *desc, *err;
3777     game_state *s;
3778     int diff, do_soak = 0, verbose = 0;
3779     random_state *rs;
3780     time_t seed = time(NULL);
3781
3782     quis = argv[0];
3783     while (--argc > 0) {
3784         char *p = *++argv;
3785         if (!strcmp(p, "-v")) {
3786             verbose = 1;
3787         } else if (!strcmp(p, "--seed")) {
3788             if (argc == 0) usage_exit("--seed needs an argument");
3789             seed = (time_t)atoi(*++argv);
3790             argc--;
3791         } else if (!strcmp(p, "--soak")) {
3792             do_soak = 1;
3793         } else if (*p == '-') {
3794             usage_exit("unrecognised option");
3795         } else {
3796             id = p;
3797         }
3798     }
3799
3800     maxtries = 50;
3801
3802     p = default_params();
3803     rs = random_new((void*)&seed, sizeof(time_t));
3804
3805     if (do_soak) {
3806         if (!id) usage_exit("need one argument for --soak");
3807         decode_params(p, *argv);
3808         soak(p, rs);
3809         return 0;
3810     }
3811
3812     if (!id) {
3813         while (1) {
3814             p->w = random_upto(rs, 15) + 3;
3815             p->h = random_upto(rs, 15) + 3;
3816             p->diff = random_upto(rs, DIFF_UNREASONABLE);
3817             diff = gen(p, rs, 0);
3818         }
3819         return 0;
3820     }
3821
3822     desc = strchr(id, ':');
3823     if (!desc) {
3824         decode_params(p, id);
3825         gen(p, rs, verbose);
3826     } else {
3827 #ifndef DEBUGGING
3828         solver_show_working = 1;
3829 #endif
3830         *desc++ = '\0';
3831         decode_params(p, id);
3832         err = validate_desc(p, desc);
3833         if (err) {
3834             fprintf(stderr, "%s: %s\n", argv[0], err);
3835             exit(1);
3836         }
3837         s = new_game(NULL, p, desc);
3838         diff = solver_state(s, DIFF_UNREASONABLE);
3839         dump_state(s);
3840         printf("Puzzle is %s.\n", galaxies_diffnames[diff]);
3841         free_game(s);
3842     }
3843
3844     free_params(p);
3845
3846     return 0;
3847 }
3848
3849 #endif
3850
3851 #ifdef STANDALONE_PICTURE_GENERATOR
3852
3853 /*
3854  * Main program for the standalone picture generator. To use it,
3855  * simply provide it with an XBM-format bitmap file (note XBM, not
3856  * XPM) on standard input, and it will output a game ID in return.
3857  * For example:
3858  *
3859  *   $ ./galaxiespicture < badly-drawn-cat.xbm
3860  *   11x11:eloMBLzFeEzLNMWifhaWYdDbixCymBbBMLoDdewGg
3861  *
3862  * If you want a puzzle with a non-standard difficulty level, pass
3863  * a partial parameters string as a command-line argument (e.g.
3864  * `./galaxiespicture du < foo.xbm', where `du' is the same suffix
3865  * which if it appeared in a random-seed game ID would set the
3866  * difficulty level to Unreasonable). However, be aware that if the
3867  * generator fails to produce an adequately difficult puzzle too
3868  * many times then it will give up and return an easier one (just
3869  * as it does during normal GUI play). To be sure you really have
3870  * the difficulty you asked for, use galaxiessolver to
3871  * double-check.
3872  * 
3873  * (Perhaps I ought to include an option to make this standalone
3874  * generator carry on looping until it really does get the right
3875  * difficulty. Hmmm.)
3876  */
3877
3878 #include <time.h>
3879
3880 int main(int argc, char **argv)
3881 {
3882     game_params *par;
3883     char *params, *desc;
3884     random_state *rs;
3885     time_t seed = time(NULL);
3886     char buf[4096];
3887     int i;
3888     int x, y;
3889
3890     par = default_params();
3891     if (argc > 1)
3892         decode_params(par, argv[1]);   /* get difficulty */
3893     par->w = par->h = -1;
3894
3895     /*
3896      * Now read an XBM file from standard input. This is simple and
3897      * hacky and will do very little error detection, so don't feed
3898      * it bogus data.
3899      */
3900     picture = NULL;
3901     x = y = 0;
3902     while (fgets(buf, sizeof(buf), stdin)) {
3903         buf[strcspn(buf, "\r\n")] = '\0';
3904         if (!strncmp(buf, "#define", 7)) {
3905             /*
3906              * Lines starting `#define' give the width and height.
3907              */
3908             char *num = buf + strlen(buf);
3909             char *symend;
3910
3911             while (num > buf && isdigit((unsigned char)num[-1]))
3912                 num--;
3913             symend = num;
3914             while (symend > buf && isspace((unsigned char)symend[-1]))
3915                 symend--;
3916
3917             if (symend-5 >= buf && !strncmp(symend-5, "width", 5))
3918                 par->w = atoi(num);
3919             else if (symend-6 >= buf && !strncmp(symend-6, "height", 6))
3920                 par->h = atoi(num);
3921         } else {
3922             /*
3923              * Otherwise, break the string up into words and take
3924              * any word of the form `0x' plus hex digits to be a
3925              * byte.
3926              */
3927             char *p, *wordstart;
3928
3929             if (!picture) {
3930                 if (par->w < 0 || par->h < 0) {
3931                     printf("failed to read width and height\n");
3932                     return 1;
3933                 }
3934                 picture = snewn(par->w * par->h, int);
3935                 for (i = 0; i < par->w * par->h; i++)
3936                     picture[i] = -1;
3937             }
3938
3939             p = buf;
3940             while (*p) {
3941                 while (*p && (*p == ',' || isspace((unsigned char)*p)))
3942                     p++;
3943                 wordstart = p;
3944                 while (*p && !(*p == ',' || *p == '}' ||
3945                                isspace((unsigned char)*p)))
3946                     p++;
3947                 if (*p)
3948                     *p++ = '\0';
3949
3950                 if (wordstart[0] == '0' &&
3951                     (wordstart[1] == 'x' || wordstart[1] == 'X') &&
3952                     !wordstart[2 + strspn(wordstart+2,
3953                                           "0123456789abcdefABCDEF")]) {
3954                     unsigned long byte = strtoul(wordstart+2, NULL, 16);
3955                     for (i = 0; i < 8; i++) {
3956                         int bit = (byte >> i) & 1;
3957                         if (y < par->h && x < par->w)
3958                             picture[y * par->w + x] = bit;
3959                         x++;
3960                     }
3961
3962                     if (x >= par->w) {
3963                         x = 0;
3964                         y++;
3965                     }
3966                 }
3967             }
3968         }
3969     }
3970
3971     for (i = 0; i < par->w * par->h; i++)
3972         if (picture[i] < 0) {
3973             fprintf(stderr, "failed to read enough bitmap data\n");
3974             return 1;
3975         }
3976
3977     rs = random_new((void*)&seed, sizeof(time_t));
3978
3979     desc = new_game_desc(par, rs, NULL, FALSE);
3980     params = encode_params(par, FALSE);
3981     printf("%s:%s\n", params, desc);
3982
3983     sfree(desc);
3984     sfree(params);
3985     free_params(par);
3986     random_free(rs);
3987
3988     return 0;
3989 }
3990
3991 #endif
3992
3993 /* vim: set shiftwidth=4 tabstop=8: */